diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 2f39f821b6..dc4ad86b7c 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -1529,6 +1529,31 @@ ], "title": "ChatgptAuthTokensLoginAccountParams", "type": "object" + }, + { + "description": "[UNSTABLE] Managed Amazon Bedrock login is experimental.", + "properties": { + "apiKey": { + "type": "string" + }, + "region": { + "type": "string" + }, + "type": { + "enum": [ + "amazonBedrock" + ], + "title": "AmazonBedrockLoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "apiKey", + "region", + "type" + ], + "title": "AmazonBedrockLoginAccountParams", + "type": "object" } ] }, diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 0eedef903a..75b5c15a64 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -11569,6 +11569,31 @@ ], "title": "ChatgptAuthTokensv2::LoginAccountParams", "type": "object" + }, + { + "description": "[UNSTABLE] Managed Amazon Bedrock login is experimental.", + "properties": { + "apiKey": { + "type": "string" + }, + "region": { + "type": "string" + }, + "type": { + "enum": [ + "amazonBedrock" + ], + "title": "AmazonBedrockv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "apiKey", + "region", + "type" + ], + "title": "AmazonBedrockv2::LoginAccountParams", + "type": "object" } ], "title": "LoginAccountParams" @@ -11662,6 +11687,22 @@ ], "title": "ChatgptAuthTokensv2::LoginAccountResponse", "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "amazonBedrock" + ], + "title": "AmazonBedrockv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AmazonBedrockv2::LoginAccountResponse", + "type": "object" } ], "title": "LoginAccountResponse" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index b428f25258..7fa21d15c1 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -7973,6 +7973,31 @@ ], "title": "ChatgptAuthTokensv2::LoginAccountParams", "type": "object" + }, + { + "description": "[UNSTABLE] Managed Amazon Bedrock login is experimental.", + "properties": { + "apiKey": { + "type": "string" + }, + "region": { + "type": "string" + }, + "type": { + "enum": [ + "amazonBedrock" + ], + "title": "AmazonBedrockv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "apiKey", + "region", + "type" + ], + "title": "AmazonBedrockv2::LoginAccountParams", + "type": "object" } ], "title": "LoginAccountParams" @@ -8066,6 +8091,22 @@ ], "title": "ChatgptAuthTokensv2::LoginAccountResponse", "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "amazonBedrock" + ], + "title": "AmazonBedrockv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AmazonBedrockv2::LoginAccountResponse", + "type": "object" } ], "title": "LoginAccountResponse" diff --git a/codex-rs/app-server-protocol/schema/json/v2/LoginAccountParams.json b/codex-rs/app-server-protocol/schema/json/v2/LoginAccountParams.json index ab7b852c91..474b7666cf 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/LoginAccountParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/LoginAccountParams.json @@ -89,6 +89,31 @@ ], "title": "ChatgptAuthTokensv2::LoginAccountParams", "type": "object" + }, + { + "description": "[UNSTABLE] Managed Amazon Bedrock login is experimental.", + "properties": { + "apiKey": { + "type": "string" + }, + "region": { + "type": "string" + }, + "type": { + "enum": [ + "amazonBedrock" + ], + "title": "AmazonBedrockv2::LoginAccountParamsType", + "type": "string" + } + }, + "required": [ + "apiKey", + "region", + "type" + ], + "title": "AmazonBedrockv2::LoginAccountParams", + "type": "object" } ], "title": "LoginAccountParams" diff --git a/codex-rs/app-server-protocol/schema/json/v2/LoginAccountResponse.json b/codex-rs/app-server-protocol/schema/json/v2/LoginAccountResponse.json index a800bffccd..802440d637 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/LoginAccountResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/LoginAccountResponse.json @@ -87,6 +87,22 @@ ], "title": "ChatgptAuthTokensv2::LoginAccountResponse", "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "amazonBedrock" + ], + "title": "AmazonBedrockv2::LoginAccountResponseType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "AmazonBedrockv2::LoginAccountResponse", + "type": "object" } ], "title": "LoginAccountResponse" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountParams.ts index e6f1e2ed43..88ee4434cf 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountParams.ts @@ -18,4 +18,4 @@ chatgptAccountId: string, * When `null`, Codex attempts to derive the plan type from access-token * claims. If unavailable, the plan defaults to `unknown`. */ -chatgptPlanType?: string | null, }; +chatgptPlanType?: string | null, } | { "type": "amazonBedrock", apiKey: string, region: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountResponse.ts index 34bccd6578..5a9f34ead3 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountResponse.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/LoginAccountResponse.ts @@ -14,4 +14,4 @@ verificationUrl: string, /** * One-time code the user must enter after signing in. */ -userCode: string, } | { "type": "chatgptAuthTokens", }; +userCode: string, } | { "type": "chatgptAuthTokens", } | { "type": "amazonBedrock", }; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index d8db99d4ff..a78be7ef41 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -2716,6 +2716,34 @@ mod tests { Ok(()) } + #[test] + fn serialize_account_login_amazon_bedrock() -> Result<()> { + let request = ClientRequest::LoginAccount { + request_id: RequestId::Integer(2), + params: v2::LoginAccountParams::AmazonBedrock { + api_key: "secret".to_string(), + region: "us-west-2".to_string(), + }, + }; + assert_eq!( + json!({ + "method": "account/login/start", + "id": 2, + "params": { + "type": "amazonBedrock", + "apiKey": "secret", + "region": "us-west-2" + } + }), + serde_json::to_value(&request)?, + ); + assert_eq!( + json!({"type": "amazonBedrock"}), + serde_json::to_value(v2::LoginAccountResponse::AmazonBedrock {})?, + ); + Ok(()) + } + #[test] fn serialize_account_login_chatgpt() -> Result<()> { let request = ClientRequest::LoginAccount { diff --git a/codex-rs/app-server-protocol/src/protocol/v2/account.rs b/codex-rs/app-server-protocol/src/protocol/v2/account.rs index 788c8f7aaf..5268c318a6 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/account.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/account.rs @@ -100,6 +100,11 @@ pub enum LoginAccountParams { #[ts(optional = nullable)] chatgpt_plan_type: Option, }, + /// [UNSTABLE] Managed Amazon Bedrock login is experimental. + #[experimental("account/login/start.amazonBedrock")] + #[serde(rename = "amazonBedrock", rename_all = "camelCase")] + #[ts(rename = "amazonBedrock", rename_all = "camelCase")] + AmazonBedrock { api_key: String, region: String }, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -133,6 +138,9 @@ pub enum LoginAccountResponse { #[serde(rename = "chatgptAuthTokens", rename_all = "camelCase")] #[ts(rename = "chatgptAuthTokens", rename_all = "camelCase")] ChatgptAuthTokens {}, + #[serde(rename = "amazonBedrock", rename_all = "camelCase")] + #[ts(rename = "amazonBedrock", rename_all = "camelCase")] + AmazonBedrock {}, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index a7986753ee..e267167eee 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1919,16 +1919,17 @@ Codex supports these authentication modes. The current mode is surfaced in `acco - **API key (`apiKey`)**: Caller supplies an OpenAI API key via `account/login/start` with `type: "apiKey"`. The API key is saved and used for API requests. - **ChatGPT managed (`chatgpt`)** (recommended): Codex owns the ChatGPT OAuth flow and refresh tokens. Start via `account/login/start` with `type: "chatgpt"` for the browser flow or `type: "chatgptDeviceCode"` for device code; Codex persists tokens to disk and refreshes them automatically. +- **Codex managed Amazon Bedrock auth (`amazonBedrock`, experimental)**: Caller supplies an Amazon Bedrock API key and region via `account/login/start` with `type: "amazonBedrock"`. The client must enable the `experimentalApi` initialization capability for Codex-managed Amazon Bedrock login. Codex saves the credential and writes `model_provider = "amazon-bedrock"` to the user config. The parameterless `account/logout` method clears managed Bedrock credentials on a best-effort basis. - **Personal access token (`personalAccessToken`)**: Codex uses a ChatGPT-backed personal access token loaded outside the app-server login RPCs, such as with `codex login --with-access-token` or `CODEX_ACCESS_TOKEN`. ### API Overview - `account/read` — fetch current account info; optionally refresh tokens. -- `account/login/start` — begin login (`apiKey`, `chatgpt`, `chatgptDeviceCode`). +- `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; triggers `account/updated`. -- `account/updated` (notify) — emitted whenever auth mode changes (`authMode`: `apikey`, `chatgpt`, `personalAccessToken`, or `null`) and includes the current ChatGPT `planType` when available. +- `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/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`. - `account/usage/read` — fetch ChatGPT account token-activity summary and daily buckets. @@ -1999,6 +2000,29 @@ Field notes: { "method": "account/updated", "params": { "authMode": "chatgpt", "planType": "plus" } } ``` +### 3) Log in with an Amazon Bedrock API key + +This experimental flow requires the client to initialize with `experimentalApi: true`. + +1. Send: + ```json + { + "method": "account/login/start", + "id": 3, + "params": { "type": "amazonBedrock", "apiKey": "…", "region": "us-west-2" } + } + ``` +2. Expect: + ```json + { "id": 3, "result": { "type": "amazonBedrock" } } + ``` +3. Notifications: + ```json + { "method": "account/login/completed", "params": { "loginId": null, "success": true, "error": null } } + ``` + +Codex stores the key and region in its configured auth store and writes `model_provider = "amazon-bedrock"` to the active user config. + ### 4) Log in with ChatGPT (device code flow) 1. Start: diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index f03351468f..119ea61790 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -495,6 +495,7 @@ use codex_app_server_protocol::ServerRequest; mod account_processor; mod apps_processor; +mod bedrock_auth; mod catalog_processor; mod command_exec_processor; mod config_processor; 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 9592563bec..f317cc45a0 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,12 @@ +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::*; use crate::auth_mode::auth_mode_to_api; use chrono::DateTime; +use codex_login::auth::read_codex_api_key_from_env; +use codex_login::read_codex_access_token_from_env; +use codex_model_provider::is_supported_amazon_bedrock_region; mod rate_limit_resets; @@ -274,6 +280,10 @@ impl AccountRequestProcessor { ) .await; } + LoginAccountParams::AmazonBedrock { api_key, region } => { + self.login_amazon_bedrock_v2(request_id, api_key, region) + .await; + } } Ok(()) } @@ -337,6 +347,64 @@ impl AccountRequestProcessor { } } + async fn login_amazon_bedrock_v2( + &self, + request_id: ConnectionRequestId, + api_key: String, + region: String, + ) { + let result = async { + if self.auth_manager.is_external_chatgpt_auth_active() { + return Err(self.external_auth_active_error()); + } + if read_codex_access_token_from_env().is_some() + || (self.auth_manager.codex_api_key_env_enabled() + && read_codex_api_key_from_env().is_some()) + { + return Err(invalid_request( + "Amazon Bedrock login is unavailable while Codex auth is supplied through the environment.", + )); + } + if matches!( + self.config.forced_login_method, + Some(ForcedLoginMethod::Chatgpt) + ) { + return Err(invalid_request( + "Amazon Bedrock login is disabled. Use ChatGPT login instead.", + )); + } + + let api_key = api_key.trim(); + if api_key.is_empty() { + return Err(invalid_request("Amazon Bedrock API key must not be empty.")); + } + let region = region.trim(); + if !is_supported_amazon_bedrock_region(region) { + return Err(invalid_request(format!( + "Amazon Bedrock Mantle does not support region `{region}`" + ))); + } + + { + let mut guard = self.active_login.lock().await; + if let Some(active) = guard.take() { + drop(active); + } + } + + login_managed_bedrock(&self.config, &self.config_manager, api_key, region).await?; + Ok(LoginAccountResponse::AmazonBedrock {}) + } + .await; + let logged_in = result.is_ok(); + self.outgoing.send_result(request_id, result).await; + + if logged_in { + self.emit_login_completed_notification(/*login_id*/ None) + .await; + } + } + // Build options for a ChatGPT login attempt; performs validation. async fn login_chatgpt_common( &self, @@ -644,6 +712,20 @@ impl AccountRequestProcessor { ) .await; + self.emit_login_success_notifications(login_id).await; + } + + async fn emit_login_success_notifications(&self, login_id: Option) { + self.emit_login_completed_notification(login_id).await; + + self.outgoing + .send_server_notification(ServerNotification::AccountUpdated( + self.current_account_updated_notification(), + )) + .await; + } + + async fn emit_login_completed_notification(&self, login_id: Option) { let payload_login_completed = AccountLoginCompletedNotification { login_id: login_id.map(|id| id.to_string()), success: true, @@ -654,12 +736,6 @@ impl AccountRequestProcessor { payload_login_completed, )) .await; - - self.outgoing - .send_server_notification(ServerNotification::AccountUpdated( - self.current_account_updated_notification(), - )) - .await; } async fn send_chatgpt_login_completion_notifications( @@ -709,7 +785,7 @@ impl AccountRequestProcessor { } } - async fn logout_common(&self) -> std::result::Result, JSONRPCErrorError> { + async fn logout_common(&self) -> Result, JSONRPCErrorError> { // Cancel any active login attempt. { let mut guard = self.active_login.lock().await; @@ -718,6 +794,14 @@ impl AccountRequestProcessor { } } + if has_managed_bedrock_login(&self.config)? { + logout_managed_bedrock(&self.config, &self.config_manager).await?; + return Ok(None); + } + if self.config.model_provider.is_amazon_bedrock() { + return Ok(None); + } + match self.auth_manager.logout_with_revoke().await { Ok(_) => {} Err(err) => { @@ -733,25 +817,20 @@ impl AccountRequestProcessor { .await; // Reflect the current auth method after logout (likely None). - Ok(self - .auth_manager - .auth_cached() - .as_ref() - .map(CodexAuth::api_auth_mode) - .map(auth_mode_to_api)) + Ok(Some(AccountUpdatedNotification { + auth_mode: self + .auth_manager + .auth_cached() + .as_ref() + .map(CodexAuth::api_auth_mode) + .map(auth_mode_to_api), + plan_type: None, + })) } async fn logout_v2(&self, request_id: ConnectionRequestId) -> Result<(), JSONRPCErrorError> { let result = self.logout_common().await; - let account_updated = - result - .as_ref() - .ok() - .cloned() - .map(|auth_mode| AccountUpdatedNotification { - auth_mode, - plan_type: None, - }); + let account_updated = result.as_ref().ok().cloned().flatten(); 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 new file mode 100644 index 0000000000..72e1866c2d --- /dev/null +++ b/codex-rs/app-server/src/request_processors/bedrock_auth.rs @@ -0,0 +1,129 @@ +use super::config_processor::map_error as map_config_error; +use crate::config_manager::ConfigManager; +use crate::error_code::internal_error; +use codex_app_server_protocol::ConfigLayerSource; +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 { + 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, + 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, + ) + .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), + /*expected_version*/ None, + ) + .await +} + +pub(super) async fn logout( + config: &Config, + config_manager: &ConfigManager, +) -> 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) + .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, + serde_json::Value::Null, + user_model_provider.version, + ) + .await?; + } + + Ok(()) +} + +fn load_stored_auth(config: &Config) -> Result, JSONRPCErrorError> { + load_auth_dot_json(&config.codex_home, config.cli_auth_credentials_store_mode) + .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( + config_manager: &ConfigManager, +) -> Result { + let user_config_path = config_manager + .user_config_path() + .map_err(|err| internal_error(format!("failed to resolve user config path: {err}")))?; + let response = config_manager + .read(ConfigReadParams { + include_layers: true, + cwd: None, + }) + .await + .map_err(|err| internal_error(format!("failed to read user config: {err}")))?; + let layer = response + .layers + .unwrap_or_default() + .into_iter() + .find(|layer| { + matches!( + &layer.name, + ConfigLayerSource::User { file, .. } if file == &user_config_path + ) + }); + let Some(layer) = layer else { + return Ok(UserModelProviderState { + model_provider: None, + version: None, + }); + }; + let model_provider = layer + .config + .get("model_provider") + .and_then(serde_json::Value::as_str) + .map(str::to_string); + Ok(UserModelProviderState { + model_provider, + version: Some(layer.version), + }) +} + +async fn write_user_model_provider( + config_manager: &ConfigManager, + value: serde_json::Value, + expected_version: Option, +) -> Result<(), JSONRPCErrorError> { + config_manager + .write_value(ConfigValueWriteParams { + key_path: "model_provider".to_string(), + value, + merge_strategy: MergeStrategy::Replace, + file_path: None, + expected_version, + }) + .await + .map(|_| ()) + .map_err(map_config_error) +} diff --git a/codex-rs/app-server/src/request_processors/config_processor.rs b/codex-rs/app-server/src/request_processors/config_processor.rs index b6dbb30b08..0eeb1aaca9 100644 --- a/codex-rs/app-server/src/request_processors/config_processor.rs +++ b/codex-rs/app-server/src/request_processors/config_processor.rs @@ -555,7 +555,7 @@ fn map_network_unix_socket_permission_to_api( } } -fn map_error(err: ConfigManagerError) -> JSONRPCErrorError { +pub(super) fn map_error(err: ConfigManagerError) -> JSONRPCErrorError { if let Some(code) = err.write_error_code() { return config_write_error(code, err.to_string()); } diff --git a/codex-rs/app-server/tests/common/test_app_server.rs b/codex-rs/app-server/tests/common/test_app_server.rs index cbb8ff161e..3cedbee2b1 100644 --- a/codex-rs/app-server/tests/common/test_app_server.rs +++ b/codex-rs/app-server/tests/common/test_app_server.rs @@ -1392,6 +1392,20 @@ impl TestAppServer { self.send_request("account/login/start", Some(params)).await } + /// Send an `account/login/start` JSON-RPC request for managed Amazon Bedrock login. + pub async fn send_login_account_amazon_bedrock_request( + &mut self, + api_key: &str, + region: &str, + ) -> anyhow::Result { + let params = serde_json::json!({ + "type": "amazonBedrock", + "apiKey": api_key, + "region": region, + }); + self.send_request("account/login/start", Some(params)).await + } + /// Send an `account/login/start` JSON-RPC request for ChatGPT login. pub async fn send_login_account_chatgpt_request(&mut self) -> anyhow::Result { let params = serde_json::json!({ diff --git a/codex-rs/app-server/tests/suite/v2/account.rs b/codex-rs/app-server/tests/suite/v2/account.rs index 3cd98e2e52..a11bcf2345 100644 --- a/codex-rs/app-server/tests/suite/v2/account.rs +++ b/codex-rs/app-server/tests/suite/v2/account.rs @@ -5,24 +5,29 @@ use app_test_support::to_response; use app_test_support::ChatGptAuthFixture; use app_test_support::ChatGptIdTokenClaims; +use app_test_support::DEFAULT_CLIENT_NAME; use app_test_support::encode_id_token; use app_test_support::write_chatgpt_auth; use app_test_support::write_models_cache; use chrono::Duration as ChronoDuration; use chrono::Utc; use codex_app_server_protocol::Account; +use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::CancelLoginAccountParams; use codex_app_server_protocol::CancelLoginAccountResponse; use codex_app_server_protocol::CancelLoginAccountStatus; use codex_app_server_protocol::ChatgptAuthTokensRefreshReason; use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse; +use codex_app_server_protocol::ClientInfo; use codex_app_server_protocol::GetAccountParams; use codex_app_server_protocol::GetAccountResponse; use codex_app_server_protocol::GetAuthStatusParams; use codex_app_server_protocol::GetAuthStatusResponse; +use codex_app_server_protocol::InitializeCapabilities; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCErrorError; +use codex_app_server_protocol::JSONRPCMessage; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::LoginAccountResponse; @@ -33,9 +38,12 @@ use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::TurnCompletedNotification; use codex_app_server_protocol::TurnStatus; use codex_config::types::AuthCredentialsStoreMode; +use codex_login::AuthDotJson; use codex_login::AuthKeyringBackendKind; use codex_login::CLIENT_ID_OVERRIDE_ENV_VAR; use codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; +use codex_login::auth::BedrockApiKeyAuth; +use codex_login::load_auth_dot_json; use codex_login::login_with_api_key; use codex_login::login_with_bedrock_api_key; use codex_protocol::account::AmazonBedrockCredentialSource; @@ -141,6 +149,51 @@ shell_snapshot = false std::fs::write(config_toml, contents) } +fn read_config_toml(codex_home: &Path) -> Result { + Ok(toml::from_str(&std::fs::read_to_string( + codex_home.join("config.toml"), + )?)?) +} + +fn aws_managed_bedrock_config() -> CreateConfigTomlParams { + CreateConfigTomlParams { + model_provider_id: Some("amazon-bedrock".to_string()), + extra_provider_config: Some( + r#"[model_providers.amazon-bedrock.aws] +profile = "codex-bedrock" +region = "us-west-2" +"# + .to_string(), + ), + ..Default::default() + } +} + +async fn read_account(mcp: &mut TestAppServer) -> Result { + let request_id = mcp + .send_get_account_request(GetAccountParams { + refresh_token: false, + }) + .await?; + let response = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + 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 mock_device_code_usercode(server: &MockServer, interval_seconds: u64) { Mock::given(method("POST")) .and(path("/api/accounts/deviceauth/usercode")) @@ -961,6 +1014,459 @@ async fn login_account_api_key_succeeds_and_notifies() -> Result<()> { Ok(()) } +#[tokio::test] +async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml( + codex_home.path(), + CreateConfigTomlParams { + requires_openai_auth: Some(true), + ..Default::default() + }, + )?; + login_with_api_key( + codex_home.path(), + "sk-test-key", + AuthCredentialsStoreMode::File, + )?; + let mut expected_config = read_config_toml(codex_home.path())?; + expected_config + .as_table_mut() + .expect("config should be a table") + .insert( + "model_provider".to_string(), + toml::Value::String("amazon-bedrock".to_string()), + ); + let mut expected_config_after_logout = expected_config.clone(); + expected_config_after_logout + .as_table_mut() + .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?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LoginAccountResponse::AmazonBedrock {} + ); + + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + Some(AuthDotJson { + auth_mode: Some(AuthMode::BedrockApiKey), + openai_api_key: None, + tokens: None, + last_refresh: None, + agent_identity: None, + personal_access_token: None, + bedrock_api_key: Some(BedrockApiKeyAuth { + api_key: "managed-bedrock-api-key".to_string(), + region: "us-west-2".to_string(), + }), + }) + ); + assert_eq!(read_config_toml(codex_home.path())?, expected_config); + + let notification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/login/completed"), + ) + .await??; + let ServerNotification::AccountLoginCompleted(payload) = notification.try_into()? else { + bail!("unexpected notification") + }; + assert_eq!( + payload, + AccountLoginCompletedNotification { + login_id: None, + success: true, + error: None, + } + ); + assert_no_account_updated(&mut mcp).await; + assert_eq!( + read_account(&mut mcp).await?, + GetAccountResponse { + account: Some(Account::ApiKey {}), + requires_openai_auth: true, + } + ); + + let request_id = mcp.send_logout_account_request().await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LogoutAccountResponse {} + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + None + ); + assert_eq!( + read_config_toml(codex_home.path())?, + expected_config_after_logout + ); + assert_no_account_updated(&mut mcp).await; + assert_eq!( + read_account(&mut mcp).await?, + GetAccountResponse { + account: Some(Account::ApiKey {}), + requires_openai_auth: true, + } + ); + Ok(()) +} + +#[tokio::test] +async fn managed_bedrock_login_requires_experimental_api_but_logout_is_best_effort() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), CreateConfigTomlParams::default())?; + let mut mcp = TestAppServer::new(codex_home.path()).await?; + let initialized = mcp + .initialize_with_capabilities( + ClientInfo { + name: DEFAULT_CLIENT_NAME.to_string(), + title: None, + version: "0.1.0".to_string(), + }, + Some(InitializeCapabilities { + experimental_api: false, + ..Default::default() + }), + ) + .await?; + assert!(matches!(initialized, JSONRPCMessage::Response(_))); + + let request_id = mcp + .send_login_account_amazon_bedrock_request("managed-bedrock-api-key", "us-west-2") + .await?; + let error = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + error.error.message, + "account/login/start.amazonBedrock requires experimentalApi capability" + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + None + ); + login_with_bedrock_api_key( + codex_home.path(), + "managed-bedrock-api-key", + "us-west-2", + AuthCredentialsStoreMode::File, + )?; + let request_id = mcp.send_logout_account_request().await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LogoutAccountResponse {} + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + None + ); + Ok(()) +} + +#[tokio::test] +async fn login_and_logout_managed_bedrock_require_restart_when_provider_is_active() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), aws_managed_bedrock_config())?; + let mut expected_config = read_config_toml(codex_home.path())?; + expected_config + .as_table_mut() + .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?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LoginAccountResponse::AmazonBedrock {} + ); + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/login/completed"), + ) + .await??; + assert_no_account_updated(&mut mcp).await; + assert_eq!( + read_account(&mut mcp).await?, + GetAccountResponse { + account: Some(Account::AmazonBedrock { + credential_source: AmazonBedrockCredentialSource::AwsManaged, + }), + requires_openai_auth: false, + } + ); + + assert!(codex_home.path().join("auth.json").exists()); + let request_id = mcp.send_logout_account_request().await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LogoutAccountResponse {} + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + None + ); + assert_eq!(read_config_toml(codex_home.path())?, expected_config); + + assert_no_account_updated(&mut mcp).await; + assert_eq!( + read_account(&mut mcp).await?, + GetAccountResponse { + account: Some(Account::AmazonBedrock { + credential_source: AmazonBedrockCredentialSource::AwsManaged, + }), + requires_openai_auth: false, + } + ); + Ok(()) +} + +#[tokio::test] +async fn logout_account_aws_managed_bedrock_preserves_openai_auth_and_config() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), aws_managed_bedrock_config())?; + login_with_api_key( + codex_home.path(), + "sk-test-key", + AuthCredentialsStoreMode::File, + )?; + let expected_auth = load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?; + 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 request_id = mcp.send_logout_account_request().await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LogoutAccountResponse {} + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + expected_auth + ); + assert_eq!(read_config_toml(codex_home.path())?, expected_config); + assert_no_account_updated(&mut mcp).await; + Ok(()) +} + +#[tokio::test] +async fn login_account_amazon_bedrock_rejects_invalid_credentials_without_changes() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), CreateConfigTomlParams::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 request_id = mcp + .send_login_account_amazon_bedrock_request(" ", "us-west-2") + .await?; + let error = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + error.error.message, + "Amazon Bedrock API key must not be empty." + ); + + let request_id = mcp + .send_login_account_amazon_bedrock_request("managed-bedrock-api-key", "us-west-1") + .await?; + let error = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + error.error.message, + "Amazon Bedrock Mantle does not support region `us-west-1`" + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + None + ); + assert_eq!(read_config_toml(codex_home.path())?, expected_config); + + drop(mcp); + let mut mcp = TestAppServer::new_with_env( + codex_home.path(), + &[ + ("OPENAI_API_KEY", None), + ("CODEX_ACCESS_TOKEN", Some("env-access-token")), + ], + ) + .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?; + let error = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_error_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + error.error.message, + "Amazon Bedrock login is unavailable while Codex auth is supplied through the environment." + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + None + ); + assert_eq!(read_config_toml(codex_home.path())?, expected_config); + + Ok(()) +} + +#[tokio::test] +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 expected_config = read_config_toml(codex_home.path())?; + expected_config + .as_table_mut() + .expect("config should be a table") + .insert( + "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?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LoginAccountResponse::AmazonBedrock {} + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + Some(AuthDotJson { + auth_mode: Some(AuthMode::BedrockApiKey), + openai_api_key: None, + tokens: None, + last_refresh: None, + agent_identity: None, + personal_access_token: None, + bedrock_api_key: Some(BedrockApiKeyAuth { + api_key: "managed-bedrock-api-key".to_string(), + region: "us-west-2".to_string(), + }), + }) + ); + assert_eq!(read_config_toml(codex_home.path())?, expected_config); + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/login/completed"), + ) + .await??; + assert_no_account_updated(&mut mcp).await; + assert_eq!( + read_account(&mut mcp).await?, + GetAccountResponse { + account: None, + requires_openai_auth: false, + } + ); + Ok(()) +} + +#[tokio::test] +async fn logout_account_managed_bedrock_preserves_changed_provider() -> Result<()> { + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), CreateConfigTomlParams::default())?; + login_with_bedrock_api_key( + codex_home.path(), + "managed-bedrock-api-key", + "us-west-2", + AuthCredentialsStoreMode::File, + )?; + 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 request_id = mcp.send_logout_account_request().await?; + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + assert_eq!( + to_response::(response)?, + LogoutAccountResponse {} + ); + assert_eq!( + load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?, + None + ); + assert_eq!(read_config_toml(codex_home.path())?, expected_config); + assert_no_account_updated(&mut mcp).await; + Ok(()) +} + #[tokio::test] async fn login_account_api_key_rejected_when_forced_chatgpt() -> Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 844410874d..f8a5fee38b 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -1456,6 +1456,11 @@ 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 + } + fn from_external_tokens(external: &ExternalAuthTokens) -> std::io::Result { let Some(chatgpt_metadata) = external.chatgpt_metadata() else { return Err(std::io::Error::other( diff --git a/codex-rs/model-provider/src/amazon_bedrock/mantle.rs b/codex-rs/model-provider/src/amazon_bedrock/mantle.rs index 9727802d11..e31ce96edc 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/mantle.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/mantle.rs @@ -39,8 +39,13 @@ pub(super) fn region_from_config(aws: &ModelProviderAwsAuthInfo) -> Option bool { + BEDROCK_MANTLE_SUPPORTED_REGIONS.contains(®ion) +} + pub(super) fn base_url(region: &str) -> Result { - if BEDROCK_MANTLE_SUPPORTED_REGIONS.contains(®ion) { + if is_supported_amazon_bedrock_region(region) { Ok(format!("https://bedrock-mantle.{region}.api.aws/openai/v1")) } else { Err(CodexErr::Fatal(format!( diff --git a/codex-rs/model-provider/src/amazon_bedrock/mod.rs b/codex-rs/model-provider/src/amazon_bedrock/mod.rs index 108308c1bf..914ddd4ca7 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/mod.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/mod.rs @@ -31,6 +31,7 @@ use crate::provider::ProviderCapabilities; use auth::resolve_provider_auth; pub(crate) use catalog::static_model_catalog; use catalog::with_default_only_service_tier; +pub use mantle::is_supported_amazon_bedrock_region; use mantle::runtime_base_url; /// Runtime provider for Amazon Bedrock's OpenAI-compatible Mantle endpoint. diff --git a/codex-rs/model-provider/src/lib.rs b/codex-rs/model-provider/src/lib.rs index 15967c4fe0..f8d1dd4047 100644 --- a/codex-rs/model-provider/src/lib.rs +++ b/codex-rs/model-provider/src/lib.rs @@ -7,11 +7,13 @@ mod provider; 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_protocol::account::ProviderAccount; pub use provider::ModelProvider; pub use provider::ModelProviderFuture;