This commit is contained in:
celia-oai
2026-07-06 13:39:14 -07:00
parent 8414dc291e
commit bcd4adfb90
16 changed files with 431 additions and 288 deletions
@@ -36,7 +36,6 @@ 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;
@@ -4,8 +4,6 @@ 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;
@@ -357,14 +355,6 @@ impl AccountRequestProcessor {
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)
@@ -393,6 +383,7 @@ impl AccountRequestProcessor {
}
login_managed_bedrock(&self.config, &self.config_manager, api_key, region).await?;
self.auth_manager.reload().await;
Ok(LoginAccountResponse::AmazonBedrock {})
}
.await;
@@ -400,7 +391,7 @@ impl AccountRequestProcessor {
self.outgoing.send_result(request_id, result).await;
if logged_in {
self.emit_login_completed_notification(/*login_id*/ None)
self.send_login_success_notifications(/*login_id*/ None)
.await;
}
}
@@ -712,20 +703,6 @@ impl AccountRequestProcessor {
)
.await;
self.emit_login_success_notifications(login_id).await;
}
async fn emit_login_success_notifications(&self, login_id: Option<Uuid>) {
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<Uuid>) {
let payload_login_completed = AccountLoginCompletedNotification {
login_id: login_id.map(|id| id.to_string()),
success: true,
@@ -736,6 +713,12 @@ 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(
@@ -785,7 +768,7 @@ impl AccountRequestProcessor {
}
}
async fn logout_common(&self) -> Result<Option<AccountUpdatedNotification>, JSONRPCErrorError> {
async fn logout_common(&self) -> Result<Option<AuthMode>, JSONRPCErrorError> {
// Cancel any active login attempt.
{
let mut guard = self.active_login.lock().await;
@@ -796,6 +779,7 @@ impl AccountRequestProcessor {
if has_managed_bedrock_login(&self.config)? {
logout_managed_bedrock(&self.config, &self.config_manager).await?;
self.auth_manager.reload().await;
return Ok(None);
}
if self.config.model_provider.is_amazon_bedrock() {
@@ -817,20 +801,30 @@ impl AccountRequestProcessor {
.await;
// Reflect the current auth method after logout (likely None).
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,
}))
Ok(self
.auth_manager
.auth_cached()
.as_ref()
.map(CodexAuth::api_auth_mode)
.map(auth_mode_to_api))
}
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 = result.as_ref().ok().cloned().flatten();
let account_updated = if skip_account_updated {
None
} else {
result
.as_ref()
.ok()
.cloned()
.map(|auth_mode| AccountUpdatedNotification {
auth_mode,
plan_type: None,
})
};
self.outgoing
.send_result(request_id, result.map(|_| LogoutAccountResponse {}))
.await;
@@ -33,6 +33,7 @@ pub(super) async fn login(
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}")))?;
@@ -49,8 +50,12 @@ pub(super) async fn logout(
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}")))?;
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(
@@ -65,9 +70,13 @@ pub(super) async fn logout(
}
fn load_stored_auth(config: &Config) -> Result<Option<AuthDotJson>, 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}")))
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(
@@ -19,6 +19,7 @@ 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;
+116 -55
View File
@@ -13,6 +13,7 @@ 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::AccountUpdatedNotification;
use codex_app_server_protocol::AuthMode;
use codex_app_server_protocol::CancelLoginAccountParams;
use codex_app_server_protocol::CancelLoginAccountResponse;
@@ -155,6 +156,14 @@ fn read_config_toml(codex_home: &Path) -> Result<toml::Value> {
)?)?)
}
fn load_file_auth(codex_home: &Path) -> Result<Option<AuthDotJson>> {
Ok(load_auth_dot_json(
codex_home,
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?)
}
fn aws_managed_bedrock_config() -> CreateConfigTomlParams {
CreateConfigTomlParams {
model_provider_id: Some("amazon-bedrock".to_string()),
@@ -1028,6 +1037,7 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu
codex_home.path(),
"sk-test-key",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
let mut expected_config = read_config_toml(codex_home.path())?;
expected_config
@@ -1061,7 +1071,7 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
load_file_auth(codex_home.path())?,
Some(AuthDotJson {
auth_mode: Some(AuthMode::BedrockApiKey),
openai_api_key: None,
@@ -1093,11 +1103,25 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu
error: None,
}
);
assert_no_account_updated(&mut mcp).await;
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_eq!(
read_account(&mut mcp).await?,
GetAccountResponse {
account: Some(Account::ApiKey {}),
account: None,
requires_openai_auth: true,
}
);
@@ -1112,10 +1136,7 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu
to_response::<LogoutAccountResponse>(response)?,
LogoutAccountResponse {}
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
None
);
assert_eq!(load_file_auth(codex_home.path())?, None);
assert_eq!(
read_config_toml(codex_home.path())?,
expected_config_after_logout
@@ -1124,7 +1145,7 @@ async fn login_and_logout_amazon_bedrock_persist_changes_until_restart() -> Resu
assert_eq!(
read_account(&mut mcp).await?,
GetAccountResponse {
account: Some(Account::ApiKey {}),
account: None,
requires_openai_auth: true,
}
);
@@ -1163,15 +1184,13 @@ async fn managed_bedrock_login_requires_experimental_api_but_logout_is_best_effo
error.error.message,
"account/login/start.amazonBedrock requires experimentalApi capability"
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
None
);
assert_eq!(load_file_auth(codex_home.path())?, None);
login_with_bedrock_api_key(
codex_home.path(),
"managed-bedrock-api-key",
"us-west-2",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
let request_id = mcp.send_logout_account_request().await?;
let response: JSONRPCResponse = timeout(
@@ -1183,27 +1202,24 @@ async fn managed_bedrock_login_requires_experimental_api_but_logout_is_best_effo
to_response::<LogoutAccountResponse>(response)?,
LogoutAccountResponse {}
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
None
);
assert_eq!(load_file_auth(codex_home.path())?, None);
Ok(())
}
#[tokio::test]
async fn login_and_logout_managed_bedrock_require_restart_when_provider_is_active() -> Result<()> {
async fn login_and_logout_managed_bedrock_update_active_provider() -> Result<()> {
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), aws_managed_bedrock_config())?;
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()
.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?;
@@ -1221,12 +1237,16 @@ async fn login_and_logout_managed_bedrock_require_restart_when_provider_is_activ
mcp.read_stream_until_notification_message("account/login/completed"),
)
.await??;
assert_no_account_updated(&mut mcp).await;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("account/updated"),
)
.await??;
assert_eq!(
read_account(&mut mcp).await?,
GetAccountResponse {
account: Some(Account::AmazonBedrock {
credential_source: AmazonBedrockCredentialSource::AwsManaged,
credential_source: AmazonBedrockCredentialSource::CodexManaged,
}),
requires_openai_auth: false,
}
@@ -1243,10 +1263,7 @@ async fn login_and_logout_managed_bedrock_require_restart_when_provider_is_activ
to_response::<LogoutAccountResponse>(response)?,
LogoutAccountResponse {}
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
None
);
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;
@@ -1270,8 +1287,9 @@ async fn logout_account_aws_managed_bedrock_preserves_openai_auth_and_config() -
codex_home.path(),
"sk-test-key",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
let expected_auth = load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?;
let expected_auth = load_file_auth(codex_home.path())?;
let expected_config = read_config_toml(codex_home.path())?;
let mut mcp =
@@ -1288,10 +1306,7 @@ async fn logout_account_aws_managed_bedrock_preserves_openai_auth_and_config() -
to_response::<LogoutAccountResponse>(response)?,
LogoutAccountResponse {}
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
expected_auth
);
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;
Ok(())
@@ -1301,11 +1316,11 @@ async fn logout_account_aws_managed_bedrock_preserves_openai_auth_and_config() -
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 expected_config = read_config_toml(codex_home.path())?;
let request_id = mcp
.send_login_account_amazon_bedrock_request(" ", "us-west-2")
@@ -1332,11 +1347,67 @@ async fn login_account_amazon_bedrock_rejects_invalid_credentials_without_change
error.error.message,
"Amazon Bedrock Mantle does not support region `us-west-1`"
);
assert_eq!(load_file_auth(codex_home.path())?, None);
assert_eq!(read_config_toml(codex_home.path())?, expected_config);
Ok(())
}
#[tokio::test]
async fn login_account_amazon_bedrock_allows_codex_environment_auth() -> Result<()> {
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), CreateConfigTomlParams::default())?;
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 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 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!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
None
to_response::<LoginAccountResponse>(response)?,
LoginAccountResponse::AmazonBedrock {}
);
assert_eq!(
load_file_auth(codex_home.path())?,
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??;
drop(mcp);
let mut mcp = TestAppServer::new_with_env(
@@ -1348,23 +1419,15 @@ async fn login_account_amazon_bedrock_rejects_invalid_credentials_without_change
)
.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."
read_account(&mut mcp).await?,
GetAccountResponse {
account: Some(Account::AmazonBedrock {
credential_source: AmazonBedrockCredentialSource::CodexManaged,
}),
requires_openai_auth: false,
}
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
None
);
assert_eq!(read_config_toml(codex_home.path())?, expected_config);
Ok(())
}
@@ -1401,7 +1464,7 @@ async fn login_account_amazon_bedrock_persists_under_provider_override() -> Resu
LoginAccountResponse::AmazonBedrock {}
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
load_file_auth(codex_home.path())?,
Some(AuthDotJson {
auth_mode: Some(AuthMode::BedrockApiKey),
openai_api_key: None,
@@ -1441,6 +1504,7 @@ async fn logout_account_managed_bedrock_preserves_changed_provider() -> Result<(
"managed-bedrock-api-key",
"us-west-2",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
let expected_config = read_config_toml(codex_home.path())?;
@@ -1458,10 +1522,7 @@ async fn logout_account_managed_bedrock_preserves_changed_provider() -> Result<(
to_response::<LogoutAccountResponse>(response)?,
LogoutAccountResponse {}
);
assert_eq!(
load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)?,
None
);
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;
Ok(())