diff --git a/codex-rs/app-server/src/in_process_bootstrap.rs b/codex-rs/app-server/src/in_process_bootstrap.rs index 2ca9c9cb2c..13ebae598f 100644 --- a/codex-rs/app-server/src/in_process_bootstrap.rs +++ b/codex-rs/app-server/src/in_process_bootstrap.rs @@ -20,26 +20,31 @@ impl EmbeddedNetworkPolicy { /// Loads the local rules for cloud bootstrap; all other traffic starts unavailable. pub async fn load(overrides: &codex_config::LoaderOverrides) -> Self { let policy = Self::default(); - let local = async { - codex_config::loader::load_local_application_requirements( - codex_exec_server::LOCAL_FS.as_ref(), - overrides, - ) - .await? - .compose(Default::default()) - } - .await; - if let Ok(application) = local { - policy.local.publish( - policy.local.policy().revision(), - crate::config_manager::application_network::destination_policy( - application.as_ref(), - ), - ); - } + let _ = policy.refresh_local(overrides).await; policy } + /// Updates bootstrap clients with the current local administrator network rules. + pub async fn refresh_local(&self, overrides: &codex_config::LoaderOverrides) -> IoResult<()> { + let revision = self.local.policy().revision(); + let application = codex_config::loader::load_local_application_requirements( + codex_exec_server::LOCAL_FS.as_ref(), + overrides, + ) + .await + .and_then(|sources| sources.compose(Default::default())) + .inspect_err(|_| self.local.unavailable(revision))?; + if !self.local.publish( + revision, + crate::config_manager::application_network::destination_policy(application.as_ref()), + ) { + return Err(IoError::other( + codex_http_client::NetworkPolicyDenied::Revoked, + )); + } + Ok(()) + } + /// Attaches the live application policy before an environment can start connecting. pub fn bind( &self, diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index 4e951a5350..c48a4f5140 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -215,6 +215,32 @@ fn finish_login(result: std::io::Result<()>) -> ! { } } +async fn ensure_config_server_resolution_current( + cli_config_overrides: &CliConfigOverrides, + resolution: &codex_config::ConfigServerResolution, +) -> std::io::Result<()> { + let overrides = cli_config_overrides + .parse_overrides() + .map_err(std::io::Error::other)?; + let current = Config::load_with_cli_overrides(overrides).await?; + let routes = current.auth_route_config(); + let factory = routes.bootstrap_http_client_factory(); + if current + .config_layer_stack + .requirements_toml() + .config_server + .as_ref() + != Some(&resolution.configured) + || factory.outbound_proxy_policy() != resolution.outbound_proxy_policy + || factory.allows_system_proxy_fallback() != resolution.system_proxy_fallback + { + return Err(std::io::Error::other( + "Config server settings changed during sign-in. Run codex login again.", + )); + } + Ok(()) +} + async fn run_interactive_login( cli_config_overrides: CliConfigOverrides, config_server_login_method: ConfigServerLoginMethod, @@ -223,24 +249,51 @@ async fn run_interactive_login( where F: std::future::Future>, { - let mut config = load_config_or_exit(cli_config_overrides.clone()).await; - if !config + let config = load_config_or_exit(cli_config_overrides.clone()).await; + let Some(server) = config .config_layer_stack .requirements_toml() - .requires_remote_config() - { + .config_server + .as_ref() + else { let _login_log_guard = init_login_file_logging(&config); finish_login(chatgpt_login(config).await); - } + }; - let result = sign_in_to_config_server_and_reload_config( - &mut config, - &cli_config_overrides, - config_server_login_method, + let network = codex_app_server::in_process::EmbeddedNetworkPolicy::load( + &codex_config::LoaderOverrides::default(), ) .await; - let _login_log_guard = init_login_file_logging(&config); - finish_login(result) + let result = codex_cloud_config::login_to_config_server( + network.bind_bootstrap_auth(config.auth_config()), + server, + config_server_login_method, + async |resolution| { + ensure_config_server_resolution_current(&cli_config_overrides, resolution).await?; + network.refresh_local(&Default::default()).await + }, + async |loader| { + let resolution = loader.config_server_resolution().cloned().ok_or_else(|| { + std::io::Error::other("Config server resolution missing during sign-in") + })?; + let overrides = cli_config_overrides + .parse_overrides() + .map_err(std::io::Error::other)?; + let loaded = codex_core::config::ConfigBuilder::default() + .codex_home(config.codex_home.to_path_buf()) + .cli_overrides(overrides) + .cloud_config_bundle(loader) + .build_with_validation(|_, _, stack| stack.ensure_config_server_applied()) + .await?; + loaded.validate_windows_mxc_requirement()?; + loaded.auth_config().validate()?; + ensure_config_server_resolution_current(&cli_config_overrides, &resolution).await?; + Ok(loaded) + }, + ) + .await; + let _login_log_guard = init_login_file_logging(result.as_ref().unwrap_or(&config)); + finish_login(result.map(|_| ())) } pub async fn run_login_with_browser(cli_config_overrides: CliConfigOverrides) -> ! { @@ -598,7 +651,10 @@ async fn logout_config_server( ) .await? { - Some((_, Some(manager))) => manager.logout().await, + Some((_, Some(manager))) => { + let _attempt = manager.try_start_login()?; + manager.logout().await + } Some((_, None)) | None => Ok(false), } } @@ -615,6 +671,15 @@ pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! { } else { Ok(false) }; + if let Err(error) = &config_server_logout + && error + .get_ref() + .and_then(|source| source.downcast_ref::()) + == Some(&codex_login::OAuthSessionError::LoginInProgress) + { + eprintln!("Error logging out: {error}"); + std::process::exit(1); + } // Cleanup is independent of the current feature gate. Retain the grant lock // through account removal so another process cannot commit a late login. @@ -781,6 +846,47 @@ mod tests { insta::assert_snapshot!(config_server_device_code_message(&prompt), @"To sign in to the config server, open https://login.example/device and enter code ABCD-EFGH."); } + #[tokio::test] + async fn logout_config_server_rejects_an_in_progress_first_login() -> anyhow::Result<()> { + let home = tempdir()?; + let requirements_path = home.path().join("requirements.toml"); + std::fs::write( + &requirements_path, + 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 = "cli" +"#, + )?; + let overrides = LoaderOverrides { + system_requirements_path: Some(requirements_path), + ignore_project_config: true, + ..LoaderOverrides::without_managed_config_for_tests() + }; + let config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .loader_overrides(overrides.clone()) + .build() + .await?; + let network = codex_app_server::in_process::EmbeddedNetworkPolicy::load(&overrides).await; + let (_, manager) = codex_cloud_config::managed_config_auth_manager( + network.bind_bootstrap_auth(config.auth_config()), + config.config_layer_stack.requirements_toml(), + ) + .await? + .expect("config server"); + let _attempt = manager.as_ref().unwrap().try_start_login()?; + + let error = logout_config_server(&config, &overrides) + .await + .expect_err("first login still owns the grant reservation"); + assert_eq!(error.kind(), ErrorKind::WouldBlock); + Ok(()) + } + #[tokio::test] async fn logout_config_server_respects_local_network_policy() -> anyhow::Result<()> { let home = tempdir()?; diff --git a/codex-rs/cloud-config/src/bundle_loader.rs b/codex-rs/cloud-config/src/bundle_loader.rs index 362a247f83..352ee19555 100644 --- a/codex-rs/cloud-config/src/bundle_loader.rs +++ b/codex-rs/cloud-config/src/bundle_loader.rs @@ -39,7 +39,7 @@ pub async fn managed_config_auth_manager( .map(Some) } -/// How to sign in when the config server has no saved OAuth grant. +/// How to authorize with the config server. pub enum ConfigServerLoginMethod { Browser, DeviceCode { present: fn(&OAuthDeviceCodePrompt) }, @@ -67,6 +67,14 @@ pub(crate) async fn ensure_config_server_login_with_manager( let Some(attempt) = manager.start_login_if_required().await? else { return Ok(()); }; + sign_in(manager, attempt, method).await +} + +pub(crate) async fn sign_in( + manager: &OAuthSessionManager, + attempt: codex_login::OAuthLoginAttempt<'_>, + method: ConfigServerLoginMethod, +) -> std::io::Result<()> { match method { ConfigServerLoginMethod::Browser => attempt.login(CONFIG_SERVER_LOGIN_FAILURE).await, ConfigServerLoginMethod::DeviceCode { present } => { diff --git a/codex-rs/cloud-config/src/config_server.rs b/codex-rs/cloud-config/src/config_server.rs index a351298a7b..9187c9673d 100644 --- a/codex-rs/cloud-config/src/config_server.rs +++ b/codex-rs/cloud-config/src/config_server.rs @@ -52,6 +52,60 @@ pub async fn config_server_bundle_loader( } } +/// Replace credentials only after the caller applies policy for the new grant. +pub async fn login_to_config_server( + auth: codex_login::AuthConfig, + config: &ConfigServer, + method: crate::ConfigServerLoginMethod, + before_fetch: impl AsyncFnOnce(&ConfigServerResolution) -> std::io::Result<()>, + apply_policy: impl AsyncFnOnce(CloudConfigBundleLoader) -> std::io::Result, +) -> std::io::Result { + let (service, resolution) = create_config_server_service( + config, + &auth.codex_home, + &auth.auth_route_config, + /*previous*/ None, + ) + .await + .map_err(std::io::Error::other)?; + let before_fetch_resolution = resolution.clone(); + service + .login( + method, + async || before_fetch(&before_fetch_resolution).await, + async |loader: CloudConfigBundleLoader| { + apply_policy(loader.with_config_server_resolution(resolution)).await + }, + ) + .await +} + +impl CloudConfigBundleService { + async fn login( + mut self, + method: crate::ConfigServerLoginMethod, + before_fetch: impl AsyncFnOnce() -> std::io::Result<()>, + apply_policy: impl AsyncFnOnce(CloudConfigBundleLoader) -> std::io::Result, + ) -> std::io::Result { + let Some(manager) = self.source.auth.take() else { + before_fetch().await?; + return apply_policy(managed_config_bundle_loader_for_service(self).0).await; + }; + let mut attempt = manager.try_start_login()?; + let (config, publish_cache) = attempt + .replace_login(async |candidate, attempt| { + crate::bundle_loader::sign_in(candidate, attempt, method).await?; + before_fetch().await?; + self.source.auth = Some(candidate.clone()); + let (loader, publish_cache) = Box::pin(self.load_for_login()).await?; + Ok((apply_policy(loader).await?, publish_cache)) + }) + .await?; + publish_cache.await; + Ok(config) + } +} + /// Git must apply the same policy as Codex without opening the OS keyring. /// Use the checked resolution directly so a second discovery cannot select OAuth. pub async fn anonymous_config_server_bundle_loader( diff --git a/codex-rs/cloud-config/src/config_server_tests.rs b/codex-rs/cloud-config/src/config_server_tests.rs index 2e2a070a5d..91fe9d5b7f 100644 --- a/codex-rs/cloud-config/src/config_server_tests.rs +++ b/codex-rs/cloud-config/src/config_server_tests.rs @@ -192,20 +192,31 @@ async fn policy_fetch_uses_replacement_config_server_credentials() { "expires_in": 60, "interval": 1, }))) - .expect(1) + .expect(6) .mount(&server) .await; - let sign_in = AtomicUsize::new(0); + let sign_ins = AtomicUsize::new(0); Mock::given(method("POST")) .and(path("/token")) .and(form_has_field(resource_field)) - .respond_with(move |_: &wiremock::Request| { + .respond_with(move |request: &wiremock::Request| { + if request + .body + .split(|byte| *byte == b'&') + .any(|field| field == b"grant_type=refresh_token") + { + return ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"})); + } + let sign_in = sign_ins.fetch_add(1, Ordering::Relaxed); + if sign_in == 1 { + return ResponseTemplate::new(400).set_body_json(json!({"error": "access_denied"})); + } ResponseTemplate::new(200).set_body_json(json!({ - "access_token": format!("account-{}", sign_in.fetch_add(1, Ordering::Relaxed)), + "access_token": format!("account-{sign_in}"), + "refresh_token": format!("refresh-{sign_in}"), "token_type": "Bearer", "expires_in": 3600, })) }) - .expect(2) .mount(&server) .await; let policies = ["never", "on-request"].map(|approval| { @@ -214,17 +225,45 @@ async fn policy_fetch_uses_replacement_config_server_credentials() { )) .into_bundle() }); - for (account, policy) in policies.iter().enumerate() { + let conflicting_policy = + CloudConfigBundleFixture::enterprise_config("forced_login_method = 'chatgpt'") + .into_bundle(); + for (account, policy) in [ + (0, &policies[0]), + (3, &conflicting_policy), + (4, &policies[1]), + (5, &policies[0]), + ] { Mock::given(path("/settings/codex/config/bundle")) .and(header("authorization", format!("Bearer account-{account}"))) .respond_with(ResponseTemplate::new(200).set_body_json(policy)) .mount(&server) .await; } + Mock::given(path("/settings/codex/config/bundle")) + .and(header("authorization", "Bearer account-2")) + .respond_with(ResponseTemplate::new(403)) + .expect(1..) + .mount(&server) + .await; + Mock::given(path("/settings/codex/config/bundle")) + .and(header("authorization", "Bearer account-6")) + .respond_with(ResponseTemplate::new(403)) + .expect(0) + .mount(&server) + .await; let home = tempdir().unwrap(); + let requirements_path = home.path().join("requirements.toml"); + std::fs::write(&requirements_path, "allowed_login_methods = ['api']").unwrap(); + let network = codex_http_client::NetworkPolicyController::default(); + assert!(network.publish( + network.policy().revision(), + codex_http_client::DestinationPolicy::Unrestricted, + )); let factory = transport_default_auth_route_config() .http_client_factory() - .clone(); + .clone() + .with_network_policy(network.policy()); let oauth = OAuthSessionConfig { device_authorization_url: Some(format!("{}/oauth/device", server.uri())), resource: Some(resource.into()), @@ -251,7 +290,7 @@ async fn policy_fetch_uses_replacement_config_server_credentials() { .await .expect("device sign-in should complete") .unwrap(); - let source = ConfigServerSource { + let source = || ConfigServerSource { cache_namespace: "test".into(), client: BackendClient::for_config_endpoint( format!("{}/settings", server.uri()), @@ -259,15 +298,77 @@ async fn policy_fetch_uses_replacement_config_server_credentials() { ), auth: Some(manager().without_interactive_login()), }; - let service = CloudConfigBundleService::from_source( - source, - home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); + let new_service = || { + CloudConfigBundleService::from_source( + source(), + home.path().to_path_buf(), + CLOUD_CONFIG_BUNDLE_TIMEOUT, + ) + }; + let service = new_service(); + let saved_grant = auth.authorization_id().await.unwrap(); + let device = || ConfigServerLoginMethod::DeviceCode { + present: |prompt| assert_eq!(prompt.user_code, "ABCD-EFGH"), + }; assert_eq!( service.load_startup_bundle_with_timeout().await.unwrap(), Some(policies[0].clone()) ); + ensure_config_server_login_with_manager(&manager(), device()) + .await + .unwrap(); + let login = async || { + new_service() + .login( + device(), + async || Ok(()), + async |loader| loader.get().await.map_err(std::io::Error::other), + ) + .await + }; + for _ in 0..2 { + assert!(login().await.is_err()); + assert_eq!(manager().authorization_id().await.unwrap(), saved_grant); + } + let rejected = new_service() + .login( + device(), + async || Ok(()), + async |loader| { + let loaded = codex_core::config::ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .loader_overrides(codex_config::LoaderOverrides { + system_requirements_path: Some(requirements_path.clone()), + ignore_project_config: true, + ..codex_config::LoaderOverrides::without_managed_config_for_tests() + }) + .cloud_config_bundle(loader) + .build() + .await?; + assert_eq!(manager().authorization_id().await.unwrap(), saved_grant); + loaded.validate_windows_mxc_requirement()?; + loaded.auth_config().validate() + }, + ) + .await; + assert_eq!( + rejected.unwrap_err().kind(), + std::io::ErrorKind::PermissionDenied + ); + assert_eq!(manager().resolve_access_token().await.unwrap(), "account-0"); + assert_eq!( + new_service().get_latest().await.unwrap(), + Some(policies[0].clone()) + ); + assert!(auth.refresh_access_token("account-0").await.is_err()); + assert_eq!(login().await.unwrap(), Some(policies[1].clone())); + let restarted = manager(); + assert_ne!(restarted.authorization_id().await.unwrap(), saved_grant); + assert_eq!(restarted.resolve_access_token().await.unwrap(), "account-4"); + assert_eq!( + new_service().get_latest().await.unwrap(), + Some(policies[1].clone()) + ); auth.login_with_browser(std::future::pending(), complete_browser_authorization) .await @@ -275,8 +376,26 @@ async fn policy_fetch_uses_replacement_config_server_credentials() { // The old access token is still valid, so this must detect the changed grant. assert_eq!( service.load_startup_bundle_with_timeout().await.unwrap(), - Some(policies[1].clone()) + Some(policies[0].clone()) ); + let saved_grant = manager().authorization_id().await.unwrap(); + let denied = new_service() + .login( + device(), + async || { + assert!(network.publish( + network.policy().revision(), + codex_http_client::DestinationPolicy::Restricted { + allowed_hosts: Default::default(), + }, + )); + Ok(()) + }, + async |loader| loader.get().await.map_err(std::io::Error::other), + ) + .await; + assert!(denied.is_err()); + assert_eq!(manager().authorization_id().await.unwrap(), saved_grant); server.verify().await; } diff --git a/codex-rs/cloud-config/src/lib.rs b/codex-rs/cloud-config/src/lib.rs index 0a641133ea..e5b582b5e4 100644 --- a/codex-rs/cloud-config/src/lib.rs +++ b/codex-rs/cloud-config/src/lib.rs @@ -26,3 +26,4 @@ pub use bundle_loader::managed_config_bundle_loader_for_storage; pub use config_server::anonymous_config_server_bundle_loader; pub use config_server::config_server_auth_manager; pub use config_server::config_server_bundle_loader; +pub use config_server::login_to_config_server; diff --git a/codex-rs/cloud-config/src/service.rs b/codex-rs/cloud-config/src/service.rs index 00c67c3613..3fbe67bbb9 100644 --- a/codex-rs/cloud-config/src/service.rs +++ b/codex-rs/cloud-config/src/service.rs @@ -52,7 +52,7 @@ enum CachedBundleLookup { } pub(crate) struct CloudConfigBundleService { - source: S, + pub(crate) source: S, cache: CloudConfigBundleCache, cache_enabled: bool, codex_home: AbsolutePathBuf, @@ -102,6 +102,36 @@ impl CloudConfigBundleService { self } + /// Fetch once without reading or replacing the previous grant's cached policy. + pub(crate) async fn load_for_login( + mut self, + ) -> std::io::Result<( + codex_config::CloudConfigBundleLoader, + impl Future, + )> { + let cache_enabled = self.cache_enabled; + self.cache_enabled = false; + let snapshot = self.get_latest_snapshot().await; + let bundle = snapshot + .bundle + .clone() + .map_err(std::io::Error::other)? + .unwrap_or_default(); + let auth = self.source.auth().await.map_err(std::io::Error::other)?; + let publish_cache = async move { + if cache_enabled + && let Some(auth) = auth + && let Some(revision) = self.policy.observe_remote_bundle(&bundle) + { + self.cache_bundle(&auth, bundle, revision).await; + } + }; + Ok(( + codex_config::CloudConfigBundleLoader::from_snapshot(snapshot), + publish_cache, + )) + } + pub(crate) async fn get_latest( &self, ) -> Result, CloudConfigBundleLoadError> { @@ -378,21 +408,10 @@ impl CloudConfigBundleService { return Err(err); } - let (chatgpt_user_id, account_id) = self.source.identity(auth); if self.cache_enabled && let Some(revision) = revision { - let result = match self - .cache - .prepare(chatgpt_user_id, account_id, bundle.clone()) - .await - { - Ok(staged) => staged.publish_if_current(revision).await, - Err(err) => Err(err), - }; - if let Err(err) = result { - tracing::warn!(error = %err, "Failed to write cloud config bundle cache"); - } + self.cache_bundle(auth, bundle.clone(), revision).await; } emit_fetch_final_metric( @@ -406,6 +425,26 @@ impl CloudConfigBundleService { Ok(optional_bundle(bundle)) } + async fn cache_bundle( + &self, + auth: &S::Auth, + bundle: CloudConfigBundle, + revision: codex_config::CloudConfigBundlePolicyRevision, + ) { + let (chatgpt_user_id, account_id) = self.source.identity(auth); + let result = match self + .cache + .prepare(chatgpt_user_id, account_id, bundle) + .await + { + Ok(staged) => staged.publish_if_current(revision).await, + Err(err) => Err(err), + }; + if let Err(err) = result { + tracing::warn!(error = %err, "Failed to write cloud config bundle cache"); + } + } + async fn retry_after_request_failure( &self, trigger: &'static str, diff --git a/codex-rs/login/src/oauth_session_login.rs b/codex-rs/login/src/oauth_session_login.rs index 419998d785..a40c9563f8 100644 --- a/codex-rs/login/src/oauth_session_login.rs +++ b/codex-rs/login/src/oauth_session_login.rs @@ -128,7 +128,8 @@ pub(super) fn status_sender_for_host( } impl OAuthSessionManager { - pub(super) fn try_start_login(&self) -> io::Result> { + /// Reserve a sign-in without changing the saved grant. + pub fn try_start_login(&self) -> io::Result> { Ok(OAuthLoginAttempt { manager: self, _lock: storage::try_lock_login(&self.state.codex_home, &self.credential_id())?, @@ -464,6 +465,62 @@ impl OAuthSessionManager { } impl OAuthLoginAttempt<'_> { + /// Runs sign-in and validation against an isolated grant. Neither the token nor + /// success notifications reach other consumers until validation succeeds. + pub async fn replace_login( + &mut self, + validate: impl AsyncFnOnce(&OAuthSessionManager, OAuthLoginAttempt<'_>) -> io::Result, + ) -> io::Result { + let manager = self.manager; + let candidate = OAuthSessionManager { + state: Arc::new(OAuthSessionState { + config: manager.state.config.clone(), + codex_home: manager.state.codex_home.clone(), + storage: OAuthSessionStorage::InMemory(Default::default()), + http_client: manager.state.http_client.clone(), + http_client_factory: manager.state.http_client_factory.clone(), + cached_token: Default::default(), + status: tokio::sync::watch::channel(/*init*/ None).0, + status_tx: broadcast::channel(/*capacity*/ 1).0, + }), + allow_interactive_login: false, + ..manager.clone() + }; + let attempt = OAuthLoginAttempt { + manager: &candidate, + // Keep the original reservation through validation and cache publication. + _lock: self._lock.try_clone()?, + }; + let previous = manager.load_token_async().await?; + let result = validate(&candidate, attempt).await?; + let token = candidate + .load_token()? + .ok_or_else(|| io::Error::other("No replacement OAuth grant"))?; + + let mut cached = manager.lock_cached_token().await?; + let lock = Arc::new(storage::lock_credentials(&manager.state.codex_home).await?); + let current = manager.load_token_async().await?; + // Refresh can rotate the old token during validation. Respect a concurrent logout. + if previous != current + && !previous + .as_ref() + .zip(current.as_ref()) + .is_some_and(|(old, new)| { + old.authorization_id.is_some() && old.authorization_id == new.authorization_id + }) + { + return Err(io::Error::other("Saved OAuth grant changed during sign-in")); + } + let mut replacement = OAuthSessionCache { + pending: Some(token), + ..Default::default() + }; + manager.persist_pending(&mut replacement, &lock).await?; + *cached = replacement; + manager.publish_status(OAuthSessionStatus::Succeeded, cached.token.as_ref()); + Ok(result) + } + pub async fn login(self, failure_message: &'static str) -> io::Result<()> { self.manager .login_with_method( diff --git a/codex-rs/login/src/oauth_session_storage.rs b/codex-rs/login/src/oauth_session_storage.rs index cce7cb3290..ec77c8acc2 100644 --- a/codex-rs/login/src/oauth_session_storage.rs +++ b/codex-rs/login/src/oauth_session_storage.rs @@ -74,6 +74,7 @@ pub(super) async fn lock_credentials(codex_home: &Path) -> io::Result { pub(super) enum OAuthSessionStorage { Keyring(SecretsManager), File(PathBuf), + InMemory(std::sync::Mutex>), } impl OAuthSessionStorage { @@ -105,6 +106,10 @@ impl OAuthSessionStorage { .map(|value| serde_json::from_str(&value).map_err(invalid_credentials)) .transpose(), Self::File(path) => Ok(read_tokens(path)?.remove(credential_id)), + Self::InMemory(token) => Ok(token + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone()), } } @@ -121,6 +126,12 @@ impl OAuthSessionStorage { tokens.insert(credential_id.to_owned(), token.clone()); write_atomically(path, &serde_json::to_string(&tokens)?) } + Self::InMemory(saved) => { + *saved + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(token.clone()); + Ok(()) + } } } @@ -137,6 +148,11 @@ impl OAuthSessionStorage { } Ok(removed) } + Self::InMemory(token) => Ok(token + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + .is_some()), } } }