From f83e13db553c0f4ab0d9f1b83434db8a21df8b6a Mon Sep 17 00:00:00 2001 From: celia-oai Date: Tue, 16 Jun 2026 17:27:23 -0700 Subject: [PATCH] changes --- codex-rs/app-server/README.md | 3 +- codex-rs/app-server/src/request_processors.rs | 1 + .../request_processors/account_processor.rs | 44 +++++---- .../src/request_processors/bedrock_auth.rs | 49 +--------- .../src/request_processors/plugins.rs | 1 - codex-rs/app-server/tests/suite/v2/account.rs | 92 +++++++++---------- codex-rs/login/src/auth/auth_tests.rs | 2 +- codex-rs/login/src/auth/bedrock_api_key.rs | 63 +++++++++++++ .../login/src/auth/bedrock_api_key_tests.rs | 26 ++++-- codex-rs/login/src/auth/manager.rs | 28 ++---- codex-rs/login/src/lib.rs | 2 +- codex-rs/model-provider/src/lib.rs | 4 +- 12 files changed, 167 insertions(+), 148 deletions(-) diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index e267167eee..4fdef79ccd 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1928,7 +1928,7 @@ Codex supports these authentication modes. The current mode is surfaced in `acco - `account/login/start` — begin login (`apiKey`, `chatgpt`, `chatgptDeviceCode`, `amazonBedrock`). - `account/login/completed` (notify) — emitted when a login attempt finishes (success or error). - `account/login/cancel` — cancel a pending managed ChatGPT login by `loginId`. -- `account/logout` — sign out without params; also clears Codex-managed Amazon Bedrock credentials on a best-effort basis; triggers `account/updated` when the OpenAI auth mode changes. +- `account/logout` — sign out without params; also clears Codex-managed Amazon Bedrock credentials on a best-effort basis; triggers `account/updated` after successful logout. - `account/updated` (notify) — emitted whenever auth mode changes (`authMode`: `apikey`, `bedrockApiKey`, `chatgpt`, `personalAccessToken`, or `null`) and includes the current ChatGPT `planType` when available. - `account/rateLimits/read` — fetch ChatGPT rate limits, an optional effective monthly credit limit, and the earned rate-limit resets currently available, including expiry details when provided by the backend. Rate-limit updates arrive via `account/rateLimits/updated` (notify); reset-credit data is snapshot-only. - `account/rateLimitResetCredit/consume` — consume one earned reset using a caller-provided idempotency key, optionally selecting a reset-credit ID returned by `account/rateLimits/read`. @@ -2019,6 +2019,7 @@ This experimental flow requires the client to initialize with `experimentalApi: 3. Notifications: ```json { "method": "account/login/completed", "params": { "loginId": null, "success": true, "error": null } } + { "method": "account/updated", "params": { "authMode": "bedrockApiKey", "planType": null } } ``` Codex stores the key and region in its configured auth store and writes `model_provider = "amazon-bedrock"` to the active user config. diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 5b205f07d1..119ea61790 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -36,6 +36,7 @@ use codex_app_server_protocol::AppTemplateUnavailableReason; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; use codex_app_server_protocol::AskForApproval; +use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::CancelLoginAccountParams; use codex_app_server_protocol::CancelLoginAccountResponse; use codex_app_server_protocol::CancelLoginAccountStatus; diff --git a/codex-rs/app-server/src/request_processors/account_processor.rs b/codex-rs/app-server/src/request_processors/account_processor.rs index eeb80bdab3..02999e29a5 100644 --- a/codex-rs/app-server/src/request_processors/account_processor.rs +++ b/codex-rs/app-server/src/request_processors/account_processor.rs @@ -1,6 +1,6 @@ -use super::bedrock_auth::has_managed_login as has_managed_bedrock_login; -use super::bedrock_auth::login as login_managed_bedrock; -use super::bedrock_auth::logout as logout_managed_bedrock; +use super::bedrock_auth::clear_user_model_provider_if_bedrock; +use super::bedrock_auth::set_user_model_provider_to_bedrock; +use super::bedrock_auth::user_model_provider_state; use super::*; use crate::auth_mode::auth_mode_to_api; use chrono::DateTime; @@ -184,9 +184,9 @@ impl AccountRequestProcessor { fn current_account_updated_notification(&self) -> AccountUpdatedNotification { let auth = self.auth_manager.auth_cached(); AccountUpdatedNotification { - auth_mode: auth - .as_ref() - .map(CodexAuth::api_auth_mode) + auth_mode: self + .auth_manager + .account_auth_mode_cached() .map(auth_mode_to_api), plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), } @@ -382,8 +382,13 @@ impl AccountRequestProcessor { } } - login_managed_bedrock(&self.config, &self.config_manager, api_key, region).await?; - self.auth_manager.reload().await; + self.auth_manager + .login_with_bedrock_api_key(api_key, region) + .await + .map_err(|err| { + internal_error(format!("failed to save Amazon Bedrock auth: {err}")) + })?; + set_user_model_provider_to_bedrock(&self.config_manager).await?; Ok(LoginAccountResponse::AmazonBedrock {}) } .await; @@ -777,9 +782,17 @@ impl AccountRequestProcessor { } } - if has_managed_bedrock_login(&self.config)? { - logout_managed_bedrock(&self.config, &self.config_manager).await?; - self.auth_manager.reload().await; + if self + .auth_manager + .has_stored_bedrock_api_key_auth() + .map_err(|err| internal_error(format!("failed to read stored auth: {err}")))? + { + let user_model_provider = user_model_provider_state(&self.config_manager).await?; + self.auth_manager + .logout() + .await + .map_err(|err| internal_error(format!("logout failed: {err}")))?; + clear_user_model_provider_if_bedrock(&self.config_manager, user_model_provider).await?; return Ok(None); } if self.config.model_provider.is_amazon_bedrock() { @@ -810,12 +823,8 @@ impl AccountRequestProcessor { } async fn logout_v2(&self, request_id: ConnectionRequestId) -> Result<(), JSONRPCErrorError> { - let skip_account_updated = matches!(has_managed_bedrock_login(&self.config), Ok(true)) - || self.config.model_provider.is_amazon_bedrock(); let result = self.logout_common().await; - let account_updated = if skip_account_updated { - None - } else { + let account_updated = result .as_ref() .ok() @@ -823,8 +832,7 @@ impl AccountRequestProcessor { .map(|auth_mode| AccountUpdatedNotification { auth_mode, plan_type: None, - }) - }; + }); self.outgoing .send_result(request_id, result.map(|_| LogoutAccountResponse {})) .await; diff --git a/codex-rs/app-server/src/request_processors/bedrock_auth.rs b/codex-rs/app-server/src/request_processors/bedrock_auth.rs index eb2cf51223..333d905d95 100644 --- a/codex-rs/app-server/src/request_processors/bedrock_auth.rs +++ b/codex-rs/app-server/src/request_processors/bedrock_auth.rs @@ -6,37 +6,16 @@ use codex_app_server_protocol::ConfigReadParams; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::MergeStrategy; -use codex_core::config::Config; -use codex_login::AuthDotJson; -use codex_login::load_auth_dot_json; -use codex_login::login_with_bedrock_api_key; -use codex_login::logout as logout_stored_auth; use codex_model_provider::AMAZON_BEDROCK_PROVIDER_ID; -struct UserModelProviderState { +pub(super) struct UserModelProviderState { model_provider: Option, version: Option, } -pub(super) fn has_managed_login(config: &Config) -> Result { - load_stored_auth(config).map(|auth| auth.is_some()) -} - -pub(super) async fn login( - config: &Config, +pub(super) async fn set_user_model_provider_to_bedrock( config_manager: &ConfigManager, - api_key: &str, - region: &str, ) -> Result<(), JSONRPCErrorError> { - login_with_bedrock_api_key( - &config.codex_home, - api_key, - region, - config.cli_auth_credentials_store_mode, - config.auth_keyring_backend_kind(), - ) - .map_err(|err| internal_error(format!("failed to save Amazon Bedrock auth: {err}")))?; - write_user_model_provider( config_manager, serde_json::json!(AMAZON_BEDROCK_PROVIDER_ID), @@ -45,18 +24,10 @@ pub(super) async fn login( .await } -pub(super) async fn logout( - config: &Config, +pub(super) async fn clear_user_model_provider_if_bedrock( config_manager: &ConfigManager, + user_model_provider: UserModelProviderState, ) -> Result<(), JSONRPCErrorError> { - let user_model_provider = user_model_provider_state(config_manager).await?; - logout_stored_auth( - &config.codex_home, - config.cli_auth_credentials_store_mode, - config.auth_keyring_backend_kind(), - ) - .map_err(|err| internal_error(format!("logout failed: {err}")))?; - if user_model_provider.model_provider.as_deref() == Some(AMAZON_BEDROCK_PROVIDER_ID) { write_user_model_provider( config_manager, @@ -69,17 +40,7 @@ pub(super) async fn logout( Ok(()) } -fn load_stored_auth(config: &Config) -> Result, JSONRPCErrorError> { - load_auth_dot_json( - &config.codex_home, - config.cli_auth_credentials_store_mode, - config.auth_keyring_backend_kind(), - ) - .map(|auth| auth.filter(AuthDotJson::is_bedrock_api_key)) - .map_err(|err| internal_error(format!("failed to read stored auth: {err}"))) -} - -async fn user_model_provider_state( +pub(super) async fn user_model_provider_state( config_manager: &ConfigManager, ) -> Result { let user_config_path = config_manager diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index c291f5055f..35c12d49c1 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -19,7 +19,6 @@ use codex_core_plugins::remote::RemoteAppTemplateUnavailableReason; use codex_core_plugins::remote::is_valid_remote_plugin_id; use codex_core_plugins::remote::validate_remote_plugin_id; use codex_core_plugins::remote_bundle::RemotePluginBundleInstallError; -use codex_login::AuthMode; use codex_mcp::McpOAuthLoginSupport; use codex_mcp::oauth_login_support; use codex_mcp::should_retry_without_scopes; diff --git a/codex-rs/app-server/tests/suite/v2/account.rs b/codex-rs/app-server/tests/suite/v2/account.rs index 0a2e34410b..cb0e570a29 100644 --- a/codex-rs/app-server/tests/suite/v2/account.rs +++ b/codex-rs/app-server/tests/suite/v2/account.rs @@ -49,6 +49,7 @@ use codex_login::login_with_api_key; use codex_login::login_with_bedrock_api_key; use codex_protocol::account::AmazonBedrockCredentialSource; use codex_protocol::account::PlanType as AccountPlanType; +use codex_protocol::auth::AuthMode as DomainAuthMode; use core_test_support::responses; use pretty_assertions::assert_eq; use serde_json::json; @@ -192,15 +193,26 @@ async fn read_account(mcp: &mut TestAppServer) -> Result { to_response(response) } -async fn assert_no_account_updated(mcp: &mut TestAppServer) { - assert!( - timeout( - Duration::from_millis(500), - mcp.read_stream_until_notification_message("account/updated"), - ) - .await - .is_err() +async fn assert_account_updated( + mcp: &mut TestAppServer, + auth_mode: Option, +) -> Result<()> { + let notification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + let ServerNotification::AccountUpdated(payload) = notification.try_into()? else { + bail!("unexpected notification") + }; + assert_eq!( + payload, + AccountUpdatedNotification { + auth_mode, + plan_type: None, + } ); + Ok(()) } async fn mock_device_code_usercode(server: &MockServer, interval_seconds: u64) { @@ -1039,6 +1051,9 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu AuthCredentialsStoreMode::File, AuthKeyringBackendKind::default(), )?; + let mut mcp = + TestAppServer::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; let mut expected_config = read_config_toml(codex_home.path())?; expected_config .as_table_mut() @@ -1053,10 +1068,6 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu .expect("config should be a table") .remove("model_provider"); - let mut mcp = - TestAppServer::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; - let request_id = mcp .send_login_account_amazon_bedrock_request(" managed-bedrock-api-key ", " us-west-2 ") .await?; @@ -1073,7 +1084,7 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu assert_eq!( load_file_auth(codex_home.path())?, Some(AuthDotJson { - auth_mode: Some(AuthMode::BedrockApiKey), + auth_mode: Some(DomainAuthMode::BedrockApiKey), openai_api_key: None, tokens: None, last_refresh: None, @@ -1103,21 +1114,7 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu error: None, } ); - let notification = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("account/updated"), - ) - .await??; - let ServerNotification::AccountUpdated(payload) = notification.try_into()? else { - bail!("unexpected notification") - }; - assert_eq!( - payload, - AccountUpdatedNotification { - auth_mode: Some(AuthMode::BedrockApiKey), - plan_type: None, - } - ); + assert_account_updated(&mut mcp, Some(AuthMode::BedrockApiKey)).await?; assert_eq!( read_account(&mut mcp).await?, GetAccountResponse { @@ -1141,7 +1138,7 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu read_config_toml(codex_home.path())?, expected_config_after_logout ); - assert_no_account_updated(&mut mcp).await; + assert_account_updated(&mut mcp, None).await?; assert_eq!( read_account(&mut mcp).await?, GetAccountResponse { @@ -1203,6 +1200,7 @@ async fn managed_bedrock_login_requires_experimental_api_but_logout_is_best_effo LogoutAccountResponse {} ); assert_eq!(load_file_auth(codex_home.path())?, None); + assert_account_updated(&mut mcp, None).await?; Ok(()) } @@ -1237,11 +1235,7 @@ async fn login_and_logout_managed_bedrock_update_active_provider() -> Result<()> mcp.read_stream_until_notification_message("account/login/completed"), ) .await??; - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_notification_message("account/updated"), - ) - .await??; + assert_account_updated(&mut mcp, Some(AuthMode::BedrockApiKey)).await?; assert_eq!( read_account(&mut mcp).await?, GetAccountResponse { @@ -1266,7 +1260,7 @@ async fn login_and_logout_managed_bedrock_update_active_provider() -> Result<()> assert_eq!(load_file_auth(codex_home.path())?, None); assert_eq!(read_config_toml(codex_home.path())?, expected_config); - assert_no_account_updated(&mut mcp).await; + assert_account_updated(&mut mcp, None).await?; assert_eq!( read_account(&mut mcp).await?, GetAccountResponse { @@ -1290,11 +1284,11 @@ async fn logout_account_aws_managed_bedrock_preserves_openai_auth_and_config() - AuthKeyringBackendKind::default(), )?; let expected_auth = load_file_auth(codex_home.path())?; - let expected_config = read_config_toml(codex_home.path())?; let mut mcp = TestAppServer::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + let expected_config = read_config_toml(codex_home.path())?; let request_id = mcp.send_logout_account_request().await?; let response: JSONRPCResponse = timeout( @@ -1308,7 +1302,7 @@ async fn logout_account_aws_managed_bedrock_preserves_openai_auth_and_config() - ); assert_eq!(load_file_auth(codex_home.path())?, expected_auth); assert_eq!(read_config_toml(codex_home.path())?, expected_config); - assert_no_account_updated(&mut mcp).await; + assert_account_updated(&mut mcp, None).await?; Ok(()) } @@ -1390,7 +1384,7 @@ async fn login_account_amazon_bedrock_allows_codex_environment_auth() -> Result< assert_eq!( load_file_auth(codex_home.path())?, Some(AuthDotJson { - auth_mode: Some(AuthMode::BedrockApiKey), + auth_mode: Some(DomainAuthMode::BedrockApiKey), openai_api_key: None, tokens: None, last_refresh: None, @@ -1436,6 +1430,13 @@ async fn login_account_amazon_bedrock_allows_codex_environment_auth() -> Result< async fn login_account_amazon_bedrock_persists_under_provider_override() -> Result<()> { let codex_home = TempDir::new()?; create_config_toml(codex_home.path(), CreateConfigTomlParams::default())?; + + let mut mcp = TestAppServer::new_with_args( + codex_home.path(), + &["-c", "model_provider=\"mock_provider\""], + ) + .await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; let mut expected_config = read_config_toml(codex_home.path())?; expected_config .as_table_mut() @@ -1444,13 +1445,6 @@ async fn login_account_amazon_bedrock_persists_under_provider_override() -> Resu "model_provider".to_string(), toml::Value::String("amazon-bedrock".to_string()), ); - - let mut mcp = TestAppServer::new_with_args( - codex_home.path(), - &["-c", "model_provider=\"mock_provider\""], - ) - .await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; let request_id = mcp .send_login_account_amazon_bedrock_request("managed-bedrock-api-key", "us-west-2") .await?; @@ -1466,7 +1460,7 @@ async fn login_account_amazon_bedrock_persists_under_provider_override() -> Resu assert_eq!( load_file_auth(codex_home.path())?, Some(AuthDotJson { - auth_mode: Some(AuthMode::BedrockApiKey), + auth_mode: Some(DomainAuthMode::BedrockApiKey), openai_api_key: None, tokens: None, last_refresh: None, @@ -1484,7 +1478,7 @@ async fn login_account_amazon_bedrock_persists_under_provider_override() -> Resu mcp.read_stream_until_notification_message("account/login/completed"), ) .await??; - assert_no_account_updated(&mut mcp).await; + assert_account_updated(&mut mcp, Some(AuthMode::BedrockApiKey)).await?; assert_eq!( read_account(&mut mcp).await?, GetAccountResponse { @@ -1506,11 +1500,11 @@ async fn logout_account_managed_bedrock_preserves_changed_provider() -> Result<( AuthCredentialsStoreMode::File, AuthKeyringBackendKind::default(), )?; - let expected_config = read_config_toml(codex_home.path())?; let mut mcp = TestAppServer::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + let expected_config = read_config_toml(codex_home.path())?; let request_id = mcp.send_logout_account_request().await?; let response: JSONRPCResponse = timeout( @@ -1524,7 +1518,7 @@ async fn logout_account_managed_bedrock_preserves_changed_provider() -> Result<( ); assert_eq!(load_file_auth(codex_home.path())?, None); assert_eq!(read_config_toml(codex_home.path())?, expected_config); - assert_no_account_updated(&mut mcp).await; + assert_account_updated(&mut mcp, None).await?; Ok(()) } diff --git a/codex-rs/login/src/auth/auth_tests.rs b/codex-rs/login/src/auth/auth_tests.rs index 158630f12e..3936a17cda 100644 --- a/codex-rs/login/src/auth/auth_tests.rs +++ b/codex-rs/login/src/auth/auth_tests.rs @@ -1609,9 +1609,9 @@ async fn load_auth_keeps_codex_api_key_env_precedence() { codex_home.path().to_path_buf(), /*enable_codex_api_key_env*/ true, AuthCredentialsStoreMode::File, + /*forced_chatgpt_workspace_id*/ None, /*chatgpt_base_url*/ None, AuthKeyringBackendKind::Direct, - /*agent_identity_authapi_base_url*/ None, /*auth_route_config*/ None, ) .await; diff --git a/codex-rs/login/src/auth/bedrock_api_key.rs b/codex-rs/login/src/auth/bedrock_api_key.rs index 3445878365..066ee2aadc 100644 --- a/codex-rs/login/src/auth/bedrock_api_key.rs +++ b/codex-rs/login/src/auth/bedrock_api_key.rs @@ -4,6 +4,8 @@ use codex_config::types::AuthCredentialsStoreMode; use serde::Deserialize; use serde::Serialize; +use super::manager::AuthManager; +use super::manager::load_auth_dot_json; use super::manager::save_auth; use super::storage::AuthDotJson; use super::storage::AuthKeyringBackendKind; @@ -44,6 +46,67 @@ pub fn login_with_bedrock_api_key( ) } +pub(super) fn load_stored_bedrock_api_key( + codex_home: &Path, + auth_credentials_store_mode: AuthCredentialsStoreMode, + keyring_backend_kind: AuthKeyringBackendKind, +) -> std::io::Result> { + load_stored_bedrock_api_key_auth( + codex_home, + auth_credentials_store_mode, + keyring_backend_kind, + ) + .map(|auth| auth.and_then(|auth| auth.bedrock_api_key)) +} + +fn load_stored_bedrock_api_key_auth( + codex_home: &Path, + auth_credentials_store_mode: AuthCredentialsStoreMode, + keyring_backend_kind: AuthKeyringBackendKind, +) -> std::io::Result> { + load_auth_dot_json( + codex_home, + auth_credentials_store_mode, + keyring_backend_kind, + ) + .map(|auth| auth.filter(AuthDotJson::is_bedrock_api_key)) +} + +impl AuthManager { + /// Current cached account auth mode, including provider-specific managed auth. + pub fn account_auth_mode_cached(&self) -> Option { + self.get_api_auth_mode().or_else(|| { + self.bedrock_api_key_auth_cached() + .map(|_| AuthMode::BedrockApiKey) + }) + } + + pub fn has_stored_bedrock_api_key_auth(&self) -> std::io::Result { + load_stored_bedrock_api_key_auth( + &self.codex_home, + self.auth_credentials_store_mode, + self.keyring_backend_kind, + ) + .map(|auth| auth.is_some()) + } + + pub async fn login_with_bedrock_api_key( + &self, + api_key: &str, + region: &str, + ) -> std::io::Result<()> { + login_with_bedrock_api_key( + &self.codex_home, + api_key, + region, + self.auth_credentials_store_mode, + self.keyring_backend_kind, + )?; + self.reload().await; + Ok(()) + } +} + #[cfg(test)] #[path = "bedrock_api_key_tests.rs"] mod tests; diff --git a/codex-rs/login/src/auth/bedrock_api_key_tests.rs b/codex-rs/login/src/auth/bedrock_api_key_tests.rs index 282957fc3a..0aa25a8866 100644 --- a/codex-rs/login/src/auth/bedrock_api_key_tests.rs +++ b/codex-rs/login/src/auth/bedrock_api_key_tests.rs @@ -52,23 +52,16 @@ fn auth_config(codex_home: &std::path::Path, forced_login_method: ForcedLoginMet forced_login_method: Some(forced_login_method), chatgpt_base_url: None, forced_chatgpt_workspace_id: None, + auth_route_config: None, } } #[tokio::test] #[serial(codex_auth_env)] -async fn login_with_bedrock_api_key_replaces_openai_auth() -> anyhow::Result<()> { +async fn auth_manager_login_with_bedrock_api_key_replaces_openai_auth() -> anyhow::Result<()> { let codex_home = tempdir()?; let storage = FileAuthStorage::new(codex_home.path().to_path_buf()); storage.save(&api_key_auth())?; - login_with_bedrock_api_key( - codex_home.path(), - "bedrock-api-key-test", - "us-east-1", - AuthCredentialsStoreMode::File, - AuthKeyringBackendKind::default(), - )?; - let auth_manager = AuthManager::new( codex_home.path().to_path_buf(), /*enable_codex_api_key_env*/ false, @@ -80,6 +73,10 @@ async fn login_with_bedrock_api_key_replaces_openai_auth() -> anyhow::Result<()> ) .await; + auth_manager + .login_with_bedrock_api_key("bedrock-api-key-test", "us-east-1") + .await?; + let loaded = storage.load()?.expect("auth should be stored"); let expected = AuthDotJson { auth_mode: Some(AuthMode::BedrockApiKey), @@ -92,6 +89,10 @@ async fn login_with_bedrock_api_key_replaces_openai_auth() -> anyhow::Result<()> }; assert_eq!(loaded, expected); assert_eq!(auth_manager.auth_mode(), None); + assert_eq!( + auth_manager.account_auth_mode_cached(), + Some(AuthMode::BedrockApiKey) + ); assert_eq!( auth_manager.bedrock_api_key_auth_cached(), Some(bedrock_auth()) @@ -102,7 +103,7 @@ async fn login_with_bedrock_api_key_replaces_openai_auth() -> anyhow::Result<()> #[tokio::test] #[serial(codex_auth_env)] -async fn logout_removes_bedrock_auth() -> anyhow::Result<()> { +async fn auth_manager_logout_removes_bedrock_api_key_auth() -> anyhow::Result<()> { let codex_home = tempdir()?; let storage = FileAuthStorage::new(codex_home.path().to_path_buf()); login_with_bedrock_api_key( @@ -128,6 +129,7 @@ async fn logout_removes_bedrock_auth() -> anyhow::Result<()> { assert_eq!(storage.load()?, None); assert_eq!(auth_manager.auth_cached(), None); assert_eq!(auth_manager.bedrock_api_key_auth_cached(), None); + assert_eq!(auth_manager.account_auth_mode_cached(), None); Ok(()) } @@ -150,6 +152,10 @@ async fn bedrock_only_auth_storage_does_not_create_codex_auth() -> anyhow::Resul .await; assert_eq!(auth_manager.auth_mode(), None); + assert_eq!( + auth_manager.account_auth_mode_cached(), + Some(AuthMode::BedrockApiKey) + ); assert_eq!( auth_manager.bedrock_api_key_auth_cached(), Some(bedrock_auth()) diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 80f5d3d499..4fddb00442 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -36,6 +36,7 @@ use super::agent_identity::record_needs_task_registration; use super::agent_identity::register_managed_chatgpt_agent_identity; use super::agent_identity::require_agent_identity_authapi_base_url; use super::agent_identity::verified_record_from_jwt; +use super::bedrock_api_key::load_stored_bedrock_api_key; use super::external_bearer::BearerTokenRefresher; use super::revoke::revoke_auth_tokens; pub use crate::auth::agent_identity::AgentIdentityAuth; @@ -644,10 +645,7 @@ impl CodexAuth { ) -> std::io::Result> { match self { Self::AgentIdentity(auth) => Ok(Some(auth.clone())), - Self::ApiKey(_) - | Self::ChatgptAuthTokens(_) - | Self::PersonalAccessToken(_) - | Self::BedrockApiKey(_) => Ok(None), + Self::ApiKey(_) | Self::ChatgptAuthTokens(_) | Self::PersonalAccessToken(_) => Ok(None), Self::Chatgpt(_) => { if policy == AgentIdentityAuthPolicy::JwtOnly { return Ok(None); @@ -1027,19 +1025,6 @@ pub fn load_auth_dot_json( storage.load() } -fn load_stored_bedrock_api_key( - codex_home: &Path, - auth_credentials_store_mode: AuthCredentialsStoreMode, - keyring_backend_kind: AuthKeyringBackendKind, -) -> std::io::Result> { - load_auth_dot_json( - codex_home, - auth_credentials_store_mode, - keyring_backend_kind, - ) - .map(|auth| auth.and_then(|auth| auth.bedrock_api_key)) -} - #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuthConfig { pub codex_home: PathBuf, @@ -1476,7 +1461,7 @@ fn refresh_token_endpoint() -> String { impl AuthDotJson { /// Returns whether this stored payload resolves to managed Amazon Bedrock API key auth. pub fn is_bedrock_api_key(&self) -> bool { - self.resolved_mode() == ApiAuthMode::BedrockApiKey + self.resolved_mode() == AuthMode::BedrockApiKey } fn from_external_tokens(external: &ExternalAuthTokens) -> std::io::Result { @@ -1815,12 +1800,12 @@ impl UnauthorizedRecovery { /// `reload()` is called explicitly. This matches the design goal of avoiding /// different parts of the program seeing inconsistent auth data mid‑run. pub struct AuthManager { - codex_home: PathBuf, + pub(super) codex_home: PathBuf, inner: RwLock, auth_change_tx: watch::Sender, enable_codex_api_key_env: bool, - auth_credentials_store_mode: AuthCredentialsStoreMode, - keyring_backend_kind: AuthKeyringBackendKind, + pub(super) auth_credentials_store_mode: AuthCredentialsStoreMode, + pub(super) keyring_backend_kind: AuthKeyringBackendKind, forced_chatgpt_workspace_id: RwLock>>, chatgpt_base_url: Option, agent_identity_authapi_base_url: Option, @@ -2003,6 +1988,7 @@ impl AuthManager { ) -> Arc { let cached = CachedAuth { auth: Some(auth), + bedrock_api_key: None, permanent_refresh_failure: None, }; let (auth_change_tx, _auth_change_rx) = watch::channel(0); diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index 54c6da3f77..ad0b08fcd7 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -24,7 +24,6 @@ pub use auth::AuthDotJson; pub use auth::AuthKeyringBackendKind; pub use auth::AuthManager; pub use auth::AuthManagerConfig; -pub use auth::AuthMode; pub use auth::CLIENT_ID; pub use auth::CLIENT_ID_OVERRIDE_ENV_VAR; pub use auth::CODEX_ACCESS_TOKEN_ENV_VAR; @@ -55,5 +54,6 @@ pub use auth::read_openai_api_key_from_env; pub use auth::save_auth; pub use auth_env_telemetry::AuthEnvTelemetry; pub use auth_env_telemetry::collect_auth_env_telemetry; +pub use codex_protocol::auth::AuthMode; pub use outbound_proxy::AuthRouteConfig; pub use token_data::TokenData; diff --git a/codex-rs/model-provider/src/lib.rs b/codex-rs/model-provider/src/lib.rs index f8d1dd4047..2a23343dfc 100644 --- a/codex-rs/model-provider/src/lib.rs +++ b/codex-rs/model-provider/src/lib.rs @@ -4,16 +4,16 @@ mod bearer_auth_provider; mod models_endpoint; mod provider; +pub use amazon_bedrock::is_supported_amazon_bedrock_region; pub use auth::AgentIdentitySessionFallback; pub use auth::ProviderAuthScope; pub use auth::ResolvedProviderAuth; -pub use amazon_bedrock::is_supported_amazon_bedrock_region; pub use auth::auth_provider_from_auth; pub use auth::unauthenticated_auth_provider; pub use bearer_auth_provider::BearerAuthProvider; pub use bearer_auth_provider::BearerAuthProvider as CoreAuthProvider; -pub use codex_model_provider_info::CHATGPT_CODEX_BASE_URL; pub use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID; +pub use codex_model_provider_info::CHATGPT_CODEX_BASE_URL; pub use codex_protocol::account::ProviderAccount; pub use provider::ModelProvider; pub use provider::ModelProviderFuture;