Support managed AWS access keys for Amazon Bedrock (#40481)

## What changed

- Add the experimental `amazonBedrockAccessKeys` app-server login flow, persist its credentials in the configured auth store, and use them for SigV4-signed Bedrock requests.
- Report `bedrockAccessKeys` as a distinct auth mode and document access-key login alongside AWS profile and environment credential setup.
- Clear the selected Bedrock provider, AWS settings, and Bedrock-specific model on logout while leaving external AWS credentials and `.env` untouched.
- Reject managed access-key login when higher-precedence configuration would prevent its region or profile settings from taking effect.

## Testing

- Cover access-key login, storage, request signing, configuration conflicts, status reporting, and logout cleanup.

GitOrigin-RevId: bbf297887c6503d3651ceb2aad85c4d626e32723
This commit is contained in:
alexsong-oai authored and copyberry committed 2026-08-24 21:39:48 +00:00
1 parent 219c203417
commit 4f6d43c267
60 files changed
+1464 -389

No files matched your search

+6
View File
@@ -370,6 +370,7 @@ async fn stored_agent_identity_jwt_keeps_auth_json_unchanged() -> anyhow::Result
agent_identity: Some(AgentIdentityStorage::Jwt(agent_identity.clone())),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
},
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
@@ -449,6 +450,7 @@ async fn login_with_access_token_writes_only_personal_access_token() {
agent_identity: None,
personal_access_token: Some("at-login-test".to_string()),
bedrock_api_key: None,
bedrock_access_keys: None,
}
);
assert_eq!(auth.resolved_mode(), AuthMode::PersonalAccessToken);
@@ -1068,6 +1070,7 @@ async fn pro_account_with_no_api_key_uses_chatgpt_auth() {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
},
auth_dot_json
);
@@ -1116,6 +1119,7 @@ fn logout_removes_auth_file() -> Result<(), std::io::Error> {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
super::save_auth(
dir.path(),
@@ -2331,6 +2335,7 @@ async fn workspace_policy_rejects_agent_identity_before_hydration() {
agent_identity: Some(stored_agent_identity),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
},
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
@@ -2572,6 +2577,7 @@ async fn enforce_login_restrictions_logs_out_for_agent_identity_workspace_mismat
agent_identity: Some(AgentIdentityStorage::Jwt(agent_identity)),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
},
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
@@ -0,0 +1,63 @@
use std::path::Path;
use codex_config::types::AuthCredentialsStoreMode;
use codex_protocol::auth::AuthMode;
use serde::Deserialize;
use serde::Serialize;
use super::manager::save_auth;
use super::storage::AuthDotJson;
use super::storage::AuthKeyringBackendKind;
/// Managed Amazon Bedrock AWS access keys persisted in auth storage.
#[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct BedrockAccessKeysAuth {
pub access_key_id: String,
pub secret_access_key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_token: Option<String>,
}
impl std::fmt::Debug for BedrockAccessKeysAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BedrockAccessKeysAuth")
.field("access_key_id", &"<redacted>")
.field("secret_access_key", &"<redacted>")
.field(
"session_token",
&self.session_token.as_ref().map(|_| "<redacted>"),
)
.finish()
}
}
/// Writes auth storage containing only Amazon Bedrock AWS access keys.
pub fn login_with_bedrock_access_keys(
codex_home: &Path,
access_key_id: &str,
secret_access_key: &str,
session_token: Option<&str>,
auth_credentials_store_mode: AuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> std::io::Result<()> {
let auth_dot_json = AuthDotJson {
auth_mode: Some(AuthMode::BedrockAccessKeys),
openai_api_key: None,
tokens: None,
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: Some(BedrockAccessKeysAuth {
access_key_id: access_key_id.to_string(),
secret_access_key: secret_access_key.to_string(),
session_token: session_token.map(str::to_string),
}),
};
save_auth(
codex_home,
&auth_dot_json,
auth_credentials_store_mode,
keyring_backend_kind,
)
}
@@ -35,6 +35,7 @@ pub fn login_with_bedrock_api_key(
api_key: api_key.to_string(),
region: region.to_string(),
}),
bedrock_access_keys: None,
};
save_auth(
codex_home,
@@ -20,6 +20,7 @@ fn api_key_auth() -> AuthDotJson {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
}
}
@@ -32,6 +33,7 @@ fn bedrock_only_auth() -> AuthDotJson {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: Some(bedrock_auth()),
bedrock_access_keys: None,
}
}
@@ -76,6 +78,7 @@ async fn login_with_bedrock_api_key_replaces_openai_auth() -> anyhow::Result<()>
agent_identity: None,
personal_access_token: None,
bedrock_api_key: Some(bedrock_auth()),
bedrock_access_keys: None,
};
assert_eq!(loaded, expected);
assert_eq!(auth_manager.auth_mode(), Some(AuthMode::BedrockApiKey));
@@ -87,7 +90,8 @@ async fn login_with_bedrock_api_key_replaces_openai_auth() -> anyhow::Result<()>
| CodexAuth::ChatgptAuthTokens(_)
| CodexAuth::Headers(_)
| CodexAuth::AgentIdentity(_)
| CodexAuth::PersonalAccessToken(_) => None,
| CodexAuth::PersonalAccessToken(_)
| CodexAuth::BedrockAccessKeys(_) => None,
}),
Some(bedrock_auth())
);
@@ -124,6 +128,60 @@ async fn logout_removes_bedrock_auth() -> anyhow::Result<()> {
Ok(())
}
#[tokio::test]
#[serial(codex_auth_env)]
async fn access_keys_auth_round_trips_and_logs_out() -> anyhow::Result<()> {
let codex_home = tempdir()?;
let storage = FileAuthStorage::new(codex_home.path().to_path_buf());
crate::auth::login_with_bedrock_access_keys(
codex_home.path(),
"access-key-id",
"secret-access-key",
Some("session-token"),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
let auth_manager = AuthManager::new(
codex_home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
Some(vec!["allowed-workspace".to_string()]),
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::default(),
crate::test_support::transport_default_auth_route_config(),
)
.await;
assert_eq!(auth_manager.auth_mode(), Some(AuthMode::BedrockAccessKeys));
assert_eq!(
auth_manager.auth_cached().and_then(|auth| match auth {
CodexAuth::BedrockAccessKeys(auth) => Some(auth),
CodexAuth::ApiKey(_)
| CodexAuth::Chatgpt(_)
| CodexAuth::ChatgptAuthTokens(_)
| CodexAuth::Headers(_)
| CodexAuth::AgentIdentity(_)
| CodexAuth::PersonalAccessToken(_)
| CodexAuth::BedrockApiKey(_) => None,
}),
Some(crate::auth::BedrockAccessKeysAuth {
access_key_id: "access-key-id".to_string(),
secret_access_key: "secret-access-key".to_string(),
session_token: Some("session-token".to_string()),
})
);
let auth_change_rx = auth_manager.auth_change_receiver();
let auth_revision = *auth_change_rx.borrow();
let mut auth_without_mode = storage.load()?.expect("access keys should be stored");
auth_without_mode.auth_mode = None;
storage.save(&auth_without_mode)?;
assert!(!auth_manager.reload().await);
assert_eq!(*auth_change_rx.borrow(), auth_revision);
assert!(auth_manager.logout().await?);
assert_eq!(storage.load()?, None);
Ok(())
}
#[tokio::test]
#[serial(codex_auth_env)]
async fn bedrock_only_auth_storage_creates_primary_auth() -> anyhow::Result<()> {
@@ -151,7 +209,8 @@ async fn bedrock_only_auth_storage_creates_primary_auth() -> anyhow::Result<()>
| CodexAuth::ChatgptAuthTokens(_)
| CodexAuth::Headers(_)
| CodexAuth::AgentIdentity(_)
| CodexAuth::PersonalAccessToken(_) => None,
| CodexAuth::PersonalAccessToken(_)
| CodexAuth::BedrockAccessKeys(_) => None,
}),
Some(bedrock_auth())
);
+45 -9
View File
@@ -43,6 +43,7 @@ use super::workload_identity::WorkloadIdentitySessionError;
use crate::auth::AuthHeaders;
pub use crate::auth::agent_identity::AgentIdentityAuth;
pub use crate::auth::agent_identity::AgentIdentityAuthError;
pub use crate::auth::bedrock_access_keys::BedrockAccessKeysAuth;
pub use crate::auth::bedrock_api_key::BedrockApiKeyAuth;
pub use crate::auth::personal_access_token::PersonalAccessTokenAuth;
pub use crate::auth::storage::AgentIdentityAuthRecord;
@@ -81,6 +82,7 @@ pub enum CodexAuth {
AgentIdentity(AgentIdentityAuth),
PersonalAccessToken(PersonalAccessTokenAuth),
BedrockApiKey(BedrockApiKeyAuth),
BedrockAccessKeys(BedrockAccessKeysAuth),
}
/// Policy for resolving Agent Identity auth from a broader Codex auth snapshot.
@@ -155,6 +157,7 @@ impl PartialEq for CodexAuth {
(Self::Headers(a), Self::Headers(b)) => a == b,
(Self::PersonalAccessToken(a), Self::PersonalAccessToken(b)) => a == b,
(Self::BedrockApiKey(a), Self::BedrockApiKey(b)) => a == b,
(Self::BedrockAccessKeys(a), Self::BedrockAccessKeys(b)) => a == b,
_ => self.api_auth_mode() == other.api_auth_mode(),
}
}
@@ -359,6 +362,14 @@ impl CodexAuth {
};
return Ok(Self::BedrockApiKey(auth));
}
if auth_mode == AuthMode::BedrockAccessKeys {
let Some(auth) = auth_dot_json.bedrock_access_keys else {
return Err(std::io::Error::other(
"Bedrock access keys auth is missing AWS access keys.",
));
};
return Ok(Self::BedrockAccessKeys(auth));
}
if auth_mode == AuthMode::Headers {
return Err(std::io::Error::other(
"externally provided auth cannot be loaded from auth storage.",
@@ -391,6 +402,9 @@ impl CodexAuth {
unreachable!("personal access token mode is handled above")
}
AuthMode::BedrockApiKey => unreachable!("bedrock api key mode is handled above"),
AuthMode::BedrockAccessKeys => {
unreachable!("bedrock access keys mode is handled above")
}
}
}
@@ -473,6 +487,7 @@ impl CodexAuth {
Self::AgentIdentity(_) => AuthMode::AgentIdentity,
Self::PersonalAccessToken(_) => AuthMode::PersonalAccessToken,
Self::BedrockApiKey(_) => AuthMode::BedrockApiKey,
Self::BedrockAccessKeys(_) => AuthMode::BedrockAccessKeys,
}
}
@@ -486,6 +501,7 @@ impl CodexAuth {
Self::AgentIdentity(_) => AuthMode::AgentIdentity,
Self::PersonalAccessToken(_) => AuthMode::PersonalAccessToken,
Self::BedrockApiKey(_) => AuthMode::BedrockApiKey,
Self::BedrockAccessKeys(_) => AuthMode::BedrockAccessKeys,
}
}
@@ -525,7 +541,8 @@ impl CodexAuth {
| Self::Headers(_)
| Self::AgentIdentity(_)
| Self::PersonalAccessToken(_)
| Self::BedrockApiKey(_) => None,
| Self::BedrockApiKey(_)
| Self::BedrockAccessKeys(_) => None,
}
}
@@ -557,7 +574,7 @@ impl CodexAuth {
"header auth does not expose a bearer token",
)),
Self::PersonalAccessToken(auth) => Ok(auth.access_token().to_string()),
Self::BedrockApiKey(_) => Err(std::io::Error::other(
Self::BedrockApiKey(_) | Self::BedrockAccessKeys(_) => Err(std::io::Error::other(
"Bedrock API key auth does not expose a Codex bearer token",
)),
}
@@ -648,7 +665,8 @@ impl CodexAuth {
| Self::Headers(_)
| Self::AgentIdentity(_)
| Self::PersonalAccessToken(_)
| Self::BedrockApiKey(_) => return None,
| Self::BedrockApiKey(_)
| Self::BedrockAccessKeys(_) => return None,
};
#[expect(clippy::unwrap_used)]
state.auth_dot_json.lock().unwrap().clone()
@@ -693,7 +711,8 @@ impl CodexAuth {
| Self::ChatgptAuthTokens(_)
| Self::Headers(_)
| Self::PersonalAccessToken(_)
| Self::BedrockApiKey(_) => Ok(None),
| Self::BedrockApiKey(_)
| Self::BedrockAccessKeys(_) => Ok(None),
Self::Chatgpt(_) => {
if policy == AgentIdentityAuthPolicy::JwtOnly {
return Ok(None);
@@ -766,6 +785,7 @@ impl CodexAuth {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
let state = ChatgptAuthState {
@@ -970,6 +990,7 @@ pub fn login_with_api_key(
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
save_auth(
codex_home,
@@ -1003,6 +1024,7 @@ pub async fn login_with_access_token(
agent_identity: None,
personal_access_token: Some(access_token.to_string()),
bedrock_api_key: None,
bedrock_access_keys: None,
}
}
CodexAccessToken::AgentIdentityJwt(jwt) => {
@@ -1021,6 +1043,7 @@ pub async fn login_with_access_token(
agent_identity: Some(AgentIdentityStorage::Jwt(jwt.to_string())),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
}
}
};
@@ -1219,7 +1242,10 @@ fn validate_auth_restrictions(
let Some(expected_workspaces) = expected_workspaces else {
return Ok(());
};
if matches!(auth, CodexAuth::ApiKey(_) | CodexAuth::BedrockApiKey(_)) {
if matches!(
auth,
CodexAuth::ApiKey(_) | CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_)
) {
return Ok(());
}
@@ -1281,7 +1307,8 @@ async fn enforce_login_restrictions_with_agent_identity_authapi_base_url(
if let Some(required_method) = config.forced_login_method {
let method_violation = match (required_method, auth.auth_mode()) {
(ForcedLoginMethod::Api, AuthMode::ApiKey)
| (ForcedLoginMethod::Api, AuthMode::BedrockApiKey) => None,
| (ForcedLoginMethod::Api, AuthMode::BedrockApiKey)
| (ForcedLoginMethod::Api, AuthMode::BedrockAccessKeys) => None,
(ForcedLoginMethod::Chatgpt, AuthMode::Chatgpt)
| (ForcedLoginMethod::Chatgpt, AuthMode::ChatgptAuthTokens)
| (ForcedLoginMethod::Chatgpt, AuthMode::Headers)
@@ -1296,7 +1323,8 @@ async fn enforce_login_restrictions_with_agent_identity_authapi_base_url(
.to_string(),
),
(ForcedLoginMethod::Chatgpt, AuthMode::ApiKey)
| (ForcedLoginMethod::Chatgpt, AuthMode::BedrockApiKey) => Some(
| (ForcedLoginMethod::Chatgpt, AuthMode::BedrockApiKey)
| (ForcedLoginMethod::Chatgpt, AuthMode::BedrockAccessKeys) => Some(
"ChatGPT login is required, but an API key is currently being used. Logging out."
.to_string(),
),
@@ -1314,7 +1342,9 @@ async fn enforce_login_restrictions_with_agent_identity_authapi_base_url(
if let Some(expected_account_ids) = config.forced_chatgpt_workspace_id.as_deref() {
let chatgpt_account_id = match &auth {
CodexAuth::ApiKey(_) | CodexAuth::BedrockApiKey(_) => {
CodexAuth::ApiKey(_)
| CodexAuth::BedrockApiKey(_)
| CodexAuth::BedrockAccessKeys(_) => {
return Ok(());
}
CodexAuth::Headers(_)
@@ -1717,6 +1747,7 @@ impl AuthDotJson {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
})
}
@@ -1730,6 +1761,9 @@ impl AuthDotJson {
if self.bedrock_api_key.is_some() {
return AuthMode::BedrockApiKey;
}
if self.bedrock_access_keys.is_some() {
return AuthMode::BedrockAccessKeys;
}
if self.openai_api_key.is_some() {
return AuthMode::ApiKey;
}
@@ -2449,6 +2483,7 @@ impl AuthManager {
},
(AuthMode::PersonalAccessToken, AuthMode::PersonalAccessToken) => a == b,
(AuthMode::BedrockApiKey, AuthMode::BedrockApiKey) => a == b,
(AuthMode::BedrockAccessKeys, AuthMode::BedrockAccessKeys) => a == b,
_ => false,
},
_ => false,
@@ -2810,7 +2845,8 @@ impl AuthManager {
| CodexAuth::Headers(_)
| CodexAuth::AgentIdentity(_)
| CodexAuth::PersonalAccessToken(_)
| CodexAuth::BedrockApiKey(_) => Ok(()),
| CodexAuth::BedrockApiKey(_)
| CodexAuth::BedrockAccessKeys(_) => Ok(()),
}
};
if let Err(RefreshTokenError::Permanent(error)) = &result {
+3
View File
@@ -1,6 +1,7 @@
mod access_token;
mod agent_identity;
mod auth_headers;
mod bedrock_access_keys;
mod bedrock_api_key;
pub mod default_client;
pub mod error;
@@ -14,6 +15,8 @@ mod manager;
mod revoke;
pub use auth_headers::AuthHeaders;
pub use bedrock_access_keys::BedrockAccessKeysAuth;
pub use bedrock_access_keys::login_with_bedrock_access_keys;
pub use bedrock_api_key::BedrockApiKeyAuth;
pub use bedrock_api_key::login_with_bedrock_api_key;
pub use error::RefreshTokenFailedError;
+4
View File
@@ -18,6 +18,7 @@ use std::sync::Arc;
use std::sync::Mutex;
use tracing::warn;
use super::BedrockAccessKeysAuth;
use super::BedrockApiKeyAuth;
use crate::token_data::TokenData;
use codex_agent_identity::AgentIdentityJwtClaims;
@@ -58,6 +59,9 @@ pub struct AuthDotJson {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bedrock_api_key: Option<BedrockApiKeyAuth>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bedrock_access_keys: Option<BedrockAccessKeysAuth>,
}
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
+12
View File
@@ -26,6 +26,7 @@ async fn file_storage_load_returns_auth_dot_json() -> anyhow::Result<()> {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
storage
@@ -49,6 +50,7 @@ async fn file_storage_save_persists_auth_dot_json() -> anyhow::Result<()> {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
let file = get_auth_file(codex_home.path());
@@ -84,6 +86,7 @@ async fn file_storage_round_trips_agent_identity_auth() -> anyhow::Result<()> {
agent_identity: Some(AgentIdentityStorage::Jwt(agent_identity)),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
storage.save(&auth_dot_json)?;
@@ -115,6 +118,7 @@ async fn file_storage_round_trips_registered_agent_identity_auth() -> anyhow::Re
agent_identity: Some(AgentIdentityStorage::Record(record)),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
storage.save(&auth_dot_json)?;
@@ -166,6 +170,7 @@ async fn file_storage_loads_empty_agent_identity_email_as_none() -> anyhow::Resu
})),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
})
);
Ok(())
@@ -192,6 +197,7 @@ async fn file_storage_writes_missing_agent_identity_email_as_empty_string() -> a
})),
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
storage.save(&auth_dot_json)?;
@@ -215,6 +221,7 @@ async fn file_storage_round_trips_personal_access_token_auth() -> anyhow::Result
agent_identity: None,
personal_access_token: Some("at-example".to_string()),
bedrock_api_key: None,
bedrock_access_keys: None,
};
storage.save(&auth_dot_json)?;
@@ -266,6 +273,7 @@ fn file_storage_delete_removes_auth_file() -> anyhow::Result<()> {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
let storage = create_auth_storage(
dir.path().to_path_buf(),
@@ -297,6 +305,7 @@ fn ephemeral_storage_save_load_delete_is_in_memory_only() -> anyhow::Result<()>
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
storage.save(&auth_dot_json)?;
@@ -430,6 +439,7 @@ fn auth_with_prefix(prefix: &str) -> AuthDotJson {
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
}
}
@@ -457,6 +467,7 @@ fn secrets_keyring_auth_storage_load_returns_deserialized_auth() -> anyhow::Resu
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
seed_secrets_backend_with_auth(&mock_keyring, codex_home.path(), &expected)?;
@@ -595,6 +606,7 @@ fn secrets_keyring_auth_storage_save_persists_and_removes_fallback_file() -> any
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
storage.save(&auth)?;
+1
View File
@@ -54,6 +54,7 @@ pub use auth::is_workload_identity_selected;
pub use auth::load_auth_dot_json;
pub use auth::login_with_access_token;
pub use auth::login_with_api_key;
pub use auth::login_with_bedrock_access_keys;
pub use auth::login_with_bedrock_api_key;
pub use auth::logout;
pub use auth::logout_with_revoke;
+1
View File
@@ -915,6 +915,7 @@ pub(crate) async fn persist_tokens_async(
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
save_auth(
&codex_home,