From 19e95b9be87c6066d8070f5414dd08c45de7a0d3 Mon Sep 17 00:00:00 2001 From: cooper-oai Date: Wed, 25 Nov 2026 01:01:41 +0000 Subject: [PATCH] Fix API workload identity authentication at startup and refresh (#63808) ## Why Installing workload identity credentials at startup can revoke the network policy already configured for them. The managed model provider also expects a ChatGPT account identity, which API workload identity credentials lack. ## What changed - Preserve the configured network policy while installing the initial credentials. Later changes in credential ownership still revoke the policy. - Bind managed API authentication to its initial credential owner so requests can use renewed workload identity tokens for the same service account, organization, and project. ## Testing Add regression tests for preserving network restrictions and existing permits at startup, revoking permits when the owner changes, and rejecting header generation and unauthorized recovery after an API key owner change, even if the original key is selected again. GitOrigin-RevId: 25b748863064334e622097c04d74e1fbee4b8a0b --- codex-rs/login/src/auth/auth_tests.rs | 53 +++++++++++++++++++++ codex-rs/login/src/auth/manager.rs | 20 ++++++-- codex-rs/model-provider/src/auth.rs | 16 +++++++ codex-rs/model-provider/src/auth_tests.rs | 58 +++++++++++++++++++++++ 4 files changed, 143 insertions(+), 4 deletions(-) diff --git a/codex-rs/login/src/auth/auth_tests.rs b/codex-rs/login/src/auth/auth_tests.rs index 9a3df938f4..4c951275e9 100644 --- a/codex-rs/login/src/auth/auth_tests.rs +++ b/codex-rs/login/src/auth/auth_tests.rs @@ -1650,6 +1650,59 @@ impl ExternalAuth for RefreshingExternalAuth { } } +#[tokio::test] +async fn initial_external_auth_preserves_policy_until_owner_changes() { + let codex_home = tempdir().unwrap(); + let controller = codex_http_client::NetworkPolicyController::default(); + let policy = controller.policy(); + assert!(controller.publish( + policy.revision(), + codex_http_client::DestinationPolicy::Restricted { + allowed_hosts: std::collections::BTreeSet::from(["allowed.example".to_string()]), + }, + )); + let allowed = "https://allowed.example/".parse().unwrap(); + let blocked = "https://blocked.example/".parse().unwrap(); + let permit = policy.acquire(&allowed).unwrap(); + let manager = AuthManager::new( + codex_home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::Ephemeral, + /*forced_chatgpt_workspace_id*/ None, + /*chatgpt_base_url*/ None, + AuthKeyringBackendKind::default(), + AuthRouteConfig::from_http_client_factory( + crate::test_support::transport_default_auth_route_config() + .http_client_factory() + .clone() + .with_network_policy(policy.clone()), + ), + ) + .await + .with_initial_external_auth(Arc::new(RefreshingExternalAuth { + initial: CodexAuth::from_api_key("initial-owner"), + refreshed: CodexAuth::from_api_key("another-owner"), + })) + .await + .unwrap(); + + assert_eq!( + manager.auth_cached().unwrap().api_key(), + Some("initial-owner") + ); + assert!(permit.check().is_ok()); + assert!(policy.acquire(&allowed).is_ok()); + assert!(policy.acquire(&blocked).is_err()); + + manager.refresh_token().await.unwrap(); + assert_eq!( + manager.auth_cached().unwrap().api_key(), + Some("another-owner") + ); + assert!(permit.check().is_err()); + assert!(policy.acquire(&allowed).is_err()); +} + fn external_header_auth(account_id: Option<&'static str>) -> CodexAuth { let mut headers = http::HeaderMap::new(); headers.insert( diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 02b652e3c9..05fbadd6cc 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -3255,6 +3255,19 @@ impl AuthManager { self.install_external_auth(external_auth).await } + async fn with_initial_external_auth( + mut self, + external_auth: Arc, + ) -> Result { + // Hydrate startup credentials before this manager is shared. Initial WIF + // selection must not revoke policy composed for those credentials. + let owns_network_policy = self.owns_network_policy; + self.owns_network_policy = false; + self.install_external_auth(external_auth).await?; + self.owns_network_policy = owns_network_policy; + Ok(self) + } + async fn install_external_auth( &self, external_auth: Arc, @@ -3452,13 +3465,12 @@ impl AuthManager { manager.owns_network_policy = matches!(network_policy_ownership, NetworkPolicyOwnership::Primary); manager.workload_identity_selected = external_auth.is_some(); - let manager = Arc::new(manager); if let Some(external_auth) = external_auth { - manager - .install_external_auth(Arc::new(external_auth)) + manager = manager + .with_initial_external_auth(Arc::new(external_auth)) .await?; } - Ok(manager) + Ok(Arc::new(manager)) } pub fn unauthorized_recovery(self: &Arc) -> UnauthorizedRecovery { diff --git a/codex-rs/model-provider/src/auth.rs b/codex-rs/model-provider/src/auth.rs index 78c2497907..f974571564 100644 --- a/codex-rs/model-provider/src/auth.rs +++ b/codex-rs/model-provider/src/auth.rs @@ -16,6 +16,7 @@ use codex_http_client::HttpClientFactory; use codex_http_client::RouteAwareClientPool; use codex_login::AuthHeaders; use codex_login::AuthManager; +use codex_login::AuthOwner; use codex_login::CodexAuth; use codex_login::auth::AgentIdentityAuth; use codex_login::auth::AgentIdentityAuthError; @@ -209,10 +210,19 @@ struct AuthManagerAuthProvider { // Startup auth is only the account-scoped identity anchor. Request // headers always come from the current AuthManager snapshot below. expected_auth: CodexAuth, + expected_api_owner: Option, } impl AuthManagerAuthProvider { fn is_expected_auth(&self, auth: &CodexAuth) -> bool { + if self.expected_auth.is_api_key_auth() { + // API WIF has no ChatGPT account ID. Its owner survives token renewal + // only within the same service account, organization, and project. + return auth.is_api_key_auth() + && self.expected_api_owner.as_ref().is_some_and(|owner| { + self.auth_manager.auth_owner_for(auth).as_ref() == Some(owner) + }); + } auth.uses_codex_backend() && auth.get_account_id() == self.expected_auth.get_account_id() && auth.get_chatgpt_user_id() == self.expected_auth.get_chatgpt_user_id() @@ -550,9 +560,15 @@ pub fn auth_provider_from_auth_manager( auth_manager: Arc, expected_auth: &CodexAuth, ) -> SharedAuthProvider { + let expected_api_owner = if expected_auth.is_api_key_auth() { + auth_manager.auth_owner_for(expected_auth) + } else { + None + }; Arc::new(AuthManagerAuthProvider { auth_manager, expected_auth: expected_auth.clone(), + expected_api_owner, }) } diff --git a/codex-rs/model-provider/src/auth_tests.rs b/codex-rs/model-provider/src/auth_tests.rs index 754ac33a7d..01dd410710 100644 --- a/codex-rs/model-provider/src/auth_tests.rs +++ b/codex-rs/model-provider/src/auth_tests.rs @@ -5,6 +5,7 @@ use codex_login::AuthCredentialsStoreMode; use codex_login::AuthKeyringBackendKind; use codex_login::auth::AgentIdentityAuthRecord; use codex_login::auth::BedrockApiKeyAuth; +use codex_login::auth::login_with_api_key; use codex_login::auth::login_with_chatgpt_auth_tokens; use codex_model_provider_info::WireApi; use codex_model_provider_info::create_oss_provider_with_base_url; @@ -399,6 +400,63 @@ async fn auth_manager_provider_follows_refreshes_but_not_account_switches() { )); } +#[tokio::test] +async fn auth_manager_api_provider_stays_bound_to_its_initial_owner() { + let codex_home = tempfile::tempdir().unwrap(); + login_with_api_key( + codex_home.path(), + "initial-token", + AuthCredentialsStoreMode::Ephemeral, + AuthKeyringBackendKind::default(), + ) + .unwrap(); + let manager = Arc::new( + AuthManager::new( + codex_home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::Ephemeral, + /*forced_chatgpt_workspace_id*/ None, + /*chatgpt_base_url*/ None, + AuthKeyringBackendKind::default(), + codex_login::test_support::transport_default_auth_route_config(), + ) + .await, + ); + let initial = manager.auth_cached().unwrap(); + let provider = auth_provider_from_auth_manager(manager.clone(), &initial); + let headers = HeaderMap::from_iter([( + AUTHORIZATION, + HeaderValue::from_static("Bearer initial-token"), + )]); + assert_eq!(provider.to_auth_headers().unwrap(), headers); + assert_eq!( + provider.apply_auth_headers(HeaderMap::new()).await.unwrap(), + headers + ); + + // A new login retires the original owner, even if its token is selected again. + for token in ["another-token", "initial-token"] { + login_with_api_key( + codex_home.path(), + token, + AuthCredentialsStoreMode::Ephemeral, + AuthKeyringBackendKind::default(), + ) + .unwrap(); + manager.reload().await; + assert_eq!(manager.auth_cached().unwrap().api_key(), Some(token)); + assert!(matches!( + provider.to_auth_headers(), + Err(AuthError::Transient(_)) + )); + assert!(matches!( + provider.apply_auth_headers(HeaderMap::new()).await, + Err(AuthError::Transient(_)) + )); + assert!(!provider.refresh_after_unauthorized(headers.clone()).await); + } +} + #[derive(Clone, Copy)] enum RefreshFailure { Transient,