diff --git a/codex-rs/app-server/src/account_notifications_tests.rs b/codex-rs/app-server/src/account_notifications_tests.rs index fba40deacc..744acf03ab 100644 --- a/codex-rs/app-server/src/account_notifications_tests.rs +++ b/codex-rs/app-server/src/account_notifications_tests.rs @@ -50,6 +50,7 @@ async fn queued_notifications_follow_auth_owner_changes(owner_generation: u64) { changes.send_replace(AuthChangeState { generation: 2, owner_generation, + source_generation: owner_generation, }); rx.recv().await.unwrap(); send.await; diff --git a/codex-rs/login/src/auth/change_state.rs b/codex-rs/login/src/auth/change_state.rs index 27d13992bd..168572bcf8 100644 --- a/codex-rs/login/src/auth/change_state.rs +++ b/codex-rs/login/src/auth/change_state.rs @@ -8,8 +8,12 @@ pub struct AuthChangeState { /// Advances whenever cached credentials change. pub generation: u64, /// Advances on login, logout, or changes of user, workspace, or auth mode. + /// A verified legacy-to-OAuth credential migration preserves the same owner. /// Credential changes with incomplete owner identity also advance this revision. pub owner_generation: u64, + /// Advances on an underlying actor credential/source change, including a new OAuth login. + /// Ordinary refresh within an identifiable OAuth session preserves this revision. + pub source_generation: u64, } pub(super) fn same_owner(previous: Option<&CodexAuth>, current: Option<&CodexAuth>) -> bool { diff --git a/codex-rs/login/src/auth/change_state_tests.rs b/codex-rs/login/src/auth/change_state_tests.rs index 25abff139a..ffc355a729 100644 --- a/codex-rs/login/src/auth/change_state_tests.rs +++ b/codex-rs/login/src/auth/change_state_tests.rs @@ -58,6 +58,7 @@ fn auth_owner_generation_distinguishes_refreshes_from_identity_changes() { AuthChangeState { generation, owner_generation, + source_generation: generation, }, ); assert_eq!(*legacy_changes.borrow_and_update(), generation); @@ -79,6 +80,7 @@ async fn auth_owner_generation_preserves_logout_and_switches_when_coalesced() { AuthChangeState { generation: 2, owner_generation: 2, + source_generation: 2, }, ); @@ -89,6 +91,7 @@ async fn auth_owner_generation_preserves_logout_and_switches_when_coalesced() { AuthChangeState { generation: 4, owner_generation: 4, + source_generation: 4, }, ); } diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 7bfae6c8bb..2d676069b1 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -954,7 +954,11 @@ fn persist_agent_identity_record( .ok_or_else(|| std::io::Error::other("auth data is not available"))?; auth.agent_identity = Some(AgentIdentityStorage::Record(record)); storage.save(&auth)?; - *guard = Some(auth); + // Publishing credentials belongs to AuthManager. Persisting identity metadata must + // not reload different on-disk credentials into already selected auth values. + if let Some(cached) = guard.as_mut() { + cached.agent_identity = auth.agent_identity; + } Ok(()) } @@ -2385,6 +2389,15 @@ impl AuthManager { .and_then(|cached| cached.auth.clone()) } + /// Current revisions if the selected credential still belongs to this manager's source. + pub fn auth_change_state_for(&self, expected: &CodexAuth) -> Option { + let cached = self.inner.read().ok()?; + if !super::source::same_source(cached.auth.as_ref(), Some(expected)) { + return None; + } + Some(*self.auth_change_state_tx.borrow()) + } + /// Subscribes to cached auth changes that can affect request recovery. pub fn auth_change_receiver(&self) -> watch::Receiver { self.auth_change_tx.subscribe() @@ -2653,6 +2666,8 @@ impl AuthManager { !Self::auths_equal_for_refresh(previous, new_auth.as_ref()); let owner_changed = auth_changed_for_refresh && !same_owner(previous, new_auth.as_ref()); + let source_changed = auth_changed_for_refresh + && !super::source::same_source(previous, new_auth.as_ref()); if owner_changed { self.auth_route_config .application_network_policy() @@ -2669,6 +2684,9 @@ impl AuthManager { if owner_changed { state.owner_generation += 1; } + if source_changed { + state.source_generation += 1; + } }); self.auth_change_tx.send_modify(|revision| *revision += 1); } @@ -3191,3 +3209,7 @@ mod change_state_tests; #[cfg(test)] #[path = "account_user_id_tests.rs"] mod account_user_id_tests; + +#[cfg(test)] +#[path = "source_tests.rs"] +mod source_tests; diff --git a/codex-rs/login/src/auth/mod.rs b/codex-rs/login/src/auth/mod.rs index 226255f39e..68184e17ab 100644 --- a/codex-rs/login/src/auth/mod.rs +++ b/codex-rs/login/src/auth/mod.rs @@ -7,6 +7,7 @@ mod change_state; pub mod default_client; pub mod error; mod personal_access_token; +mod source; mod storage; mod util; mod workload_identity; diff --git a/codex-rs/login/src/auth/source.rs b/codex-rs/login/src/auth/source.rs new file mode 100644 index 0000000000..afe03ea705 --- /dev/null +++ b/codex-rs/login/src/auth/source.rs @@ -0,0 +1,77 @@ +//! Compare actor credential sources for local runtime reuse, not server authentication. +//! +//! OAuth session claims are only continuity hints. The registration service verifies +//! the credential and binds the runtime; these values never grant authority locally. + +use super::CodexAuth; +use crate::token_data::decode_jwt_payload; +use serde::Deserialize; + +pub(super) fn same_source(previous: Option<&CodexAuth>, current: Option<&CodexAuth>) -> bool { + let (Some(previous), Some(current)) = (previous, current) else { + return false; + }; + if previous.api_auth_mode() != current.api_auth_mode() + || previous.get_account_id() != current.get_account_id() + || previous.get_chatgpt_user_id() != current.get_chatgpt_user_id() + { + return false; + } + let (Ok(previous_token), Ok(current_token)) = (previous.get_token(), current.get_token()) + else { + return false; + }; + if previous_token == current_token { + return true; + } + match previous { + CodexAuth::Chatgpt(_) | CodexAuth::ChatgptAuthTokens(_) => { + if previous_token.split('.').count() != 3 || current_token.split('.').count() != 3 { + return false; + } + let (Ok(previous), Ok(current)) = ( + decode_jwt_payload::(&previous_token), + decode_jwt_payload::(¤t_token), + ) else { + // Sessionless credentials must refresh during bootstrap before a + // source-bound runtime can be registered. Never guess continuity. + return false; + }; + !previous.iss.trim().is_empty() + && !previous.session_id.trim().is_empty() + && previous == current + } + CodexAuth::ApiKey(_) + | CodexAuth::PersonalAccessToken(_) + | CodexAuth::Headers(_) + | CodexAuth::AgentIdentity(_) + | CodexAuth::BedrockApiKey(_) + | CodexAuth::BedrockAccessKeys(_) => false, + } +} + +#[derive(Deserialize, PartialEq, Eq)] +struct OAuthSource { + iss: String, + session_id: String, + sub: Option, + client_id: Option, + azp: Option, + #[serde(rename = "https://api.openai.com/auth", default)] + identity: OAuthIdentity, +} + +#[derive(Default, Deserialize, PartialEq, Eq)] +struct OAuthIdentity { + user_id: Option, + chatgpt_user_id: Option, + chatgpt_account_id: Option, + chatgpt_account_user_id: Option, + chatgpt_backing_organization_id: Option, + wif_identity_provider_id: Option, + wif_federation_rule_id: Option, + wif_tenant_id: Option, + wif_external_issuer: Option, + wif_principal_kind: Option, + wif_product: Option, +} diff --git a/codex-rs/login/src/auth/source_tests.rs b/codex-rs/login/src/auth/source_tests.rs new file mode 100644 index 0000000000..76ab4bcd2b --- /dev/null +++ b/codex-rs/login/src/auth/source_tests.rs @@ -0,0 +1,181 @@ +//! Runtime reuse follows the credential source, not just its owner or token bytes. + +use super::*; +use base64::Engine; +use pretty_assertions::assert_eq; +use serde_json::json; + +fn oauth(session: &str, token: &str) -> CodexAuth { + let claims = json!({ + "iss": "https://auth.openai.com/", + "session_id": session, + "sub": "user-a", + "jti": token, + "https://api.openai.com/auth": { + "user_id": "user-a", "chatgpt_account_id": "workspace-a" + }, + }); + from_claims(claims, "workspace-a") +} + +fn from_claims(claims: serde_json::Value, workspace: &str) -> CodexAuth { + let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string()); + CodexAuth::from_external_chatgpt_tokens( + &format!("header.{payload}.signature"), + workspace, + /*chatgpt_plan_type*/ None, + ) + .unwrap() +} + +#[test] +fn refreshed_credentials_reuse_the_source_but_a_new_login_does_not() { + let original = oauth("login-a", "token-1"); + let manager = AuthManager::from_auth_for_testing(original.clone()); + let initial = manager.auth_change_state_for(&original).unwrap(); + manager.set_cached_auth(Some(oauth("login-a", "token-2"))); + let refreshed = manager.auth_change_state_for(&original).unwrap(); + assert_ne!(initial.generation, refreshed.generation); + assert_eq!(initial.source_generation, refreshed.source_generation); + + manager.set_cached_auth(Some(oauth("login-b", "token-3"))); + assert!(manager.auth_change_state_for(&original).is_none()); + // Returning to an earlier credential does not revive its retired runtime. + manager.set_cached_auth(Some(original.clone())); + assert_ne!( + initial.source_generation, + manager + .auth_change_state_for(&original) + .unwrap() + .source_generation + ); +} + +#[test] +fn token_rotation_does_not_hide_a_resource_or_workload_change() { + let original = oauth("login-a", "token-1"); + let token = original.get_token().unwrap(); + let payload = token.split('.').nth(1).unwrap(); + let claims: serde_json::Value = serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload) + .unwrap(), + ) + .unwrap(); + for path in [ + vec!["iss"], + vec!["sub"], + vec!["client_id"], + vec!["https://api.openai.com/auth", "user_id"], + vec![ + "https://api.openai.com/auth", + "chatgpt_backing_organization_id", + ], + vec!["https://api.openai.com/auth", "wif_federation_rule_id"], + ] { + let manager = AuthManager::from_auth_for_testing(original.clone()); + let mut changed = claims.clone(); + let mut value = &mut changed; + for component in path { + value = &mut value[component]; + } + *value = json!("changed"); + manager.set_cached_auth(Some(from_claims(changed, "workspace-a"))); + assert!(manager.auth_change_state_for(&original).is_none()); + } + let manager = AuthManager::from_auth_for_testing(original.clone()); + manager.set_cached_auth(Some(from_claims(claims, "workspace-b"))); + assert!(manager.auth_change_state_for(&original).is_none()); +} + +#[test] +fn a_sessionless_token_cannot_claim_refresh_continuity() { + let claims = json!({"https://api.openai.com/auth": {"user_id": "user-a"}, "jti": "one"}); + let original = from_claims(claims.clone(), "workspace-a"); + let manager = AuthManager::from_auth_for_testing(original.clone()); + assert!(manager.auth_change_state_for(&original).is_some()); + let mut changed = claims; + changed["jti"] = json!("two"); + manager.set_cached_auth(Some(from_claims(changed, "workspace-a"))); + assert!(manager.auth_change_state_for(&original).is_none()); +} + +#[test] +fn api_key_replacement_and_logout_retire_the_previous_source() { + let key_a = CodexAuth::from_api_key("key-a"); + let key_b = CodexAuth::from_api_key("key-b"); + let manager = AuthManager::from_auth_for_testing(key_a.clone()); + let first = manager.auth_change_state_for(&key_a).unwrap(); + manager.set_cached_auth(Some(key_a.clone())); + assert_eq!(first, manager.auth_change_state_for(&key_a).unwrap()); + manager.set_cached_auth(Some(key_b.clone())); + assert!(manager.auth_change_state_for(&key_a).is_none()); + let second = manager.auth_change_state_for(&key_b).unwrap(); + manager.set_cached_auth(/*new_auth*/ None); + assert!(manager.auth_change_state_for(&key_b).is_none()); + manager.set_cached_auth(Some(key_b.clone())); + assert_ne!( + second.source_generation, + manager + .auth_change_state_for(&key_b) + .unwrap() + .source_generation + ); +} + +#[tokio::test] +#[serial_test::serial(codex_auth_env)] +async fn legacy_identity_persistence_does_not_reload_credentials() -> anyhow::Result<()> { + let home = tempfile::tempdir()?; + let storage = create_auth_storage( + home.path().to_path_buf(), + AuthCredentialsStoreMode::File, + AuthKeyringBackendKind::Direct, + ); + let original = oauth("login-a", "token-1"); + let replacement = oauth("login-b", "token-2"); + let mut stored = original.get_current_auth_json().unwrap(); + stored.auth_mode = Some(AuthMode::Chatgpt); + stored.last_refresh = Some(chrono::Utc::now()); + storage.save(&stored)?; + let manager = AuthManager::shared( + home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*forced_chatgpt_workspace_id*/ None, + /*chatgpt_base_url*/ None, + AuthKeyringBackendKind::Direct, + crate::test_support::transport_default_auth_route_config(), + ) + .await; + let captured = manager.auth_cached().unwrap(); + let initial = manager.auth_change_state_for(&captured).unwrap(); + stored.tokens = replacement.get_current_auth_json().unwrap().tokens; + storage.save(&stored)?; + let stored = storage.load()?.unwrap(); + let identity = serde_json::from_value(json!({ + "agent_runtime_id": "legacy-runtime", + "agent_private_key": codex_agent_identity::generate_agent_key_material()?.private_key_pkcs8_base64, + "account_id": "workspace-a", "chatgpt_user_id": "user-a", "plan_type": "pro", + "chatgpt_account_is_fedramp": false, "task_id": "legacy-task", + }))?; + captured.persist_managed_chatgpt_agent_identity_record(identity)?; + assert_eq!(captured.get_token()?, original.get_token()?); + assert_eq!(manager.auth_change_state_for(&captured), Some(initial)); + assert_eq!(storage.load()?.unwrap().tokens, stored.tokens); + manager.reload().await; + assert_eq!( + manager.auth_cached().unwrap().get_token()?, + replacement.get_token()? + ); + assert_ne!( + initial.source_generation, + manager + .auth_change_state_receiver() + .borrow() + .source_generation + ); + assert!(manager.auth_change_state_for(&captured).is_none()); + assert_eq!(captured.get_token()?, original.get_token()?); + Ok(()) +} diff --git a/codex-rs/login/src/token_data.rs b/codex-rs/login/src/token_data.rs index 3bfdb9f167..203700a379 100644 --- a/codex-rs/login/src/token_data.rs +++ b/codex-rs/login/src/token_data.rs @@ -141,7 +141,7 @@ pub enum IdTokenInfoError { Json(#[from] serde_json::Error), } -fn decode_jwt_payload(jwt: &str) -> Result { +pub(crate) fn decode_jwt_payload(jwt: &str) -> Result { // JWT format: header.payload.signature let mut parts = jwt.split('.'); let (_header_b64, payload_b64, _sig_b64) = match (parts.next(), parts.next(), parts.next()) {