mirror of
https://github.com/openai/codex.git
synced 2026-11-21 22:50:37 +00:00
Enable configuration server OAuth during app-server startup (#62867)
## Why When an organization's configuration server requires a new OAuth grant, clients need a way to sign in before the app server starts so they can load and validate the required settings. ## What changed - Have `--print-startup-config` return the `configServerLogin` action when browser sign-in is required, and verify that the required server settings were applied before returning startup requirements. - Add `codex app-server --startup-oauth`, a dedicated stdio mode that resolves the configuration server from local managed requirements, sends the client a browser authorization URL, and handles the callback, token exchange, and credential storage. Clients can cancel a pending sign-in or rerun `--print-startup-config` after it succeeds. ## Testing Add a test that checks the browser handoff URL and verifies that cancellation completes the pending login request with `LoginFailed`. GitOrigin-RevId: 00f10d28befe33539882f4f3c0d2baf868ceb4a1
This commit is contained in:
committed by
copyberry
parent
f342aa7b92
commit
cf8992e940
@@ -780,6 +780,31 @@ HTTP, WebSocket, and code-mode gRPC requests use the shared destination checks.
|
||||
User-directed Git, SSH, shell, and other subprocess traffic retain their existing
|
||||
execution and sandbox policies.
|
||||
|
||||
### Configuration server sign-in during startup
|
||||
|
||||
`codex app-server --print-startup-config` reads requirements without starting
|
||||
the app server. If a required configuration server uses OAuth and needs a new
|
||||
grant, the command exits with an error whose `data` contains
|
||||
`"reason": "configServer"` and `"action": "configServerLogin"`.
|
||||
|
||||
When the action is `configServerLogin`, start `codex app-server --startup-oauth`.
|
||||
This dedicated stdio connection accepts one JSON request per line without an
|
||||
initialize handshake. Each reply echoes the string or integer request ID.
|
||||
|
||||
1. After the user chooses Sign in, send
|
||||
`{"id":1,"method":"account/gatewayOAuth/login","params":{"target":{"kind":"configServer"}}}`.
|
||||
The helper resolves the target from local managed requirements.
|
||||
2. On this pipe, `account/gatewayOAuth/changed` sends the browser handoff with
|
||||
`{"target":{"kind":"configServer"},"status":"started","authUrl":"..."}`.
|
||||
Open that URL on the user's desktop. Rust handles the callback, token exchange,
|
||||
and credential storage.
|
||||
3. The original login request stays pending and returns `{"prompt":null}` on
|
||||
success, or an error on failure. To cancel, send
|
||||
`{"id":2,"method":"account/gatewayOAuth/cancel"}`. Closing stdin also ends the
|
||||
pending attempt.
|
||||
4. On success, close the pipe and rerun `--print-startup-config`. Continue startup
|
||||
only with the validated requirements.
|
||||
|
||||
# Item history anchors
|
||||
|
||||
Live notifications and turn history return the same `ThreadItem`. Each item has
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use super::*;
|
||||
|
||||
fn cloud_config_bundle_load_error(err: &std::io::Error) -> Option<&CloudConfigBundleLoadError> {
|
||||
pub(crate) fn cloud_config_bundle_load_error(
|
||||
err: &std::io::Error,
|
||||
) -> Option<&CloudConfigBundleLoadError> {
|
||||
let mut current: Option<&(dyn std::error::Error + 'static)> = err
|
||||
.get_ref()
|
||||
.map(|source| source as &(dyn std::error::Error + 'static));
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
//! One-shot configuration discovery. Never initializes environments, thread storage, or plugins.
|
||||
//! Early policy discovery and configuration-server sign-in. Never initializes environments, thread storage, or plugins.
|
||||
|
||||
mod oauth;
|
||||
#[cfg(test)]
|
||||
mod oauth_tests;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::request_processors::account_processor::clear_account_configuration;
|
||||
use crate::request_processors::account_processor::logout_configured_account;
|
||||
use crate::request_processors::config_errors::cloud_config_bundle_load_error;
|
||||
use crate::request_processors::config_errors::config_load_error;
|
||||
use crate::request_processors::config_processor::map_requirements_to_api;
|
||||
use codex_app_server_protocol::ClientInfo;
|
||||
use codex_app_server_protocol::ConfigRequirementsReadResponse;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoadErrorCode;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_core::config::find_codex_home;
|
||||
@@ -28,15 +34,23 @@ use std::sync::Arc;
|
||||
#[derive(Debug, clap::Args)]
|
||||
pub struct StartupConfigArgs {
|
||||
/// Sign out using the managed auth path before loading fresh startup requirements.
|
||||
#[arg(long, requires = "print_startup_config")]
|
||||
#[arg(
|
||||
long,
|
||||
requires = "print_startup_config",
|
||||
conflicts_with = "startup_oauth"
|
||||
)]
|
||||
pub startup_sign_out: bool,
|
||||
|
||||
/// Serve only configuration-server OAuth requests over standard input and output.
|
||||
#[arg(long, group = "startup_mode", conflicts_with_all = ["listen", "stdio", "remote_control", "managed_daemon"])]
|
||||
pub startup_oauth: bool,
|
||||
|
||||
/// Validate configuration and print requirements as JSON without starting the app server.
|
||||
#[arg(long, conflicts_with_all = ["listen", "stdio", "remote_control", "managed_daemon"])]
|
||||
#[arg(long, group = "startup_mode", conflicts_with_all = ["listen", "stdio", "remote_control", "managed_daemon"])]
|
||||
pub print_startup_config: bool,
|
||||
|
||||
/// ClientInfo JSON used for configuration/auth request identity.
|
||||
#[arg(long, requires = "print_startup_config", value_parser = |value: &str| serde_json::from_str::<ClientInfo>(value))]
|
||||
#[arg(long, requires = "startup_mode", value_parser = |value: &str| serde_json::from_str::<ClientInfo>(value))]
|
||||
pub startup_client_info: Option<ClientInfo>,
|
||||
}
|
||||
|
||||
@@ -47,7 +61,7 @@ struct StartupConfig {
|
||||
config_requirements: ConfigRequirementsReadResponse,
|
||||
}
|
||||
|
||||
/// Writes exactly one JSON value, including structured errors on failure.
|
||||
/// Runs the selected early startup operation before the regular app server initializes.
|
||||
pub async fn print_startup_config(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
cli_config_overrides: CliConfigOverrides,
|
||||
@@ -55,14 +69,21 @@ pub async fn print_startup_config(
|
||||
strict_config: bool,
|
||||
startup: StartupConfigArgs,
|
||||
) -> io::Result<()> {
|
||||
let result = read_startup_config(
|
||||
let manager = startup_manager(
|
||||
arg0_paths,
|
||||
cli_config_overrides,
|
||||
loader_overrides,
|
||||
strict_config,
|
||||
startup,
|
||||
)
|
||||
.await;
|
||||
startup.startup_client_info,
|
||||
);
|
||||
if startup.startup_oauth {
|
||||
let manager = manager.map_err(|error| io::Error::other(error.message))?;
|
||||
return oauth::serve(manager, tokio::io::stdin(), tokio::io::stdout()).await;
|
||||
}
|
||||
let result = match manager {
|
||||
Ok(manager) => read_startup_config(manager, startup.startup_sign_out).await,
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let output = match &result {
|
||||
Ok(config) => serde_json::to_vec(config)?,
|
||||
Err(error) => serde_json::to_vec(&serde_json::json!({ "error": error }))?,
|
||||
@@ -77,47 +98,15 @@ pub async fn print_startup_config(
|
||||
}
|
||||
|
||||
async fn read_startup_config(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
cli_config_overrides: CliConfigOverrides,
|
||||
loader_overrides: LoaderOverrides,
|
||||
strict_config: bool,
|
||||
startup: StartupConfigArgs,
|
||||
manager: ConfigManager,
|
||||
sign_out: bool,
|
||||
) -> Result<StartupConfig, JSONRPCErrorError> {
|
||||
if startup.startup_sign_out
|
||||
&& (is_workload_identity_selected() || read_codex_access_token_from_env().is_some())
|
||||
if sign_out && (is_workload_identity_selected() || read_codex_access_token_from_env().is_some())
|
||||
{
|
||||
return Err(crate::error_code::invalid_request(
|
||||
"Configured external authentication is owned by the app-server host and cannot be changed during startup recovery.",
|
||||
));
|
||||
}
|
||||
if let Some(client) = startup.startup_client_info {
|
||||
match set_default_originator(client.name.clone()) {
|
||||
Ok(()) | Err(SetOriginatorError::AlreadyInitialized) => {}
|
||||
Err(SetOriginatorError::InvalidHeaderValue) => {
|
||||
return Err(crate::error_code::invalid_params("invalid client name"));
|
||||
}
|
||||
}
|
||||
if let Ok(mut suffix) = USER_AGENT_SUFFIX.lock() {
|
||||
*suffix = Some(format!("{}; {}", client.name, client.version));
|
||||
}
|
||||
}
|
||||
let loader_overrides = crate::loader_overrides_with_test_user_config_file(
|
||||
loader_overrides,
|
||||
crate::test_user_config_file_from_env(),
|
||||
)
|
||||
.map_err(startup_error)?;
|
||||
let overrides = cli_config_overrides
|
||||
.parse_overrides()
|
||||
.map_err(|error| startup_error(io::Error::new(io::ErrorKind::InvalidInput, error)))?;
|
||||
let manager = ConfigManager::new(
|
||||
find_codex_home().map_err(startup_error)?.to_path_buf(),
|
||||
overrides,
|
||||
loader_overrides,
|
||||
strict_config,
|
||||
Default::default(),
|
||||
arg0_paths,
|
||||
Arc::new(NoopThreadConfigLoader),
|
||||
);
|
||||
let cwd = std::env::current_dir().ok();
|
||||
let loaded = manager
|
||||
.load_managed_startup_config(cwd.clone())
|
||||
@@ -126,10 +115,18 @@ async fn read_startup_config(
|
||||
let config = match loaded.config {
|
||||
Ok(config) => config,
|
||||
// Recovery retains local credential settings when cloud policy is unavailable.
|
||||
Err(_) if startup.startup_sign_out => loaded.bootstrap.clone(),
|
||||
Err(_) if sign_out => loaded.bootstrap.clone(),
|
||||
Err(error)
|
||||
if manager
|
||||
.current_managed_config_loader()
|
||||
.config_server()
|
||||
.is_some_and(|server| server.oauth.is_some()) =>
|
||||
{
|
||||
return Err(config_server_error(error));
|
||||
}
|
||||
Err(error) => return Err(startup_error(error)),
|
||||
};
|
||||
let config = if startup.startup_sign_out {
|
||||
let config = if sign_out {
|
||||
// Preserve local credential authority while using the effective HTTP route.
|
||||
let mut auth_config = loaded.bootstrap.auth_config();
|
||||
auth_config.auth_route_config = config.auth_route_config();
|
||||
@@ -153,6 +150,10 @@ async fn read_startup_config(
|
||||
} else {
|
||||
config
|
||||
};
|
||||
config
|
||||
.config_layer_stack
|
||||
.ensure_config_server_applied()
|
||||
.map_err(startup_error)?;
|
||||
// Validate and emit the fetched snapshot, or the fresh signed-out snapshot.
|
||||
config
|
||||
.validate_windows_mxc_requirement()
|
||||
@@ -176,6 +177,71 @@ async fn read_startup_config(
|
||||
})
|
||||
}
|
||||
|
||||
fn startup_manager(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
cli_config_overrides: CliConfigOverrides,
|
||||
loader_overrides: LoaderOverrides,
|
||||
strict_config: bool,
|
||||
client_info: Option<ClientInfo>,
|
||||
) -> Result<ConfigManager, JSONRPCErrorError> {
|
||||
if let Some(client) = client_info {
|
||||
match set_default_originator(client.name.clone()) {
|
||||
Ok(()) | Err(SetOriginatorError::AlreadyInitialized) => {}
|
||||
Err(SetOriginatorError::InvalidHeaderValue) => {
|
||||
return Err(crate::error_code::invalid_params("invalid client name"));
|
||||
}
|
||||
}
|
||||
if let Ok(mut suffix) = USER_AGENT_SUFFIX.lock() {
|
||||
*suffix = Some(format!("{}; {}", client.name, client.version));
|
||||
}
|
||||
}
|
||||
let loader_overrides = crate::loader_overrides_with_test_user_config_file(
|
||||
loader_overrides,
|
||||
crate::test_user_config_file_from_env(),
|
||||
)
|
||||
.map_err(startup_error)?;
|
||||
let overrides = cli_config_overrides
|
||||
.parse_overrides()
|
||||
.map_err(|error| startup_error(io::Error::new(io::ErrorKind::InvalidInput, error)))?;
|
||||
Ok(ConfigManager::new(
|
||||
find_codex_home().map_err(startup_error)?.to_path_buf(),
|
||||
overrides,
|
||||
loader_overrides,
|
||||
strict_config,
|
||||
Default::default(),
|
||||
arg0_paths,
|
||||
Arc::new(NoopThreadConfigLoader),
|
||||
))
|
||||
}
|
||||
|
||||
fn config_server_error(error: io::Error) -> JSONRPCErrorError {
|
||||
let Some(auth) = cloud_config_bundle_load_error(&error)
|
||||
.filter(|err| err.code() == CloudConfigBundleLoadErrorCode::Auth)
|
||||
else {
|
||||
return startup_error(error);
|
||||
};
|
||||
if !auth.requires_login() {
|
||||
return config_server_login_failed(auth.to_string());
|
||||
}
|
||||
|
||||
let mut error = crate::error_code::invalid_request("Configuration server sign-in required");
|
||||
error.data = Some(serde_json::json!({
|
||||
"reason": "configServer",
|
||||
"errorCode": "Auth",
|
||||
"action": "configServerLogin",
|
||||
}));
|
||||
error
|
||||
}
|
||||
|
||||
fn config_server_login_failed(message: impl Into<String>) -> JSONRPCErrorError {
|
||||
let mut error = crate::error_code::invalid_request(message);
|
||||
error.data = Some(serde_json::json!({
|
||||
"reason": "configServer",
|
||||
"errorCode": "LoginFailed",
|
||||
}));
|
||||
error
|
||||
}
|
||||
|
||||
fn startup_error(error: io::Error) -> JSONRPCErrorError {
|
||||
let mut response = config_load_error(&error);
|
||||
if response.data.is_none() {
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Browser OAuth before Desktop has loaded policy. Each pipe owns at most one attempt.
|
||||
|
||||
use super::ConfigManager;
|
||||
use super::config_server_login_failed;
|
||||
use super::startup_error;
|
||||
use crate::error_code::invalid_params;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::error_code::method_not_found;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::GatewayOAuthCancelResponse;
|
||||
use codex_app_server_protocol::GatewayOAuthLoginParams;
|
||||
use codex_app_server_protocol::GatewayOAuthLoginResponse;
|
||||
use codex_app_server_protocol::GatewayOAuthStatus;
|
||||
use codex_app_server_protocol::GatewayOAuthTarget;
|
||||
use codex_app_server_protocol::JSONRPCError;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::JSONRPCRequest;
|
||||
use codex_app_server_protocol::JSONRPCResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::StartupGatewayOAuthChangedNotification;
|
||||
use codex_login::OAuthSessionManager;
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::io;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
// The policy read already reported that sign-in is required. Use the local
|
||||
// bootstrap settings to resolve the grant without fetching policy again.
|
||||
async fn discover_session(
|
||||
manager: &ConfigManager,
|
||||
) -> Result<Option<OAuthSessionManager>, JSONRPCErrorError> {
|
||||
let bootstrap = manager
|
||||
.load_startup_config(std::env::current_dir().ok())
|
||||
.await
|
||||
.map_err(startup_error)?
|
||||
.config;
|
||||
codex_cloud_config::managed_config_auth_manager(
|
||||
bootstrap.auth_config(),
|
||||
bootstrap.config_layer_stack.requirements_toml(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| config_server_login_failed("Could not initialize configuration server sign-in"))
|
||||
}
|
||||
|
||||
struct Attempt {
|
||||
id: RequestId,
|
||||
cancel: CancellationToken,
|
||||
login: BoxFuture<'static, io::Result<()>>,
|
||||
}
|
||||
|
||||
impl Attempt {
|
||||
async fn start(
|
||||
id: RequestId,
|
||||
session: OAuthSessionManager,
|
||||
) -> Result<(Self, StartupGatewayOAuthChangedNotification), JSONRPCErrorError> {
|
||||
let cancel = CancellationToken::new();
|
||||
let cancelled = cancel.clone().cancelled_owned();
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let mut login = async move {
|
||||
session
|
||||
.login_with_browser(cancelled, |url| {
|
||||
let _ = tx.send(url.to_string());
|
||||
})
|
||||
.await
|
||||
}
|
||||
.boxed();
|
||||
let auth_url = tokio::select! {
|
||||
_ = &mut login => return Err(config_server_login_failed("Could not start browser sign-in")),
|
||||
url = rx => url.map_err(|_| config_server_login_failed("Could not start browser sign-in"))?,
|
||||
};
|
||||
let handoff = StartupGatewayOAuthChangedNotification {
|
||||
target: GatewayOAuthTarget::ConfigServer,
|
||||
status: GatewayOAuthStatus::Started,
|
||||
auth_url,
|
||||
};
|
||||
Ok((Self { id, cancel, login }, handoff))
|
||||
}
|
||||
|
||||
fn reply(self, result: io::Result<()>) -> Value {
|
||||
let result = match result {
|
||||
Ok(()) => Ok(json!(GatewayOAuthLoginResponse { prompt: None })),
|
||||
Err(_) if self.cancel.is_cancelled() => Err(config_server_login_failed(
|
||||
"Configuration server sign-in was cancelled",
|
||||
)),
|
||||
Err(_) => Err(config_server_login_failed(
|
||||
"Configuration server sign-in failed",
|
||||
)),
|
||||
};
|
||||
reply(self.id, result)
|
||||
}
|
||||
}
|
||||
|
||||
fn reply(id: RequestId, result: Result<Value, JSONRPCErrorError>) -> Value {
|
||||
match result {
|
||||
Ok(result) => json!(JSONRPCResponse { id, result }),
|
||||
Err(error) => json!(JSONRPCError { id, error }),
|
||||
}
|
||||
}
|
||||
|
||||
async fn write(output: &mut (impl AsyncWrite + Unpin), message: Value) -> io::Result<()> {
|
||||
let mut bytes = serde_json::to_vec(&message)?;
|
||||
bytes.push(b'\n');
|
||||
output.write_all(&bytes).await?;
|
||||
output.flush().await
|
||||
}
|
||||
|
||||
async fn start_login(
|
||||
id: RequestId,
|
||||
params: GatewayOAuthLoginParams,
|
||||
manager: &ConfigManager,
|
||||
active: &mut Option<Attempt>,
|
||||
) -> Result<StartupGatewayOAuthChangedNotification, JSONRPCErrorError> {
|
||||
if params.target != Some(GatewayOAuthTarget::ConfigServer) || params.model_provider.is_some() {
|
||||
return Err(invalid_params(
|
||||
"Startup login requires the configServer target",
|
||||
));
|
||||
}
|
||||
if params.device_auth {
|
||||
return Err(invalid_params(
|
||||
"Startup supports browser authentication only",
|
||||
));
|
||||
}
|
||||
if active.is_some() {
|
||||
return Err(invalid_request("Sign-in already in progress"));
|
||||
}
|
||||
let session = discover_session(manager).await?.ok_or_else(|| {
|
||||
config_server_login_failed("Configuration server OAuth is not configured")
|
||||
})?;
|
||||
let (attempt, handoff) = Attempt::start(id, session).await?;
|
||||
*active = Some(attempt);
|
||||
Ok(handoff)
|
||||
}
|
||||
|
||||
async fn handle_request(
|
||||
line: &str,
|
||||
manager: &ConfigManager,
|
||||
active: &mut Option<Attempt>,
|
||||
output: &mut (impl AsyncWrite + Unpin),
|
||||
) -> io::Result<()> {
|
||||
let raw: JSONRPCRequest = serde_json::from_str(line).map_err(io::Error::other)?;
|
||||
let id = raw.id.clone();
|
||||
if !matches!(
|
||||
raw.method.as_str(),
|
||||
"account/gatewayOAuth/login" | "account/gatewayOAuth/cancel"
|
||||
) {
|
||||
return write(
|
||||
output,
|
||||
reply(id, Err(method_not_found("Unknown startup OAuth method"))),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let result = match ClientRequest::try_from(raw) {
|
||||
Ok(ClientRequest::GatewayOAuthLogin { params, .. }) => {
|
||||
match start_login(id.clone(), params.unwrap_or_default(), manager, active).await {
|
||||
Ok(handoff) => {
|
||||
return write(
|
||||
output,
|
||||
json!({"method":"account/gatewayOAuth/changed","params":handoff}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
Ok(ClientRequest::GatewayOAuthCancel { .. }) => {
|
||||
if let Some(mut attempt) = active.take() {
|
||||
attempt.cancel.cancel();
|
||||
let result = (&mut attempt.login).await;
|
||||
write(output, attempt.reply(result)).await?;
|
||||
}
|
||||
Ok(json!(GatewayOAuthCancelResponse {}))
|
||||
}
|
||||
_ => Err(invalid_params("Invalid startup OAuth parameters")),
|
||||
};
|
||||
write(output, reply(id, result)).await
|
||||
}
|
||||
|
||||
pub(super) async fn serve(
|
||||
manager: ConfigManager,
|
||||
input: impl AsyncRead + Unpin,
|
||||
mut output: impl AsyncWrite + Unpin,
|
||||
) -> io::Result<()> {
|
||||
let mut requests = BufReader::new(input).lines();
|
||||
let mut active: Option<Attempt> = None;
|
||||
loop {
|
||||
let line = if let Some(attempt) = active.as_mut() {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut attempt.login => {
|
||||
if let Some(attempt) = active.take() {
|
||||
write(&mut output, attempt.reply(result)).await?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
line = requests.next_line() => line,
|
||||
}
|
||||
} else {
|
||||
requests.next_line().await
|
||||
}?;
|
||||
let Some(line) = line else { return Ok(()) };
|
||||
handle_request(&line, &manager, &mut active, &mut output).await?;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Exercises the startup-only connection against an isolated managed enrollment.
|
||||
|
||||
use super::oauth::serve;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use codex_config::LoaderOverrides;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::io::DuplexStream;
|
||||
use tokio::io::Lines;
|
||||
use tokio::io::ReadHalf;
|
||||
use tokio::io::WriteHalf;
|
||||
use url::Url;
|
||||
|
||||
struct Client {
|
||||
lines: Lines<BufReader<ReadHalf<DuplexStream>>>,
|
||||
input: WriteHalf<DuplexStream>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn receive(&mut self) -> anyhow::Result<Value> {
|
||||
let line = self
|
||||
.lines
|
||||
.next_line()
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("startup pipe closed"))?;
|
||||
Ok(serde_json::from_str(&line)?)
|
||||
}
|
||||
|
||||
async fn send(&mut self, request: Value) -> anyhow::Result<()> {
|
||||
self.input
|
||||
.write_all(format!("{request}\n").as_bytes())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_gateway_oauth_cancels_pending_browser_login() -> anyhow::Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let managed = home.path().join("managed_config.toml");
|
||||
let requirements = home.path().join("requirements.toml");
|
||||
std::fs::write(
|
||||
&requirements,
|
||||
r#"
|
||||
[config_server]
|
||||
base_url = "https://config.example.test"
|
||||
[config_server.oauth]
|
||||
authorization_url = "https://login.example.test/authorize"
|
||||
token_url = "https://login.example.test/token"
|
||||
client_id = "desktop"
|
||||
"#,
|
||||
)?;
|
||||
let (client, server) = tokio::io::duplex(8192);
|
||||
let (read, write) = tokio::io::split(server);
|
||||
let task = tokio::spawn(async move {
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().into(),
|
||||
vec![],
|
||||
LoaderOverrides::with_managed_config_path_for_tests(managed),
|
||||
Default::default(),
|
||||
);
|
||||
serve(manager, read, write).await
|
||||
});
|
||||
let (read, input) = tokio::io::split(client);
|
||||
let mut client = Client {
|
||||
lines: BufReader::new(read).lines(),
|
||||
input,
|
||||
};
|
||||
client
|
||||
.send(json!({
|
||||
"id": 1,
|
||||
"method": "account/gatewayOAuth/login",
|
||||
"params": {"target": {"kind": "configServer"}},
|
||||
}))
|
||||
.await?;
|
||||
let started = client.receive().await?;
|
||||
assert_eq!(started["method"], "account/gatewayOAuth/changed");
|
||||
assert_eq!(started["params"]["status"], "started");
|
||||
assert_eq!(started["params"]["target"], json!({"kind": "configServer"}));
|
||||
let url = Url::parse(started["params"]["authUrl"].as_str().unwrap())?;
|
||||
assert_eq!(url.host_str(), Some("login.example.test"));
|
||||
|
||||
client
|
||||
.send(json!({"id": 2, "method": "account/gatewayOAuth/cancel"}))
|
||||
.await?;
|
||||
let cancelled = client.receive().await?;
|
||||
assert_eq!(cancelled["id"], 1);
|
||||
assert_eq!(cancelled["error"]["data"]["errorCode"], "LoginFailed");
|
||||
assert_eq!(client.receive().await?, json!({"id": 2, "result": {}}));
|
||||
drop(client);
|
||||
task.await??;
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user