diff --git a/codex-rs/login/BUILD.bazel b/codex-rs/login/BUILD.bazel index 561176b3ed..78eea8c3dc 100644 --- a/codex-rs/login/BUILD.bazel +++ b/codex-rs/login/BUILD.bazel @@ -8,5 +8,9 @@ codex_rust_crate( "src/assets/success_legacy.html", ], crate_name = "codex_login", + test_shard_counts = { + # Gateway credential tests exercise real encryption and run serially on Windows. + "login-unit-tests": 4, + }, unit_test_timeout = "long", ) diff --git a/codex-rs/login/src/gateway_auth.rs b/codex-rs/login/src/gateway_auth.rs index bf9842a80d..00871113ed 100644 --- a/codex-rs/login/src/gateway_auth.rs +++ b/codex-rs/login/src/gateway_auth.rs @@ -1,4 +1,4 @@ -//! Owns gateway credentials and coordinates refresh and browser login through shared OAuth operations. +//! Owns gateway credentials, token refresh, and policy-controlled browser authorization. //! Credential I/O runs off the async worker and writes retain the store lock through cancellation. //! Rotated credentials survive caller cancellation and remain pending until persistence succeeds. @@ -34,11 +34,18 @@ use url::Url; #[path = "gateway_auth_callback.rs"] mod callback; +#[path = "gateway_auth_login.rs"] +mod login; #[path = "gateway_auth_storage.rs"] mod storage; #[path = "gateway_auth_token.rs"] mod token; +pub use login::GatewayAuthStatus; +pub use login::GatewayAuthStatusChange; +pub use login::GatewayLoginControl; +pub use login::subscribe_gateway_auth_status; + use callback::CallbackListener; use storage::GatewayAuthStorage; use token::StoredToken; @@ -47,6 +54,15 @@ use token::TokenResponse; const REFRESH_SKEW_SECONDS: i64 = 30; const HTTP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 20); +/// Gateway authentication states that require user action rather than request retries. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum GatewayAuthError { + #[error("Gateway sign-in required. Choose Sign in or Reconnect, then retry your request")] + LoginRequired, + #[error("Gateway authentication is in progress; retry after sign-in")] + LoginInProgress, +} + /// Public-client OAuth settings for a model provider. #[derive(Clone, PartialEq, Eq)] pub struct GatewayAuthConfig { @@ -61,6 +77,7 @@ pub struct GatewayAuthConfig { /// Resolves and persists an OAuth access token for a model provider. #[derive(Clone)] pub struct GatewayAuthManager { + control: Arc, state: Arc, } @@ -83,7 +100,7 @@ impl RefreshPolicy { enum RefreshOutcome { AccessToken(String), - Authorize, + LoginRequired, } struct GatewayAuthState { @@ -92,14 +109,20 @@ struct GatewayAuthState { storage: GatewayAuthStorage, http_client: HttpClient, cached_token: Arc>, + // Reserve explicit login independently of background credential reads and refreshes. + login_attempt: Arc>, + status: tokio::sync::watch::Sender>, + status_tx: tokio::sync::broadcast::Sender, } -#[derive(Default)] +#[derive(Clone, Default, PartialEq, Eq)] struct GatewayAuthCache { token: Option, // Retain rotated credentials across a failed save. The prior persisted token remains // available for comparison so retrying cannot overwrite a newer external login. pending: Option, + // A failed recovery requires replacement credentials, even before local expiry. + login_required: Option, } impl GatewayAuthManager { @@ -121,57 +144,121 @@ impl GatewayAuthManager { ) .map_err(|_| io::Error::other("failed to create provider OAuth HTTP client"))?; Ok(Self { + control: GatewayLoginControl::for_host(&codex_home, http_client_factory), state: Arc::new(GatewayAuthState { config, + status_tx: login::status_sender_for_host(&codex_home, http_client_factory), storage: GatewayAuthStorage::new(codex_home.clone(), keyring), codex_home, http_client, cached_token: Arc::new(Mutex::new(GatewayAuthCache::default())), + login_attempt: Arc::new(Mutex::new(())), + status: tokio::sync::watch::channel(/*init*/ None).0, }), }) } - /// Returns a cached access token or refreshes/authorizes when it is no longer usable. + /// Returns a usable token, refreshing or starting browser login according to the host policy. pub async fn resolve_access_token(&self) -> io::Result { - self.resolve(RefreshPolicy::WhenExpired).await + self.resolve_with_browser(RefreshPolicy::WhenExpired, login::open_browser) + .await } /// Recovers after a request rejects `rejected_access_token`, reusing a usable replacement - /// from storage or refreshing/authorizing when necessary. Pass the access token used by the - /// failed request; callers must bound retries and decide whether the request is safe to replay. + /// from storage or refreshing/authorizing according to the host policy. + /// Pass the token used by the failed request; callers must bound retries and decide + /// whether the request is safe to replay. pub async fn refresh_access_token(&self, rejected_access_token: &str) -> io::Result { - self.resolve(RefreshPolicy::AfterRejection( - rejected_access_token.to_owned(), - )) + self.resolve_with_browser( + RefreshPolicy::AfterRejection(rejected_access_token.to_owned()), + login::open_browser, + ) .await } - async fn resolve(&self, policy: RefreshPolicy) -> io::Result { + async fn resolve_with_browser( + &self, + policy: RefreshPolicy, + open_browser: impl FnOnce(&Url), + ) -> io::Result { validate_config(&self.state.config)?; - let mut cached = Arc::clone(&self.state.cached_token).lock_owned().await; - if cached.token.is_none() && cached.pending.is_none() { + let mut cached = self.lock_cached_token().await?; + let terminal_status = self.state.status.borrow().as_ref().is_some_and(|snapshot| { + matches!( + snapshot.status, + GatewayAuthStatus::NotReady | GatewayAuthStatus::Failed { .. } + ) + }); + // A cached token may predate the failed login. Only persisted replacements can clear it. + if cached.pending.is_none() + && (cached.token.is_none() || terminal_status || cached.login_required.is_some()) + { cached.token = self.load_token_async().await?; } + if cached.pending.is_none() + && cached.login_required.is_some() + && cached.token == cached.login_required + { + if !self + .control + .explicit_login + .load(std::sync::atomic::Ordering::Relaxed) + { + return self.authorize_with_browser(&mut cached, open_browser).await; + } + return Err(self.login_required_error(cached.token.as_ref())); + } if cached.pending.is_none() && matches!(policy, RefreshPolicy::WhenExpired) && let Some(token) = cached.token.as_ref() && token_is_usable(token) { - return Ok(token.access_token.clone()); + let terminal_matches = self.state.status.borrow().as_ref().is_some_and(|snapshot| { + matches!( + snapshot.status, + GatewayAuthStatus::NotReady | GatewayAuthStatus::Failed { .. } + ) && snapshot.credential.as_ref() == Some(token) + }); + if !terminal_matches { + self.publish_status(GatewayAuthStatus::Succeeded, Some(token)); + } + let access_token = token.access_token.clone(); + cached.login_required = None; + return Ok(access_token); } // The provider may rotate its token before the HTTP response arrives. Keep the // refresh, persistence, and cache update alive if the caller drops this future. let manager = self.clone(); let (mut cached, result) = tokio::spawn(async move { - let result = manager.refresh(&mut cached, &policy).await; + let result = match manager.refresh(&mut cached, &policy).await { + Err(error) => Err(error), + Ok(RefreshOutcome::AccessToken(access_token)) => { + cached.login_required = None; + manager.publish_status(GatewayAuthStatus::Succeeded, cached.token.as_ref()); + Ok(access_token) + } + Ok(RefreshOutcome::LoginRequired) => { + cached.login_required = cached.token.clone(); + Err(manager.login_required_error(cached.token.as_ref())) + } + }; (cached, result) }) .await .map_err(|_| io::Error::other("provider OAuth refresh task failed"))?; - match result? { - RefreshOutcome::AccessToken(access_token) => Ok(access_token), - RefreshOutcome::Authorize => self.authorize(&mut cached).await, + if result.as_ref().is_err_and(|error| { + error + .get_ref() + .and_then(|source| source.downcast_ref::()) + == Some(&GatewayAuthError::LoginRequired) + }) && !self + .control + .explicit_login + .load(std::sync::atomic::Ordering::Relaxed) + { + return self.authorize_with_browser(&mut cached, open_browser).await; } + result } async fn persist_pending( @@ -196,6 +283,7 @@ impl GatewayAuthManager { .map_err(|_| io::Error::other("provider OAuth credential save task failed"))??; let access_token = token.access_token.clone(); cached.token = cached.pending.take(); + cached.login_required = None; Ok(access_token) } @@ -253,7 +341,7 @@ impl GatewayAuthManager { ) => { // Some public clients receive refresh tokens despite being unable to use - // that grant. Reauthorize after explicit rejection without disabling refresh. + // that grant. Require browser login after rejection without disabling refresh. // Also recover updates from clients that predate the credential lock. if self.load_token_async().await? == cached.token { break; @@ -279,7 +367,7 @@ impl GatewayAuthManager { return Ok(RefreshOutcome::AccessToken(token.access_token.clone())); } } - Ok(RefreshOutcome::Authorize) + Ok(RefreshOutcome::LoginRequired) } fn credential_id(&self) -> String { @@ -327,16 +415,6 @@ impl GatewayAuthManager { self.state.storage.save(&self.credential_id(), &value) } - async fn authorize(&self, cached: &mut GatewayAuthCache) -> io::Result { - self.authorize_with_browser(cached, |authorization_url| { - eprintln!("Authorize the model provider by opening this URL:\n{authorization_url}\n"); - if webbrowser::open(authorization_url.as_str()).is_err() { - eprintln!("Browser launch failed; open the URL above manually."); - } - }) - .await - } - async fn authorize_with_browser( &self, cached: &mut GatewayAuthCache, @@ -390,7 +468,9 @@ impl GatewayAuthManager { ) })?; cached.pending = Some(response.into_stored(/*previous_refresh_token*/ None)?); - self.persist_pending(cached, &credential_lock).await + let access_token = self.persist_pending(cached, &credential_lock).await?; + self.publish_status(GatewayAuthStatus::Succeeded, cached.token.as_ref()); + Ok(access_token) } fn oauth(&self) -> OAuthClient<'_> { diff --git a/codex-rs/login/src/gateway_auth_login.rs b/codex-rs/login/src/gateway_auth_login.rs new file mode 100644 index 0000000000..d6840c3f44 --- /dev/null +++ b/codex-rs/login/src/gateway_auth_login.rs @@ -0,0 +1,377 @@ +//! Coordinates gateway login, readiness, and status notifications. +//! Reports login progress before credential I/O and success only after persistence. +//! Readiness I/O leaves the cache unlocked and preserves newer state. + +use super::*; +use std::future::Future; +use std::sync::OnceLock; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use tokio::sync::OwnedMutexGuard; +use tokio::sync::broadcast; + +/// Readiness and browser authorization progress for a gateway credential. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GatewayAuthStatus { + NotReady, + Started, + Succeeded, + Failed { message: String }, +} + +// Keep terminal status tied to its credential and retain successful credential expiry for busy reads. +// Deliberately omit Debug: this snapshot contains credentials. +#[derive(Clone)] +pub(super) struct GatewayAuthStatusSnapshot { + pub(super) status: GatewayAuthStatus, + pub(super) credential: Option, +} + +/// A credential status change scoped to the configured OAuth account. +#[derive(Clone, Debug)] +pub struct GatewayAuthStatusChange { + pub config: GatewayAuthConfig, + pub status: GatewayAuthStatus, +} + +/// Browser policy shared by gateway managers with the same home and network configuration. +#[derive(Debug)] +pub struct GatewayLoginControl { + pub(super) explicit_login: AtomicBool, + status_tx: broadcast::Sender, +} + +impl GatewayLoginControl { + /// Returns the control shared across this runtime's provider configurations. + pub fn for_runtime(runtime: &crate::AuthRuntimeConfig) -> Arc { + Self::for_host( + &runtime.codex_home, + runtime.auth_route_config.http_client_factory(), + ) + } + + pub(super) fn for_host(codex_home: &std::path::Path, factory: &HttpClientFactory) -> Arc { + type Controls = Vec<(PathBuf, HttpClientFactory, Arc)>; + static CONTROLS: OnceLock> = OnceLock::new(); + let mut controls = CONTROLS + .get_or_init(std::sync::Mutex::default) + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + // Keep subscriptions alive between manager lifetimes, including before a gateway is configured. + controls.retain(|(_, _, control)| { + Arc::strong_count(control) > 1 + || control.status_tx.strong_count() > 1 + || control.status_tx.receiver_count() > 0 + }); + if let Some((_, _, control)) = controls + .iter() + .find(|(home, routes, _)| home == codex_home && routes == factory) + { + return Arc::clone(control); + } + let control = Arc::new(Self { + explicit_login: AtomicBool::new(/*v*/ false), + status_tx: broadcast::channel(/*capacity*/ 16).0, + }); + controls.push(( + codex_home.to_path_buf(), + factory.clone(), + Arc::clone(&control), + )); + control + } + + /// Requires caller-initiated browser login, including during app-server startup. + pub fn require_explicit_login(&self) { + self.explicit_login.store(/*val*/ true, Ordering::Relaxed); + } + + /// Restores automatic browser authorization for legacy clients after initialization. + pub fn allow_automatic_login(&self) { + self.explicit_login.store(/*val*/ false, Ordering::Relaxed); + } +} + +/// Subscribes to gateway status changes for this home and network configuration. +/// The subscription also covers managers created after configuration changes. +pub fn subscribe_gateway_auth_status( + runtime: &crate::AuthRuntimeConfig, +) -> broadcast::Receiver { + GatewayLoginControl::for_runtime(runtime) + .status_tx + .subscribe() +} + +pub(super) fn status_sender_for_host( + codex_home: &std::path::Path, + factory: &HttpClientFactory, +) -> broadcast::Sender { + GatewayLoginControl::for_host(codex_home, factory) + .status_tx + .clone() +} + +impl GatewayAuthManager { + /// Returns the OAuth account configuration used to scope status notifications. + pub fn config(&self) -> &GatewayAuthConfig { + &self.state.config + } + + /// Returns whether the status changed and a notification was published. + pub(super) fn publish_status( + &self, + status: GatewayAuthStatus, + credential: Option<&StoredToken>, + ) -> bool { + let credential = match status { + GatewayAuthStatus::NotReady + | GatewayAuthStatus::Failed { .. } + | GatewayAuthStatus::Succeeded => credential.cloned(), + GatewayAuthStatus::Started => None, + }; + let mut changed = false; + self.state.status.send_if_modified(|previous| { + changed = previous + .as_ref() + .is_none_or(|previous| previous.status != status); + if !changed + && previous + .as_ref() + .is_some_and(|previous| previous.credential == credential) + { + return false; + } + *previous = Some(GatewayAuthStatusSnapshot { + status: status.clone(), + credential, + }); + if changed { + let _ = self.state.status_tx.send(GatewayAuthStatusChange { + config: self.state.config.clone(), + status: status.clone(), + }); + } + true + }); + changed + } + + pub(super) fn login_required_error(&self, credential: Option<&StoredToken>) -> io::Error { + // Requests must re-prompt even after an earlier NotReady notification was dismissed. + // Passive readiness reads continue to use the deduplicated publisher above. + if !self.publish_status(GatewayAuthStatus::NotReady, credential) { + let _ = self.state.status_tx.send(GatewayAuthStatusChange { + config: self.state.config.clone(), + status: GatewayAuthStatus::NotReady, + }); + } + io::Error::new( + io::ErrorKind::PermissionDenied, + GatewayAuthError::LoginRequired, + ) + } + + pub(super) async fn lock_cached_token(&self) -> io::Result> { + let mut status = self.state.status.subscribe(); + let lock = Arc::clone(&self.state.cached_token).lock_owned(); + tokio::pin!(lock); + loop { + if status + .borrow_and_update() + .as_ref() + .is_some_and(|snapshot| snapshot.status == GatewayAuthStatus::Started) + { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + GatewayAuthError::LoginInProgress, + )); + } + tokio::select! { + biased; + _ = status.changed() => {} + guard = &mut lock => return Ok(guard), + } + } + } + + /// Reads readiness without refreshing credentials, opening a browser, or waiting for login. + pub async fn status(&self) -> io::Result { + let manager = self.clone(); + tokio::task::spawn_blocking(move || manager.status_blocking()) + .await + .map_err(|_| io::Error::other("provider OAuth readiness task failed"))? + } + + fn status_blocking(&self) -> io::Result { + let mut status_changes = self.state.status.subscribe(); + let previous_cache = { + let Ok(cached) = self.state.cached_token.try_lock() else { + return Ok(self.snapshot_status()); + }; + if status_changes + .borrow_and_update() + .as_ref() + .is_some_and(|snapshot| snapshot.status == GatewayAuthStatus::Started) + { + return Ok(GatewayAuthStatus::Started); + } + cached.clone() + }; + // Keyring I/O may stall even after the caller drops this readiness request. + // Leave the cache available to inference and concurrent login/refresh work. + let stored = self.load_token(); + let Ok(mut cached) = self.state.cached_token.try_lock() else { + return Ok(self.snapshot_status()); + }; + if *cached != previous_cache + || status_changes.has_changed().unwrap_or(/*default*/ true) + { + return Ok(self.snapshot_status()); + } + let snapshot = status_changes.borrow().clone(); + let stored = stored?; + let terminal = snapshot.as_ref().filter(|snapshot| { + matches!( + snapshot.status, + GatewayAuthStatus::NotReady | GatewayAuthStatus::Failed { .. } + ) + }); + if stored.as_ref().is_some_and(token_is_usable) + && (cached.pending.is_none() || stored != cached.token) + && stored != cached.login_required + && terminal.is_none_or(|snapshot| stored != snapshot.credential) + { + // Only a persisted replacement supersedes a failed-save baseline or rejected token. + cached.token = stored; + cached.pending = None; + cached.login_required = None; + self.publish_status(GatewayAuthStatus::Succeeded, cached.token.as_ref()); + return Ok(GatewayAuthStatus::Succeeded); + } + if let Some(snapshot) = terminal { + return Ok(snapshot.status.clone()); + } + self.publish_status(GatewayAuthStatus::NotReady, stored.as_ref()); + Ok(GatewayAuthStatus::NotReady) + } + + fn snapshot_status(&self) -> GatewayAuthStatus { + let mut status = GatewayAuthStatus::NotReady; + // Check and downgrade atomically so an expired observation cannot overwrite + // a completed refresh or newly started login. + self.state.status.send_if_modified(|snapshot| { + let Some(snapshot) = snapshot else { + return false; + }; + let expired = snapshot.status == GatewayAuthStatus::Succeeded + && !snapshot.credential.as_ref().is_some_and(token_is_usable); + if expired { + snapshot.status = GatewayAuthStatus::NotReady; + let _ = self.state.status_tx.send(GatewayAuthStatusChange { + config: self.state.config.clone(), + status: GatewayAuthStatus::NotReady, + }); + } + status = snapshot.status.clone(); + expired + }); + status + } + + /// Starts browser authorization using a caller-provided URL handoff and cancellation future. + /// Completion means the credential was saved and is visible to existing request consumers. + pub async fn login_with_browser( + &self, + cancel: impl Future, + open_browser: impl FnOnce(&Url), + ) -> io::Result<()> { + validate_config(&self.state.config)?; + let _login_attempt = Arc::clone(&self.state.login_attempt) + .try_lock_owned() + .map_err(|_| { + io::Error::new(io::ErrorKind::WouldBlock, GatewayAuthError::LoginInProgress) + })?; + tokio::pin!(cancel); + let mut cached = tokio::select! { + biased; + cached = Arc::clone(&self.state.cached_token).lock_owned() => cached, + _ = &mut cancel => return Err(io::Error::new( + io::ErrorKind::Interrupted, + "Gateway sign-in was canceled", + )), + }; + let mut guard = LoginStatusGuard { + manager: self, + credential: cached.token.clone(), + completed: false, + }; + self.publish_status(GatewayAuthStatus::Started, /*credential*/ None); + let result = tokio::select! { + biased; + _ = &mut cancel => Err(io::Error::new(io::ErrorKind::Interrupted, "Gateway sign-in was canceled")), + result = async { + // A blocking read may outlive cancellation; it must not retain the login locks. + guard.credential = self.load_token_async().await?; + self.authorize_with_browser(&mut cached, open_browser).await.map(|_| ()) + } => result, + } + .map_err(|error| { + // Issuer errors may echo arbitrary credentials. Only retain safe text in the + // returned error and shared status, which is broadcast and can be debug-printed. + let message = if error.kind() == io::ErrorKind::Interrupted { + "Gateway sign-in was canceled" + } else { + "Gateway sign-in failed; check the gateway configuration and credential store." + }; + io::Error::new(error.kind(), message) + }); + if result.is_ok() { + // Success describes the newly saved credential, not the pre-login baseline. + guard.credential = cached.token.clone(); + } + guard.finish(&result); + result + } +} + +struct LoginStatusGuard<'a> { + manager: &'a GatewayAuthManager, + credential: Option, + completed: bool, +} + +impl LoginStatusGuard<'_> { + fn finish(&mut self, result: &io::Result) { + self.manager.publish_status( + match result { + Ok(_) => GatewayAuthStatus::Succeeded, + Err(error) => GatewayAuthStatus::Failed { + message: error.to_string(), + }, + }, + self.credential.as_ref(), + ); + self.completed = true; + } +} + +impl Drop for LoginStatusGuard<'_> { + fn drop(&mut self) { + if !self.completed { + self.manager.publish_status( + GatewayAuthStatus::Failed { + message: "Gateway sign-in was canceled".to_string(), + }, + self.credential.as_ref(), + ); + } + } +} + +// The legacy CLI/TUI flow hands browser authorization directly to the user. +pub(super) fn open_browser(url: &Url) { + eprintln!("Authorize the model provider by opening this URL:\n{url}\n"); + if webbrowser::open(url.as_str()).is_err() { + eprintln!("Browser launch failed; open the URL above manually."); + } +} diff --git a/codex-rs/login/src/gateway_auth_login_tests.rs b/codex-rs/login/src/gateway_auth_login_tests.rs new file mode 100644 index 0000000000..bb1e5a1319 --- /dev/null +++ b/codex-rs/login/src/gateway_auth_login_tests.rs @@ -0,0 +1,520 @@ +//! Explicit browser login shares credentials with request consumers and remains cancellable. + +use super::*; +use crate::GatewayAuthError; +use crate::GatewayAuthStatus; +use pretty_assertions::assert_eq; +use tokio::sync::Notify; + +#[tokio::test] +async fn status_subscriptions_survive_gateway_changes_and_are_isolated_by_home() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let runtime = crate::AuthRuntimeConfig { + codex_home: home.path().to_path_buf(), + auth_route_config: transport_default_auth_route_config(), + }; + // Subscribe before any manager exists, as app-server does without gateway configuration. + let mut events = crate::subscribe_gateway_auth_status(&runtime); + crate::GatewayLoginControl::for_runtime(&runtime).require_explicit_login(); + let keyring = Arc::new(MockKeyringStore::default()); + let (other_manager, _other_home) = client(config(&server), keyring.clone()); + other_manager.resolve_access_token().await.unwrap_err(); + assert!(matches!( + events.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + + for client_id in ["first-gateway", "replacement-gateway"] { + let mut gateway = config(&server); + gateway.client_id = client_id.to_string(); + let manager = GatewayAuthManager::new( + gateway.clone(), + home.path().to_path_buf(), + runtime.auth_route_config.http_client_factory(), + keyring.clone(), + ) + .unwrap(); + manager.resolve_access_token().await.unwrap_err(); + let event = tokio::time::timeout(Duration::from_secs(/*secs*/ 2), events.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!( + (event.config, event.status), + (gateway, GatewayAuthStatus::NotReady) + ); + // The next gateway must reach the same subscriber after the last manager is dropped. + drop(manager); + } + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn cancel_releases_callback_while_reads_and_requests_stay_responsive() { + let server = MockServer::start().await; + let (manager, _home) = client(config(&server), Arc::new(MockKeyringStore::default())); + let observer = manager.clone(); + let mut events = manager.state.status_tx.subscribe(); + let cancel = Notify::new(); + let (url_tx, url_rx) = tokio::sync::oneshot::channel(); + let login = manager.login_with_browser(cancel.notified(), |url| { + let redirect = url + .query_pairs() + .find(|(key, _)| key == "redirect_uri") + .unwrap() + .1 + .into_owned(); + url_tx.send(url::Url::parse(&redirect).unwrap()).unwrap(); + }); + let check = async { + let callback = url_rx.await.unwrap(); + assert_eq!(observer.status().await.unwrap(), GatewayAuthStatus::Started); + assert_eq!( + observer.resolve_access_token().await.unwrap_err().kind(), + std::io::ErrorKind::WouldBlock + ); + cancel.notify_one(); + callback + }; + let (result, callback) = tokio::join!(login, check); + assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted); + let failed = GatewayAuthStatus::Failed { + message: "Gateway sign-in was canceled".to_string(), + }; + assert_eq!(observer.status().await.unwrap(), failed); + assert_eq!( + events.recv().await.unwrap().status, + GatewayAuthStatus::Started + ); + assert_eq!(events.recv().await.unwrap().status, failed); + tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async { + loop { + if let Ok(listener) = TcpListener::bind(("127.0.0.1", callback.port().unwrap())) { + break listener; + } + tokio::time::sleep(Duration::from_millis(/*millis*/ 10)).await; + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn credential_read_failure_finishes_login_status() { + let server = MockServer::start().await; + let (manager, home) = client(config(&server), Arc::new(MockKeyringStore::default())); + let path = home.path().join("secrets/gateway_oauth.age"); + std::fs::create_dir_all(&path).unwrap(); + let mut events = manager.state.status_tx.subscribe(); + let error = manager + .login_with_browser(std::future::pending(), |_| panic!("unexpected browser")) + .await + .unwrap_err(); + let message = "Gateway sign-in failed; check the gateway configuration and credential store."; + assert_eq!(error.to_string(), message); + assert_eq!( + events.try_recv().unwrap().status, + GatewayAuthStatus::Started + ); + let failed = GatewayAuthStatus::Failed { + message: message.into(), + }; + assert_eq!(events.try_recv().unwrap().status, failed); + std::fs::remove_dir(&path).unwrap(); + assert_eq!(manager.status().await.unwrap(), failed); + let cancel = Notify::new(); + let error = manager + .login_with_browser(cancel.notified(), |_| cancel.notify_one()) + .await + .unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::Interrupted); +} + +#[tokio::test] +async fn rejected_credentials_stay_not_ready_until_replaced() { + let server = MockServer::start().await; + let keyring = Arc::new(MockKeyringStore::default()); + let (manager, _home) = client(config(&server), keyring.clone()); + let mut events = manager.state.status_tx.subscribe(); + save_token( + &manager, + "rejected", + Some("revoked-refresh"), + Utc::now().timestamp() + 3600, + ); + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("grant_type=refresh_token")) + .respond_with( + ResponseTemplate::new(/*s*/ 400).set_body_json(json!({"error": "invalid_grant"})), + ) + .expect(/*r*/ 1) + .mount(&server) + .await; + assert_eq!( + manager + .refresh_access_token("rejected") + .await + .unwrap_err() + .kind(), + std::io::ErrorKind::PermissionDenied + ); + assert_eq!(manager.status().await.unwrap(), GatewayAuthStatus::NotReady); + assert_eq!( + events.try_recv().unwrap().status, + GatewayAuthStatus::NotReady + ); + for _ in 0..2 { + assert_eq!( + manager.resolve_access_token().await.unwrap_err().kind(), + std::io::ErrorKind::PermissionDenied + ); + assert_eq!( + events.try_recv().unwrap().status, + GatewayAuthStatus::NotReady + ); + assert_eq!(manager.status().await.unwrap(), GatewayAuthStatus::NotReady); + assert!(matches!( + events.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + } + // Canceling a new login must not make the previously rejected credential reusable. + manager + .login_with_browser(std::future::ready(()), |_| panic!("unexpected browser")) + .await + .unwrap_err(); + assert_eq!( + manager.resolve_access_token().await.unwrap_err().kind(), + std::io::ErrorKind::PermissionDenied + ); + save_token( + &manager, + "replacement", + Some("new-refresh"), + Utc::now().timestamp() + 3600, + ); + assert_eq!( + manager.status().await.unwrap(), + GatewayAuthStatus::Succeeded + ); + assert_eq!(manager.resolve_access_token().await.unwrap(), "replacement"); + + // A rejected token with no refresh token also requires replacement credentials. + save_token( + &manager, + "no-refresh", + /*refresh_token*/ None, + Utc::now().timestamp() + 3600, + ); + assert_eq!( + manager + .refresh_access_token("no-refresh") + .await + .unwrap_err() + .kind(), + std::io::ErrorKind::PermissionDenied + ); + assert_eq!( + manager.resolve_access_token().await.unwrap_err().kind(), + std::io::ErrorKind::PermissionDenied + ); + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("grant_type=authorization_code")) + .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ + "access_token": "signed-in", "expires_in": 3600, + }))) + .expect(/*r*/ 1) + .mount(&server) + .await; + manager + .login_with_browser(std::future::pending(), complete_browser_authorization) + .await + .unwrap(); + let cache_lock = Arc::clone(&manager.state.cached_token).lock_owned().await; + assert_eq!( + manager.status().await.unwrap(), + GatewayAuthStatus::Succeeded + ); + drop(cache_lock); + assert_eq!(manager.resolve_access_token().await.unwrap(), "signed-in"); +} + +#[tokio::test] +async fn dropping_login_clears_in_progress_status() { + let server = MockServer::start().await; + let (manager, _home) = client(config(&server), Arc::new(MockKeyringStore::default())); + let observer = manager.clone(); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let login = tokio::spawn(async move { + manager + .login_with_browser(std::future::pending(), |_| { + let _ = started_tx.send(()); + }) + .await + }); + started_rx.await.unwrap(); + assert_eq!(observer.status().await.unwrap(), GatewayAuthStatus::Started); + login.abort(); + assert!(login.await.unwrap_err().is_cancelled()); + assert_eq!( + observer.status().await.unwrap(), + GatewayAuthStatus::Failed { + message: "Gateway sign-in was canceled".to_string() + } + ); +} + +#[tokio::test] +async fn expired_readiness_stays_not_ready_while_refresh_is_blocked() { + for read_before_refresh in [false, true] { + let server = MockServer::start().await; + let (manager, home) = client(config(&server), Arc::new(MockKeyringStore::default())); + let expired = StoredToken { + access_token: "expired".into(), + refresh_token: Some("refresh".into()), + expires_at: Some(Utc::now().timestamp() - 1), + }; + manager.save_token(&expired).unwrap(); + // Seed the last successful observation with a credential that has since expired. + manager.publish_status(GatewayAuthStatus::Succeeded, Some(&expired)); + let mut events = manager.state.status_tx.subscribe(); + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("grant_type=refresh_token")) + .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ + "access_token": "renewed", "expires_in": 3600, + }))) + .expect(/*r*/ 1) + .mount(&server) + .await; + if read_before_refresh { + assert_eq!(manager.status().await.unwrap(), GatewayAuthStatus::NotReady); + } + // Block the real refresh on the cross-process store lock after it takes the cache lock. + let store_lock = super::super::storage::lock_credentials(home.path()) + .await + .unwrap(); + let refresh = manager.resolve_access_token(); + tokio::pin!(refresh); + tokio::select! { + result = &mut refresh => panic!("refresh unexpectedly completed: {result:?}"), + ready = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async { + while manager.state.cached_token.try_lock().is_ok() { + tokio::task::yield_now().await; + } + }) => ready.expect("refresh holds cache lock"), + } + assert_eq!(manager.status().await.unwrap(), GatewayAuthStatus::NotReady); + assert_eq!(manager.status().await.unwrap(), GatewayAuthStatus::NotReady); + assert_eq!( + events.try_recv().unwrap().status, + GatewayAuthStatus::NotReady + ); + assert!(matches!( + events.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + assert!(server.received_requests().await.unwrap().is_empty()); + drop(store_lock); + assert_eq!(refresh.await.unwrap(), "renewed"); + // A busy cache must still report a newly refreshed, unexpired credential as usable. + let cache_lock = Arc::clone(&manager.state.cached_token).lock_owned().await; + assert_eq!( + manager.status().await.unwrap(), + GatewayAuthStatus::Succeeded + ); + drop(cache_lock); + assert_eq!( + events.try_recv().unwrap().status, + GatewayAuthStatus::Succeeded + ); + assert_eq!( + manager.status().await.unwrap(), + GatewayAuthStatus::Succeeded + ); + } +} + +#[tokio::test] +async fn external_credentials_recover_missing_and_failed_readiness() { + let server = MockServer::start().await; + for failed_login in [false, true] { + let keyring = Arc::new(MockKeyringStore::default()); + let (manager, _home) = client(config(&server), keyring.clone()); + let expected = if failed_login { + // The failed attempt starts with an existing usable token. It must not immediately + // look successful again just because that same token is still on disk. + save_token( + &manager, + "old", + /*refresh_token*/ None, + Utc::now().timestamp() + 3600, + ); + assert_eq!(manager.resolve_access_token().await.unwrap(), "old"); + save_token( + &manager, + "baseline", + /*refresh_token*/ None, + Utc::now().timestamp() + 3600, + ); + let cancel = Notify::new(); + manager + .login_with_browser(cancel.notified(), |_| cancel.notify_one()) + .await + .unwrap_err(); + GatewayAuthStatus::Failed { + message: "Gateway sign-in was canceled".into(), + } + } else { + manager.resolve_access_token().await.unwrap_err(); + GatewayAuthStatus::NotReady + }; + assert_eq!(manager.status().await.unwrap(), expected); + if failed_login { + // An older cached token must not be mistaken for a new external login. + assert_eq!(manager.resolve_access_token().await.unwrap(), "baseline"); + assert_eq!(manager.status().await.unwrap(), expected); + } + save_token( + &manager, + "expired", + /*refresh_token*/ None, + Utc::now().timestamp() - 1, + ); + assert_eq!(manager.status().await.unwrap(), expected); + save_token( + &manager, + "replacement", + /*refresh_token*/ None, + Utc::now().timestamp() + 3600, + ); + if !failed_login { + // A request may load the replacement before the next readiness read. + assert_eq!(manager.resolve_access_token().await.unwrap(), "replacement"); + } + assert_eq!( + manager.status().await.unwrap(), + GatewayAuthStatus::Succeeded + ); + assert_eq!(manager.resolve_access_token().await.unwrap(), "replacement"); + } + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn login_waits_for_background_credentials_and_can_cancel_while_queued() { + let server = MockServer::start().await; + let (manager, _home) = client(config(&server), Arc::new(MockKeyringStore::default())); + for cancel_while_queued in [true, false] { + // The credential mutex is also held by background resolution and refresh. + let cache_lock = Arc::clone(&manager.state.cached_token).lock_owned().await; + let cancel = tokio::sync::Notify::new(); + let (url_tx, mut url_rx) = tokio::sync::oneshot::channel(); + let login = manager.login_with_browser(cancel.notified(), |_| { + let _ = url_tx.send(()); + }); + tokio::pin!(login); + tokio::select! { + biased; + result = &mut login => panic!("login must wait for credentials: {result:?}"), + _ = std::future::ready(()) => {} + } + assert!(matches!( + url_rx.try_recv(), + Err(tokio::sync::oneshot::error::TryRecvError::Empty) + )); + let duplicate = manager + .login_with_browser(std::future::pending(), |_| panic!("duplicate browser")) + .await + .unwrap_err(); + assert_eq!( + duplicate + .get_ref() + .and_then(|error| error.downcast_ref::()) + .copied(), + Some(GatewayAuthError::LoginInProgress), + ); + if cancel_while_queued { + cancel.notify_one(); + let error = tokio::time::timeout(Duration::from_secs(/*secs*/ 2), &mut login) + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::Interrupted); + assert_eq!(manager.status().await.unwrap(), GatewayAuthStatus::NotReady); + drop(cache_lock); + } else { + drop(cache_lock); + let check = async { + url_rx.await.unwrap(); + assert_eq!(manager.status().await.unwrap(), GatewayAuthStatus::Started); + cancel.notify_one(); + }; + let (result, ()) = tokio::join!(login, check); + assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted); + } + } + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn legacy_policy_authorizes_missing_and_rejected_credentials() { + for reauthorize in [false, true] { + let server = MockServer::start().await; + let (manager, _home) = client(config(&server), Arc::new(MockKeyringStore::default())); + if reauthorize { + save_token( + &manager, + "rejected", + Some("revoked"), + Utc::now().timestamp() - 1, + ); + Mock::given(method("POST")) + .and(body_string_contains("grant_type=refresh_token")) + .respond_with( + ResponseTemplate::new(/*s*/ 400) + .set_body_json(json!({"error": "invalid_grant"})), + ) + .expect(/*r*/ 1) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(body_string_contains("grant_type=authorization_code")) + .respond_with( + ResponseTemplate::new(/*s*/ 200) + .set_body_json(json!({"access_token": "signed-in"})), + ) + .expect(/*r*/ 1) + .mount(&server) + .await; + assert_eq!( + manager + .resolve_with_browser(super::super::RefreshPolicy::WhenExpired, |_| panic!( + "explicit mode opened browser" + )) + .await + .unwrap_err() + .kind(), + std::io::ErrorKind::PermissionDenied + ); + manager.control.allow_automatic_login(); + assert_eq!( + manager + .resolve_with_browser( + super::super::RefreshPolicy::WhenExpired, + complete_browser_authorization + ) + .await + .unwrap(), + "signed-in" + ); + assert_eq!( + manager.status().await.unwrap(), + GatewayAuthStatus::Succeeded + ); + } +} diff --git a/codex-rs/login/src/gateway_auth_storage_tests.rs b/codex-rs/login/src/gateway_auth_storage_tests.rs new file mode 100644 index 0000000000..0548940fb4 --- /dev/null +++ b/codex-rs/login/src/gateway_auth_storage_tests.rs @@ -0,0 +1,204 @@ +//! Login cancellation and readiness stay responsive during blocked credential reads. + +use super::*; +use codex_keyring_store::CredentialStoreError; +use codex_keyring_store::KeyringStore; +use pretty_assertions::assert_eq; +use std::sync::Mutex; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; + +#[derive(Debug)] +struct BlockingKeyring { + inner: MockKeyringStore, + async_thread: std::thread::ThreadId, + check_thread: AtomicBool, + gate: Mutex< + Option<( + tokio::sync::oneshot::Sender<()>, + std::sync::mpsc::Receiver<()>, + )>, + >, +} + +impl BlockingKeyring { + fn check_thread(&self) { + if self.check_thread.load(Ordering::Relaxed) { + assert_ne!(std::thread::current().id(), self.async_thread); + } + } +} + +impl KeyringStore for BlockingKeyring { + fn load(&self, service: &str, account: &str) -> Result, CredentialStoreError> { + self.check_thread(); + let gate = self.gate.lock().unwrap().take(); + if let Some((entered, release)) = gate { + entered.send(()).unwrap(); + release + .recv_timeout(Duration::from_secs(/*secs*/ 30)) + .unwrap(); + } + self.inner.load(service, account) + } + + fn save(&self, service: &str, account: &str, value: &str) -> Result<(), CredentialStoreError> { + self.check_thread(); + self.inner.save(service, account, value) + } + + fn delete(&self, service: &str, account: &str) -> Result { + self.check_thread(); + self.inner.delete(service, account) + } +} + +fn blocking_client() -> (GatewayAuthManager, tempfile::TempDir, Arc) { + let home = tempfile::tempdir().unwrap(); + let keyring = Arc::new(BlockingKeyring { + inner: MockKeyringStore::default(), + async_thread: std::thread::current().id(), + check_thread: AtomicBool::new(/*v*/ false), + gate: Mutex::new(/*t*/ None), + }); + let manager = GatewayAuthManager::new( + loopback_config(), + home.path().to_path_buf(), + transport_default_auth_route_config().http_client_factory(), + keyring.clone(), + ) + .unwrap(); + (manager, home, keyring) +} + +#[tokio::test] +async fn readiness_does_not_block_cached_requests_or_overwrite_newer_credentials() { + let (manager, _home, keyring) = blocking_client(); + save_token(&manager, "old", /*refresh_token*/ None, i64::MAX); + assert_eq!(manager.resolve_access_token().await.unwrap(), "old"); + keyring.check_thread.store(/*val*/ true, Ordering::Relaxed); + let (entered_tx, entered_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + *keyring.gate.lock().unwrap() = Some((entered_tx, release_rx)); + let observer = manager.clone(); + let readiness = tokio::spawn(async move { observer.status().await }); + tokio::time::timeout(Duration::from_secs(/*secs*/ 2), entered_rx) + .await + .unwrap() + .unwrap(); + // The status read has captured the old encrypted file and is blocked in keyring I/O. + assert_eq!( + tokio::time::timeout( + Duration::from_secs(/*secs*/ 2), + manager.resolve_access_token() + ) + .await + .unwrap() + .unwrap(), + "old" + ); + let writer = manager.clone(); + tokio::task::spawn_blocking(move || { + save_token( + &writer, + "replacement", + /*refresh_token*/ None, + i64::MAX, + ); + }) + .await + .unwrap(); + assert_eq!( + tokio::time::timeout( + // Refresh decrypts the persisted replacement; only cached requests must be immediate. + Duration::from_secs(/*secs*/ 10), + manager.refresh_access_token("old"), + ) + .await + .unwrap() + .unwrap(), + "replacement" + ); + release_tx.send(()).unwrap(); + assert_eq!( + readiness.await.unwrap().unwrap(), + crate::GatewayAuthStatus::Succeeded + ); + assert_eq!(manager.resolve_access_token().await.unwrap(), "replacement"); +} + +#[tokio::test] +async fn cancel_during_keyring_read_releases_login_and_cached_credentials() { + let (manager, _home, keyring) = blocking_client(); + save_token(&manager, "existing", /*refresh_token*/ None, i64::MAX); + assert_eq!(manager.resolve_access_token().await.unwrap(), "existing"); + let mut events = manager.state.status_tx.subscribe(); + keyring.check_thread.store(/*val*/ true, Ordering::Relaxed); + let (entered_tx, entered_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + *keyring.gate.lock().unwrap() = Some((entered_tx, release_rx)); + let cancel = Arc::new(tokio::sync::Notify::new()); + let login_manager = manager.clone(); + let login_cancel = Arc::clone(&cancel); + let login = tokio::spawn(async move { + login_manager + .login_with_browser(login_cancel.notified(), |_| panic!("unexpected browser")) + .await + }); + tokio::time::timeout(Duration::from_secs(/*secs*/ 2), entered_rx) + .await + .unwrap() + .unwrap(); + let error = tokio::time::timeout( + Duration::from_secs(/*secs*/ 2), + manager.resolve_access_token(), + ) + .await + .expect("requests must not wait for login credential I/O") + .unwrap_err(); + assert_eq!( + error + .get_ref() + .and_then(|error| error.downcast_ref::()), + Some(&crate::GatewayAuthError::LoginInProgress), + ); + assert_eq!( + manager.status().await.unwrap(), + crate::GatewayAuthStatus::Started + ); + assert_eq!( + events.try_recv().unwrap().status, + crate::GatewayAuthStatus::Started + ); + cancel.notify_one(); + let error = tokio::time::timeout(Duration::from_secs(/*secs*/ 2), login) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::Interrupted); + assert_eq!( + events.try_recv().unwrap().status, + crate::GatewayAuthStatus::Failed { + message: "Gateway sign-in was canceled".into(), + } + ); + // Both request consumers and a new login must proceed before the keyring read returns. + assert_eq!( + tokio::time::timeout( + // Failed status makes the request reread and decrypt the stored credential. + Duration::from_secs(/*secs*/ 10), + manager.resolve_access_token() + ) + .await + .unwrap() + .unwrap(), + "existing" + ); + let error = manager + .login_with_browser(std::future::ready(()), |_| panic!("unexpected browser")) + .await + .unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::Interrupted); + release_tx.send(()).unwrap(); +} diff --git a/codex-rs/login/src/gateway_auth_tests.rs b/codex-rs/login/src/gateway_auth_tests.rs index e3b2dd4b49..53a68e8383 100644 --- a/codex-rs/login/src/gateway_auth_tests.rs +++ b/codex-rs/login/src/gateway_auth_tests.rs @@ -23,6 +23,12 @@ use super::StoredToken; use super::callback::CallbackListener; use crate::test_support::transport_default_auth_route_config; +#[path = "gateway_auth_login_tests.rs"] +mod login_tests; + +#[path = "gateway_auth_storage_tests.rs"] +mod storage_tests; + fn client( config: GatewayAuthConfig, keyring: Arc, @@ -35,6 +41,7 @@ fn client( keyring, ) .expect("gateway auth manager"); + manager.control.require_explicit_login(); (manager, home) } @@ -414,7 +421,13 @@ async fn query_credentials_are_not_exposed_by_echoed_errors_or_truncated_request json!({"error_description": format!("Unknown input: {secret}")}), ), ) - .expect(/*r*/ 1) + .expect( + if matches!(location, QueryLocation::AuthorizationEndpoint) { + 2 + } else { + 1 + }, + ) .mount(&server) .await; let mut oauth = config(&server); @@ -440,6 +453,27 @@ async fn query_credentials_are_not_exposed_by_echoed_errors_or_truncated_request assert!(message.contains("returned HTTP 503")); assert!(message.contains("provider response details omitted")); assert!(!message.contains("query-secret")); + if matches!(location, QueryLocation::AuthorizationEndpoint) { + let mut events = manager.state.status_tx.subscribe(); + let error = manager + .login_with_browser(std::future::pending(), complete_browser_authorization) + .await + .unwrap_err(); + let message = + "Gateway sign-in failed; check the gateway configuration and credential store."; + assert_eq!(error.to_string(), message); + let failed = crate::GatewayAuthStatus::Failed { + message: message.into(), + }; + assert_eq!(manager.status().await.unwrap(), failed); + assert_eq!( + events.try_recv().unwrap().status, + crate::GatewayAuthStatus::Started + ); + let event = events.try_recv().unwrap(); + assert_eq!(event.status, failed); + assert!(!format!("{error:?} {event:?}").contains("query-secret")); + } } } @@ -644,36 +678,6 @@ async fn ignores_mismatched_callback_state_even_for_provider_errors() { ); } -#[tokio::test] -async fn cancelled_callback_wait_releases_its_configured_port() { - let available_port = TcpListener::bind("127.0.0.1:0").expect("available callback port"); - let port = available_port - .local_addr() - .expect("callback address") - .port(); - drop(available_port); - let listener = - CallbackListener::new(Some(port), "expected-state".to_string()).expect("callback listener"); - - let callback_wait = tokio::spawn(async move { - let mut listener = listener; - listener.wait().await - }); - callback_wait.abort(); - let _ = callback_wait.await; - - tokio::time::timeout(Duration::from_secs(/*secs*/ 2), async { - loop { - if TcpListener::bind(("127.0.0.1", port)).is_ok() { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("cancelled callback released its listener"); -} - #[tokio::test] async fn rejects_insecure_or_credentialed_endpoints() { let keyring = Arc::new(MockKeyringStore::default()); @@ -707,86 +711,114 @@ fn accepts_ipv4_and_ipv6_loopback_endpoints() { } #[tokio::test] -async fn cancelled_refresh_still_persists_and_caches_rotated_credentials() { +async fn cancelled_refresh_still_records_rotated_or_rejected_credentials() { use tokio::io::AsyncBufReadExt; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("token listener"); - let endpoint = format!( - "http://{}/token", - listener.local_addr().expect("token address") - ); - let (accepted, received) = tokio::sync::oneshot::channel(); - let (release, response_ready) = tokio::sync::oneshot::channel(); - let server = tokio::spawn(async move { - let (mut stream, _) = listener.accept().await.expect("token request"); - let mut reader = tokio::io::BufReader::new(&mut stream); - let mut content_length = 0; - loop { - let mut line = String::new(); - assert!( - reader.read_line(&mut line).await.expect("request header") > 0, - "incomplete request headers" - ); - if line == "\r\n" { - break; - } - if let Some(length) = line.to_ascii_lowercase().strip_prefix("content-length:") { - content_length = length.trim().parse().expect("body length"); - } - } - reader - .read_exact(&mut vec![0; content_length]) + for rejected in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await - .expect("complete grant"); - accepted.send(()).expect("provider accepted rotation"); - response_ready - .await - .expect("caller cancelled before response"); - let body = - json!({"access_token": "new-access", "refresh_token": "new-refresh"}).to_string(); - stream + .expect("token listener"); + let endpoint = format!( + "http://{}/token", + listener.local_addr().expect("token address") + ); + let (accepted, received) = tokio::sync::oneshot::channel(); + let (release, response_ready) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.expect("token request"); + let mut reader = tokio::io::BufReader::new(&mut stream); + let mut content_length = 0; + loop { + let mut line = String::new(); + assert!( + reader.read_line(&mut line).await.expect("request header") > 0, + "incomplete request headers" + ); + if line == "\r\n" { + break; + } + if let Some(length) = line.to_ascii_lowercase().strip_prefix("content-length:") { + content_length = length.trim().parse().expect("body length"); + } + } + reader + .read_exact(&mut vec![0; content_length]) + .await + .expect("complete grant"); + accepted.send(()).expect("provider accepted rotation"); + response_ready + .await + .expect("caller cancelled before response"); + let (status, body) = if rejected { + ( + "400 Bad Request", + json!({"error": "invalid_grant"}).to_string(), + ) + } else { + ( + "200 OK", + json!({"access_token": "new-access", "refresh_token": "new-refresh"}) + .to_string(), + ) + }; + stream .write_all( format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len() ) .as_bytes(), ) .await .expect("rotated credentials"); - }); - let keyring = Arc::new(MockKeyringStore::default()); - let mut oauth = loopback_config(); - oauth.token_url = endpoint; - let (manager, _home) = client(oauth, keyring.clone()); - save_token( - &manager, - "old-access", - Some("old-refresh"), - Utc::now().timestamp() - 1, - ); - let caller = manager.clone(); - let task = tokio::spawn(async move { caller.resolve_access_token().await }); - received.await.expect("accepted refresh"); - task.abort(); - assert!(task.await.expect_err("cancelled caller").is_cancelled()); - release.send(()).expect("release response"); - server.await.expect("token response task"); - // Taking the same cache lock waits for the detached transaction to finish persisting. - let cached = manager.state.cached_token.lock().await; - let expected = json!({"access_token": "new-access", "refresh_token": "new-refresh"}); - assert_eq!( - serde_json::to_value(cached.token.as_ref()).expect("cached token"), - expected - ); - assert_eq!( - serde_json::to_value(manager.load_token().expect("persisted token")) - .expect("stored credential"), - expected - ); + }); + let keyring = Arc::new(MockKeyringStore::default()); + let mut oauth = loopback_config(); + oauth.token_url = endpoint; + let (manager, _home) = client(oauth, keyring.clone()); + save_token( + &manager, + "old-access", + Some("old-refresh"), + Utc::now().timestamp() + 3600, + ); + let caller = manager.clone(); + let task = tokio::spawn(async move { caller.refresh_access_token("old-access").await }); + received.await.expect("accepted refresh"); + task.abort(); + assert!(task.await.expect_err("cancelled caller").is_cancelled()); + release.send(()).expect("release response"); + server.await.expect("token response task"); + // Taking the same cache lock waits for the detached transaction to finish persisting. + let cached = Arc::clone(&manager.state.cached_token).lock_owned().await; + if rejected { + drop(cached); + assert_eq!( + manager.status().await.unwrap(), + crate::GatewayAuthStatus::NotReady + ); + assert_eq!( + manager.resolve_access_token().await.unwrap_err().kind(), + std::io::ErrorKind::PermissionDenied + ); + } else { + let expected = json!({"access_token": "new-access", "refresh_token": "new-refresh"}); + assert_eq!( + serde_json::to_value(cached.token.as_ref()).expect("cached token"), + expected + ); + assert_eq!( + serde_json::to_value(manager.load_token().expect("persisted token")) + .expect("stored credential"), + expected + ); + assert_eq!( + manager.status().await.unwrap(), + crate::GatewayAuthStatus::Succeeded + ); + } + } } #[tokio::test] @@ -824,7 +856,7 @@ async fn only_explicit_refresh_grant_rejections_request_reauthorization() { match (status, error_code) { (400, Some("invalid_grant" | "unauthorized_client" | "unsupported_grant_type")) => { - assert!(matches!(result, Ok(super::RefreshOutcome::Authorize))); + assert!(matches!(result, Ok(super::RefreshOutcome::LoginRequired))); } _ => { let message = result @@ -889,7 +921,7 @@ async fn invalid_grant_recovers_external_credentials_with_a_bounded_retry() { .refresh(&mut cached, &super::RefreshPolicy::WhenExpired) .await .expect("bounded recovery"), - super::RefreshOutcome::Authorize + super::RefreshOutcome::LoginRequired )); } else { let expected = if retry_status.is_some() { diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index 931bd1657a..abbbf1d897 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -76,4 +76,9 @@ pub use outbound_proxy::AuthRouteConfig; pub use token_data::TokenData; pub use gateway_auth::GatewayAuthConfig; +pub use gateway_auth::GatewayAuthError; pub use gateway_auth::GatewayAuthManager; +pub use gateway_auth::GatewayAuthStatus; +pub use gateway_auth::GatewayAuthStatusChange; +pub use gateway_auth::GatewayLoginControl; +pub use gateway_auth::subscribe_gateway_auth_status; diff --git a/codex-rs/model-provider/src/combined_auth.rs b/codex-rs/model-provider/src/combined_auth.rs index d1cd2d3979..513d82836c 100644 --- a/codex-rs/model-provider/src/combined_auth.rs +++ b/codex-rs/model-provider/src/combined_auth.rs @@ -8,6 +8,7 @@ use codex_api::AuthHeadersFuture; use codex_api::AuthProvider; use codex_api::AuthProviderFuture; use codex_api::SharedAuthProvider; +use codex_login::GatewayAuthError; use codex_login::GatewayAuthManager; use codex_model_provider_info::GatewayOAuthConfig; use codex_model_provider_info::GatewayOAuthDelivery; @@ -34,13 +35,19 @@ pub(crate) async fn compose_auth( .as_ref() .map_err(|error| CodexErr::InvalidRequest(error.clone()))?; let token = manager.resolve_access_token().await.map_err(|error| { - // Issuer errors may echo arbitrary credentials from configured URLs. Keep the - // diagnostic safe and bounded for callers that return it as tool output. - std::io::Error::new( - error.kind(), - "Gateway OAuth authentication failed; check the gateway configuration and credential store.", - ) - })?; + if let Some(login_error) = error + .get_ref() + .and_then(|source| source.downcast_ref::()) + { + return CodexErr::InvalidRequest(login_error.to_string()); + } + // Issuer errors may echo arbitrary credentials from configured URLs. Keep the + // diagnostic safe and bounded, preserving retries for transient failures. + CodexErr::Io(std::io::Error::new( + error.kind(), + "Gateway OAuth authentication failed; check the gateway configuration and credential store.", + )) + })?; let (name, value) = gateway_header(config, &token)?; if resolved.auth.to_auth_headers().contains_key(&name) { return Err(CodexErr::InvalidRequest( diff --git a/codex-rs/model-provider/src/shared_state_tests.rs b/codex-rs/model-provider/src/shared_state_tests.rs index 09caa4cf87..e58edd0ef8 100644 --- a/codex-rs/model-provider/src/shared_state_tests.rs +++ b/codex-rs/model-provider/src/shared_state_tests.rs @@ -236,6 +236,7 @@ async fn gateway_refresh_preserves_primary_auth_and_hides_issuer_errors() { Ok(_) => panic!("issuer failure should fail auth"), Err(error) => error, }; + assert!(error.retry_delay(/*retry_count*/ 1).is_some()); assert_eq!( error.to_string(), "Gateway OAuth authentication failed; check the gateway configuration and credential store." @@ -524,3 +525,60 @@ async fn gateway_setup_errors_are_reported_when_authentication_is_requested() { )); assert!(server.received_requests().await.unwrap().is_empty()); } + +#[tokio::test] +async fn gateway_login_states_stop_request_retries() { + let server = MockServer::start().await; + let home = tempfile::tempdir().unwrap(); + let primary = AuthManager::from_auth_for_testing_with_home( + CodexAuth::from_api_key("primary-token"), + home.path().to_path_buf(), + ); + let info = ModelProviderInfo { + gateway_oauth: Some(GatewayOAuthConfig { + authorization_url: format!("{}/authorize", server.uri()), + token_url: format!("{}/token", server.uri()), + client_id: "client".into(), + resource: None, + scopes: vec![], + redirect_port: None, + delivery: GatewayOAuthDelivery::Header { + name: "x-gateway-auth".into(), + scheme: "Bearer".into(), + }, + }), + ..ModelProviderInfo::create_openai_provider(Some(server.uri())) + }; + let login_control = codex_login::GatewayLoginControl::for_runtime(&primary.runtime_config()); + login_control.require_explicit_login(); + let provider = create_model_provider(info, Some(primary)); + let gateway = provider.gateway_auth_manager().unwrap().unwrap(); + let error = provider.api_auth().await.err().expect("login required"); + assert_eq!( + (error.to_string(), error.retry_delay(/*retry_count*/ 1)), + ( + codex_login::GatewayAuthError::LoginRequired.to_string(), + None + ), + ); + let cancel = tokio::sync::Notify::new(); + let (url_tx, url_rx) = tokio::sync::oneshot::channel(); + let login = gateway.login_with_browser(cancel.notified(), |_| { + let _ = url_tx.send(()); + }); + let check = async { + url_rx.await.unwrap(); + let error = provider.api_auth().await.err().expect("login in progress"); + assert_eq!( + (error.to_string(), error.retry_delay(/*retry_count*/ 1)), + ( + codex_login::GatewayAuthError::LoginInProgress.to_string(), + None + ), + ); + cancel.notify_one(); + }; + let (result, ()) = tokio::join!(login, check); + assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted); + assert!(server.received_requests().await.unwrap().is_empty()); +}