Rimossi i provider integrati OpenAI, Bedrock e GCP e ogni fallback a OpenAI (B)
Parte "sicurezza" della fase 3 di aKode (e39aae00), senza le funzioni di imeAI:
- via i provider integrati openai, amazon-bedrock, amazon-bedrock-runtime e gcp
(crate model-provider: moduli amazon_bedrock, gcp, chatgpt_base_url; login Bedrock;
onboarding Bedrock/GCP; richieste app-server di setup cloud);
- nessun URL predefinito verso api.openai.com / chatgpt.com: un provider senza
base_url non viene mai contattato; senza model_provider configurato exec e TUI
mostrano come scriverne uno in config.toml (NO_MODEL_PROVIDER_CONFIGURED_ERROR);
- via la skill openai-docs, la sample skill-installer (scaricava da github.com/openai/skills),
request_plugin_install, AppsInstructions, URL predefiniti di realtime e updater;
- test di sicurezza adattati (provider "mock" al posto di quello integrato), non cancellati.
Restano fuori da questo commit (categoria F/D/E, non portate): chiave per provider nel
portachiavi, modelli da /models, unione dei messaggi di sistema, crate web-tools e
SearXNG, header @@ in apply_patch, modello ausiliario, tool function per apply_patch.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,617 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_api::AuthError;
|
||||
use codex_api::AuthProvider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_aws_auth::AwsAccessKeys;
|
||||
use codex_aws_auth::AwsAuthContext;
|
||||
use codex_aws_auth::AwsAuthError;
|
||||
use codex_aws_auth::AwsRequestToSign;
|
||||
use codex_http_client::Request;
|
||||
use codex_http_client::RequestBody;
|
||||
use codex_http_client::RequestCompression;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use http::HeaderMap;
|
||||
|
||||
use crate::BearerAuthProvider;
|
||||
use crate::shared_state::process_shared_state;
|
||||
|
||||
use super::BedrockEndpoint;
|
||||
use super::mantle::aws_auth_config;
|
||||
use super::mantle::region_from_config;
|
||||
use super::runtime;
|
||||
|
||||
pub(super) const AWS_BEARER_TOKEN_BEDROCK_ENV_VAR: &str = "AWS_BEARER_TOKEN_BEDROCK";
|
||||
const AWS_ACCESS_KEY_ID_ENV_VAR: &str = "AWS_ACCESS_KEY_ID";
|
||||
const AWS_SECRET_ACCESS_KEY_ENV_VAR: &str = "AWS_SECRET_ACCESS_KEY";
|
||||
const AWS_REGION_ENV_VAR: &str = "AWS_REGION";
|
||||
const AWS_DEFAULT_REGION_ENV_VAR: &str = "AWS_DEFAULT_REGION";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum BedrockAuthSource {
|
||||
CommandBearerToken,
|
||||
CredentialExport,
|
||||
ConfiguredAwsProfile,
|
||||
ManagedBearerToken,
|
||||
ManagedAccessKeys,
|
||||
EnvBearerToken,
|
||||
EnvAwsCredentials,
|
||||
AwsSdk,
|
||||
}
|
||||
|
||||
pub(super) enum BedrockAuthMethod {
|
||||
ManagedBearerToken { token: String, region: String },
|
||||
EnvBearerToken { token: String, region: String },
|
||||
AwsSdkAuth { context: AwsAuthContext },
|
||||
}
|
||||
|
||||
pub(super) fn auth_source(
|
||||
provider_info: &ModelProviderInfo,
|
||||
auth_manager: Option<&AuthManager>,
|
||||
env_var: impl Fn(&'static str) -> std::result::Result<String, std::env::VarError> + Copy,
|
||||
) -> BedrockAuthSource {
|
||||
if provider_info.has_command_auth() {
|
||||
BedrockAuthSource::CommandBearerToken
|
||||
} else if provider_info
|
||||
.aws
|
||||
.as_ref()
|
||||
.is_some_and(|aws| aws.credential_export.is_some())
|
||||
{
|
||||
BedrockAuthSource::CredentialExport
|
||||
} else if provider_info
|
||||
.aws
|
||||
.as_ref()
|
||||
.is_some_and(|aws| aws.profile.is_some())
|
||||
{
|
||||
BedrockAuthSource::ConfiguredAwsProfile
|
||||
} else if matches!(
|
||||
auth_manager.and_then(AuthManager::auth_cached),
|
||||
Some(CodexAuth::BedrockApiKey(_))
|
||||
) {
|
||||
BedrockAuthSource::ManagedBearerToken
|
||||
} else if matches!(
|
||||
auth_manager.and_then(AuthManager::auth_cached),
|
||||
Some(CodexAuth::BedrockAccessKeys(_))
|
||||
) {
|
||||
BedrockAuthSource::ManagedAccessKeys
|
||||
} else if non_empty_env_var_from(AWS_BEARER_TOKEN_BEDROCK_ENV_VAR, env_var).is_some() {
|
||||
BedrockAuthSource::EnvBearerToken
|
||||
} else if non_empty_env_var_from(AWS_ACCESS_KEY_ID_ENV_VAR, env_var).is_some()
|
||||
&& non_empty_env_var_from(AWS_SECRET_ACCESS_KEY_ENV_VAR, env_var).is_some()
|
||||
{
|
||||
BedrockAuthSource::EnvAwsCredentials
|
||||
} else {
|
||||
BedrockAuthSource::AwsSdk
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_auth_method(
|
||||
source: BedrockAuthSource,
|
||||
managed_auth: Option<&CodexAuth>,
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
endpoint: BedrockEndpoint,
|
||||
http_client_factory: &codex_http_client::HttpClientFactory,
|
||||
) -> Result<BedrockAuthMethod> {
|
||||
match source {
|
||||
BedrockAuthSource::CommandBearerToken => Err(CodexErr::Fatal(
|
||||
"Amazon Bedrock command authentication must be resolved by the model provider"
|
||||
.to_string(),
|
||||
)),
|
||||
BedrockAuthSource::CredentialExport => {
|
||||
let config = match endpoint {
|
||||
BedrockEndpoint::Mantle => aws_auth_config(aws),
|
||||
BedrockEndpoint::Runtime => runtime::aws_auth_config(aws),
|
||||
};
|
||||
let credential_export = process_shared_state()
|
||||
.aws_credential_export(aws)
|
||||
.ok_or_else(|| {
|
||||
CodexErr::Fatal(
|
||||
"selected Amazon Bedrock credential exporter is no longer configured"
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
let context = AwsAuthContext::load_with_credentials_provider(
|
||||
config,
|
||||
credential_export,
|
||||
http_client_factory.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(aws_auth_error_to_codex_error)?;
|
||||
Ok(BedrockAuthMethod::AwsSdkAuth { context })
|
||||
}
|
||||
BedrockAuthSource::ManagedBearerToken => {
|
||||
let Some(CodexAuth::BedrockApiKey(auth)) = managed_auth else {
|
||||
return Err(CodexErr::Fatal(
|
||||
"selected Codex-managed Amazon Bedrock API key is no longer available"
|
||||
.to_string(),
|
||||
));
|
||||
};
|
||||
Ok(BedrockAuthMethod::ManagedBearerToken {
|
||||
token: auth.api_key.clone(),
|
||||
region: auth.region.clone(),
|
||||
})
|
||||
}
|
||||
BedrockAuthSource::EnvBearerToken => {
|
||||
let token = non_empty_env_var_from(AWS_BEARER_TOKEN_BEDROCK_ENV_VAR, std::env::var)
|
||||
.ok_or_else(|| {
|
||||
CodexErr::Fatal(
|
||||
"selected `AWS_BEARER_TOKEN_BEDROCK` credential is no longer available"
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
let region = bearer_token_region(aws, std::env::var)?;
|
||||
Ok(BedrockAuthMethod::EnvBearerToken { token, region })
|
||||
}
|
||||
BedrockAuthSource::ConfiguredAwsProfile => {
|
||||
let config = match endpoint {
|
||||
BedrockEndpoint::Mantle => aws_auth_config(aws),
|
||||
BedrockEndpoint::Runtime => runtime::aws_auth_config(aws),
|
||||
};
|
||||
let context = AwsAuthContext::load_profile(config, http_client_factory.clone())
|
||||
.await
|
||||
.map_err(aws_auth_error_to_codex_error)?;
|
||||
Ok(BedrockAuthMethod::AwsSdkAuth { context })
|
||||
}
|
||||
BedrockAuthSource::ManagedAccessKeys => {
|
||||
let Some(CodexAuth::BedrockAccessKeys(auth)) = managed_auth else {
|
||||
return Err(CodexErr::Fatal(
|
||||
"selected Codex-managed Amazon Bedrock access keys are no longer available"
|
||||
.to_string(),
|
||||
));
|
||||
};
|
||||
let access_keys = AwsAccessKeys {
|
||||
access_key_id: auth.access_key_id.clone(),
|
||||
secret_access_key: auth.secret_access_key.clone(),
|
||||
session_token: auth.session_token.clone(),
|
||||
};
|
||||
let config = match endpoint {
|
||||
BedrockEndpoint::Mantle => aws_auth_config(aws),
|
||||
BedrockEndpoint::Runtime => runtime::aws_auth_config(aws),
|
||||
};
|
||||
let context = AwsAuthContext::load_with_access_keys(
|
||||
config,
|
||||
access_keys,
|
||||
http_client_factory.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(aws_auth_error_to_codex_error)?;
|
||||
Ok(BedrockAuthMethod::AwsSdkAuth { context })
|
||||
}
|
||||
BedrockAuthSource::EnvAwsCredentials | BedrockAuthSource::AwsSdk => {
|
||||
let config = match endpoint {
|
||||
BedrockEndpoint::Mantle => aws_auth_config(aws),
|
||||
BedrockEndpoint::Runtime => runtime::aws_auth_config(aws),
|
||||
};
|
||||
let context = AwsAuthContext::load(config, http_client_factory.clone())
|
||||
.await
|
||||
.map_err(aws_auth_error_to_codex_error)?;
|
||||
Ok(BedrockAuthMethod::AwsSdkAuth { context })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_provider_auth(
|
||||
source: BedrockAuthSource,
|
||||
managed_auth: Option<&CodexAuth>,
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
endpoint: BedrockEndpoint,
|
||||
http_client_factory: &codex_http_client::HttpClientFactory,
|
||||
) -> Result<SharedAuthProvider> {
|
||||
match resolve_auth_method(source, managed_auth, aws, endpoint, http_client_factory).await? {
|
||||
BedrockAuthMethod::ManagedBearerToken { token, .. }
|
||||
| BedrockAuthMethod::EnvBearerToken { token, .. } => Ok(Arc::new(BearerAuthProvider {
|
||||
token: Some(token),
|
||||
is_fedramp_account: false,
|
||||
})),
|
||||
BedrockAuthMethod::AwsSdkAuth { context } => {
|
||||
Ok(Arc::new(BedrockSigV4AuthProvider::new(context, endpoint)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_region(
|
||||
source: BedrockAuthSource,
|
||||
managed_auth: Option<&CodexAuth>,
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
endpoint: BedrockEndpoint,
|
||||
http_client_factory: &codex_http_client::HttpClientFactory,
|
||||
) -> Result<String> {
|
||||
if source == BedrockAuthSource::CommandBearerToken {
|
||||
let config = match endpoint {
|
||||
BedrockEndpoint::Mantle => aws_auth_config(aws),
|
||||
BedrockEndpoint::Runtime => runtime::aws_auth_config(aws),
|
||||
};
|
||||
let context = AwsAuthContext::load(config, http_client_factory.clone())
|
||||
.await
|
||||
.map_err(aws_auth_error_to_codex_error)?;
|
||||
return Ok(context.region().to_string());
|
||||
}
|
||||
|
||||
match resolve_auth_method(source, managed_auth, aws, endpoint, http_client_factory).await? {
|
||||
BedrockAuthMethod::ManagedBearerToken { region, .. }
|
||||
| BedrockAuthMethod::EnvBearerToken { region, .. } => Ok(region),
|
||||
BedrockAuthMethod::AwsSdkAuth { context } => Ok(context.region().to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_env_var_from(
|
||||
name: &'static str,
|
||||
env_var: impl Fn(&'static str) -> std::result::Result<String, std::env::VarError>,
|
||||
) -> Option<String> {
|
||||
env_var(name)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn bearer_token_region(
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
env_var: impl Fn(&'static str) -> std::result::Result<String, std::env::VarError> + Copy,
|
||||
) -> Result<String> {
|
||||
region_from_config(aws)
|
||||
.or_else(|| non_empty_env_var_from(AWS_REGION_ENV_VAR, env_var))
|
||||
.or_else(|| non_empty_env_var_from(AWS_DEFAULT_REGION_ENV_VAR, env_var))
|
||||
.ok_or_else(|| {
|
||||
CodexErr::Fatal(
|
||||
"Amazon Bedrock bearer token auth requires \
|
||||
`model_providers.amazon-bedrock.aws.region`, `AWS_REGION`, or `AWS_DEFAULT_REGION`"
|
||||
.to_string(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn aws_auth_error_to_codex_error(error: AwsAuthError) -> CodexErr {
|
||||
CodexErr::Fatal(format!("failed to resolve Amazon Bedrock auth: {error}"))
|
||||
}
|
||||
|
||||
fn aws_auth_error_to_auth_error(error: AwsAuthError) -> AuthError {
|
||||
if let Some(source) = error.credentials_provider_error() {
|
||||
// Command failures need provider recovery, not repeated HTTP transport attempts.
|
||||
return AuthError::Build(if error.is_retryable() {
|
||||
format!("failed to load AWS credentials: {source}")
|
||||
} else {
|
||||
format!(
|
||||
"{} {source}",
|
||||
super::error::CREDENTIAL_EXPORT_CONFIG_ERROR_PREFIX
|
||||
)
|
||||
});
|
||||
}
|
||||
if error.is_retryable() {
|
||||
AuthError::Transient(error.to_string())
|
||||
} else {
|
||||
AuthError::Build(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_headers_not_preserved_by_bedrock_mantle(headers: &mut HeaderMap) {
|
||||
// The Bedrock Mantle front door does not preserve legacy OpenAI
|
||||
// compatibility headers that use snake_case, such as `session_id` and
|
||||
// `thread_id`, before SigV4 verification. Signing that header class makes
|
||||
// richer Codex agent requests fail even though raw Responses requests work.
|
||||
let headers_to_remove = headers
|
||||
.keys()
|
||||
.filter(|name| name.as_str().contains('_'))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
for name in headers_to_remove {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// AWS SigV4 auth provider for Bedrock OpenAI-compatible requests.
|
||||
#[derive(Debug)]
|
||||
struct BedrockSigV4AuthProvider {
|
||||
context: AwsAuthContext,
|
||||
endpoint: BedrockEndpoint,
|
||||
}
|
||||
|
||||
impl BedrockSigV4AuthProvider {
|
||||
fn new(context: AwsAuthContext, endpoint: BedrockEndpoint) -> Self {
|
||||
Self { context, endpoint }
|
||||
}
|
||||
|
||||
async fn apply_auth(&self, request: Request) -> std::result::Result<Request, AuthError> {
|
||||
let mut request = request;
|
||||
if self.endpoint == BedrockEndpoint::Mantle {
|
||||
remove_headers_not_preserved_by_bedrock_mantle(&mut request.headers);
|
||||
}
|
||||
let prepared = request.prepare_body_for_send().map_err(AuthError::Build)?;
|
||||
let signed = self
|
||||
.context
|
||||
.sign(AwsRequestToSign {
|
||||
method: request.method.clone(),
|
||||
url: request.url.clone(),
|
||||
headers: prepared.headers.clone(),
|
||||
body: prepared.body_bytes(),
|
||||
})
|
||||
.await
|
||||
.map_err(aws_auth_error_to_auth_error)?;
|
||||
|
||||
request.url = signed.url;
|
||||
request.headers = signed.headers;
|
||||
request.body = prepared.body.map(RequestBody::Raw);
|
||||
request.compression = RequestCompression::None;
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthProvider for BedrockSigV4AuthProvider {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> std::result::Result<(), AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_auth(&self, request: Request) -> codex_api::AuthProviderFuture<'_> {
|
||||
Box::pin(BedrockSigV4AuthProvider::apply_auth(self, request))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::num::NonZeroU64;
|
||||
|
||||
use codex_api::AuthProvider;
|
||||
use codex_login::auth::BedrockAccessKeysAuth;
|
||||
use codex_login::auth::BedrockApiKeyAuth;
|
||||
use codex_model_provider_info::AwsCredentialExportConfig;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn missing_env_var(_: &'static str) -> std::result::Result<String, std::env::VarError> {
|
||||
Err(std::env::VarError::NotPresent)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_auth_source_distinguishes_static_environment_credentials() {
|
||||
let provider = ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None);
|
||||
let configured_profile_provider =
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: Some("configured-profile".to_string()),
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
}));
|
||||
let credential_export_provider =
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: Some(AwsCredentialExportConfig {
|
||||
command: "export-credentials".to_string(),
|
||||
args: Vec::new(),
|
||||
timeout_ms: NonZeroU64::new(30_000).expect("timeout should be non-zero"),
|
||||
}),
|
||||
auth_refresh: None,
|
||||
}));
|
||||
let managed_auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "managed-bedrock-api-key".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
}));
|
||||
let managed_access_keys = AuthManager::from_auth_for_testing(CodexAuth::BedrockAccessKeys(
|
||||
BedrockAccessKeysAuth {
|
||||
access_key_id: "managed-access-key-id".to_string(),
|
||||
secret_access_key: "managed-secret-access-key".to_string(),
|
||||
session_token: None,
|
||||
},
|
||||
));
|
||||
let cases: &[(
|
||||
&ModelProviderInfo,
|
||||
Option<&AuthManager>,
|
||||
&[&str],
|
||||
BedrockAuthSource,
|
||||
)] = &[
|
||||
(
|
||||
&credential_export_provider,
|
||||
Some(managed_auth.as_ref()),
|
||||
&[
|
||||
AWS_BEARER_TOKEN_BEDROCK_ENV_VAR,
|
||||
AWS_ACCESS_KEY_ID_ENV_VAR,
|
||||
AWS_SECRET_ACCESS_KEY_ENV_VAR,
|
||||
],
|
||||
BedrockAuthSource::CredentialExport,
|
||||
),
|
||||
(
|
||||
&credential_export_provider,
|
||||
Some(managed_access_keys.as_ref()),
|
||||
&[AWS_BEARER_TOKEN_BEDROCK_ENV_VAR],
|
||||
BedrockAuthSource::CredentialExport,
|
||||
),
|
||||
(
|
||||
&configured_profile_provider,
|
||||
Some(managed_auth.as_ref()),
|
||||
&[
|
||||
AWS_BEARER_TOKEN_BEDROCK_ENV_VAR,
|
||||
AWS_ACCESS_KEY_ID_ENV_VAR,
|
||||
AWS_SECRET_ACCESS_KEY_ENV_VAR,
|
||||
],
|
||||
BedrockAuthSource::ConfiguredAwsProfile,
|
||||
),
|
||||
(
|
||||
&provider,
|
||||
Some(managed_auth.as_ref()),
|
||||
&[AWS_BEARER_TOKEN_BEDROCK_ENV_VAR],
|
||||
BedrockAuthSource::ManagedBearerToken,
|
||||
),
|
||||
(
|
||||
&configured_profile_provider,
|
||||
Some(managed_access_keys.as_ref()),
|
||||
&[AWS_BEARER_TOKEN_BEDROCK_ENV_VAR],
|
||||
BedrockAuthSource::ConfiguredAwsProfile,
|
||||
),
|
||||
(
|
||||
&provider,
|
||||
Some(managed_access_keys.as_ref()),
|
||||
&[AWS_BEARER_TOKEN_BEDROCK_ENV_VAR],
|
||||
BedrockAuthSource::ManagedAccessKeys,
|
||||
),
|
||||
(
|
||||
&provider,
|
||||
None,
|
||||
&[
|
||||
AWS_BEARER_TOKEN_BEDROCK_ENV_VAR,
|
||||
AWS_ACCESS_KEY_ID_ENV_VAR,
|
||||
AWS_SECRET_ACCESS_KEY_ENV_VAR,
|
||||
],
|
||||
BedrockAuthSource::EnvBearerToken,
|
||||
),
|
||||
(
|
||||
&provider,
|
||||
None,
|
||||
&[AWS_ACCESS_KEY_ID_ENV_VAR, AWS_SECRET_ACCESS_KEY_ENV_VAR],
|
||||
BedrockAuthSource::EnvAwsCredentials,
|
||||
),
|
||||
(
|
||||
&provider,
|
||||
None,
|
||||
&[AWS_ACCESS_KEY_ID_ENV_VAR],
|
||||
BedrockAuthSource::AwsSdk,
|
||||
),
|
||||
(
|
||||
&provider,
|
||||
None,
|
||||
&["AWS_PROFILE", AWS_REGION_ENV_VAR],
|
||||
BedrockAuthSource::AwsSdk,
|
||||
),
|
||||
];
|
||||
|
||||
for (provider, auth_manager, variables, expected) in cases {
|
||||
let actual = auth_source(provider, *auth_manager, |name| {
|
||||
variables
|
||||
.contains(&name)
|
||||
.then(|| "configured".to_string())
|
||||
.ok_or(std::env::VarError::NotPresent)
|
||||
});
|
||||
assert_eq!(actual, *expected, "{variables:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_bearer_auth_prefers_configured_region_and_uses_header() {
|
||||
let token = "bedrock-api-key-test".to_string();
|
||||
let region = bearer_token_region(
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some(" us-west-2 ".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
|name| match name {
|
||||
AWS_REGION_ENV_VAR => Ok("eu-west-1".to_string()),
|
||||
_ => Err(std::env::VarError::NotPresent),
|
||||
},
|
||||
)
|
||||
.expect("configured region should resolve");
|
||||
let provider = BearerAuthProvider {
|
||||
token: Some(token),
|
||||
is_fedramp_account: false,
|
||||
};
|
||||
let mut headers = http::HeaderMap::new();
|
||||
|
||||
provider.add_auth_headers(&mut headers).unwrap();
|
||||
|
||||
assert_eq!(region, "us-west-2");
|
||||
assert!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|value| value.starts_with("Bearer bedrock-api-key-"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_bearer_auth_uses_aws_region_env() {
|
||||
let region = bearer_token_region(
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
|name| match name {
|
||||
AWS_REGION_ENV_VAR => Ok(" eu-central-1 ".to_string()),
|
||||
_ => Err(std::env::VarError::NotPresent),
|
||||
},
|
||||
)
|
||||
.expect("AWS_REGION should resolve");
|
||||
|
||||
assert_eq!(region, "eu-central-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_bearer_auth_uses_aws_default_region_env() {
|
||||
let region = bearer_token_region(
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
|name| match name {
|
||||
AWS_DEFAULT_REGION_ENV_VAR => Ok("ap-northeast-1".to_string()),
|
||||
_ => Err(std::env::VarError::NotPresent),
|
||||
},
|
||||
)
|
||||
.expect("AWS_DEFAULT_REGION should resolve");
|
||||
|
||||
assert_eq!(region, "ap-northeast-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_bearer_auth_rejects_missing_configured_region() {
|
||||
let err = bearer_token_region(
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
missing_env_var,
|
||||
)
|
||||
.expect_err("missing region should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"Fatal error: Amazon Bedrock bearer token auth requires \
|
||||
`model_providers.amazon-bedrock.aws.region`, `AWS_REGION`, or `AWS_DEFAULT_REGION`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_mantle_sigv4_strips_headers_not_preserved_by_mantle() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"session_id",
|
||||
HeaderValue::from_static("019dae79-15c3-70c3-8736-3219b8602b37"),
|
||||
);
|
||||
headers.insert(
|
||||
"thread_id",
|
||||
HeaderValue::from_static("019dae79-15c3-70c3-8736-3219b8602b37"),
|
||||
);
|
||||
headers.insert(
|
||||
"future_identity_header",
|
||||
HeaderValue::from_static("019dae79-15c3-70c3-8736-3219b8602b37"),
|
||||
);
|
||||
headers.insert(
|
||||
"x-client-request-id",
|
||||
HeaderValue::from_static("request-id"),
|
||||
);
|
||||
|
||||
remove_headers_not_preserved_by_bedrock_mantle(&mut headers);
|
||||
|
||||
assert!(!headers.contains_key("session_id"));
|
||||
assert!(!headers.contains_key("thread_id"));
|
||||
assert!(!headers.contains_key("future_identity_header"));
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("x-client-request-id")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("request-id")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
use std::io::IsTerminal;
|
||||
use std::ops::Deref;
|
||||
use std::process::Stdio;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_model_provider_info::AwsAuthRefreshConfig;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
/// Shares the configured AWS reauthentication command across Bedrock providers.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AwsAuthRecovery {
|
||||
config: AwsAuthRefreshConfig,
|
||||
refresh_lock: Semaphore,
|
||||
generation: AtomicU64,
|
||||
}
|
||||
|
||||
impl AwsAuthRecovery {
|
||||
pub(crate) fn new(config: AwsAuthRefreshConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
refresh_lock: Semaphore::new(/*permits*/ 1),
|
||||
generation: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn refresh(&self) -> std::io::Result<()> {
|
||||
if self.config.command != "aws" {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"AWS auth refresh command must be `aws`",
|
||||
));
|
||||
}
|
||||
|
||||
let generation = self.generation.load(Ordering::Acquire);
|
||||
let _refresh_lock = self
|
||||
.refresh_lock
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(std::io::Error::other)?;
|
||||
if self.generation.load(Ordering::Acquire) != generation {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let interactive = std::io::stdin().is_terminal();
|
||||
let mut command = if interactive {
|
||||
Command::new(&self.config.command)
|
||||
} else {
|
||||
Command::from(codex_utils_process::background_command(
|
||||
&self.config.command,
|
||||
))
|
||||
};
|
||||
command
|
||||
.args(self.config.args.iter().map(Deref::deref))
|
||||
.stdin(if interactive {
|
||||
Stdio::inherit()
|
||||
} else {
|
||||
Stdio::null()
|
||||
})
|
||||
// Keep interactive prompts visible without corrupting app-server's JSON-RPC stdout.
|
||||
.stdout(std::io::stderr())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true);
|
||||
|
||||
let status = tokio::time::timeout(self.config.timeout(), command.status())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
std::io::Error::other(format!(
|
||||
"AWS auth refresh command timed out after {} ms",
|
||||
self.config.timeout_ms
|
||||
))
|
||||
})?
|
||||
.map_err(|error| {
|
||||
std::io::Error::other(format!(
|
||||
"failed to run AWS auth refresh command `{}`: {error}",
|
||||
self.config.command
|
||||
))
|
||||
})?;
|
||||
|
||||
if status.success() {
|
||||
self.generation.fetch_add(1, Ordering::Release);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other(format!(
|
||||
"AWS auth refresh command exited with {status}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,443 +0,0 @@
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_5_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID;
|
||||
use codex_models_manager::bundled_models_response;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::openai_models::ModelServiceTier;
|
||||
use codex_protocol::openai_models::ModelVisibility;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_protocol::openai_models::WebSearchToolType;
|
||||
|
||||
use super::BedrockEndpoint;
|
||||
|
||||
const GPT_5_BEDROCK_CONTEXT_WINDOW: i64 = 272_000;
|
||||
const GPT_5_6_SOL_OPENAI_MODEL_ID: &str = "gpt-5.6-sol";
|
||||
const GPT_5_6_TERRA_OPENAI_MODEL_ID: &str = "gpt-5.6-terra";
|
||||
const GPT_5_6_LUNA_OPENAI_MODEL_ID: &str = "gpt-5.6-luna";
|
||||
const GPT_6_1_SOL_OPENAI_MODEL_ID: &str = "gpt-6.1-sol";
|
||||
const GPT_6_1_TERRA_OPENAI_MODEL_ID: &str = "gpt-6.1-terra";
|
||||
const GPT_6_SOL_OPENAI_MODEL_ID: &str = "gpt-6-sol";
|
||||
const GPT_6_LUNA_OPENAI_MODEL_ID: &str = "gpt-6-luna";
|
||||
const GPT_6_ASTRA_OPENAI_MODEL_ID: &str = "gpt-6-astra";
|
||||
const GPT_5_5_OPENAI_MODEL_ID: &str = "gpt-5.5";
|
||||
|
||||
pub(crate) fn static_model_catalog() -> ModelsResponse {
|
||||
let catalog = ModelsResponse {
|
||||
models: vec![
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_6_1_SOL_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID,
|
||||
"GPT-6.1 Sol",
|
||||
/*priority*/ 0,
|
||||
),
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_6_ASTRA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID,
|
||||
"GPT-6-Astra",
|
||||
/*priority*/ 1,
|
||||
),
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_6_1_TERRA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID,
|
||||
"GPT-6.1 Terra",
|
||||
/*priority*/ 2,
|
||||
),
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_6_SOL_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID,
|
||||
"GPT-6 Sol",
|
||||
/*priority*/ 3,
|
||||
),
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_6_LUNA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID,
|
||||
"GPT-6 Luna",
|
||||
/*priority*/ 4,
|
||||
),
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_5_6_SOL_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID,
|
||||
"GPT-5.6 Sol",
|
||||
/*priority*/ 5,
|
||||
),
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_5_6_TERRA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID,
|
||||
"GPT-5.6 Terra",
|
||||
/*priority*/ 6,
|
||||
),
|
||||
bedrock_model(
|
||||
bundled_openai_model(GPT_5_6_LUNA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
"GPT-5.6 Luna",
|
||||
/*priority*/ 7,
|
||||
),
|
||||
gpt_5_bedrock_model(
|
||||
GPT_5_5_OPENAI_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_5_MODEL_ID,
|
||||
"GPT-5.5",
|
||||
/*priority*/ 8,
|
||||
),
|
||||
],
|
||||
};
|
||||
normalize_bundled_bedrock_catalog(catalog, BedrockEndpoint::Mantle)
|
||||
}
|
||||
|
||||
pub(super) fn static_gov_model_catalog() -> ModelsResponse {
|
||||
let mut catalog = static_model_catalog();
|
||||
catalog.models.retain(|model| {
|
||||
matches!(
|
||||
model.slug.as_str(),
|
||||
AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID | AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID
|
||||
)
|
||||
});
|
||||
catalog
|
||||
}
|
||||
|
||||
pub(super) fn normalize_bundled_bedrock_catalog(
|
||||
mut catalog: ModelsResponse,
|
||||
endpoint: BedrockEndpoint,
|
||||
) -> ModelsResponse {
|
||||
for model in &mut catalog.models {
|
||||
// Bundled defaults must not inherit OpenAI-only tiers or opt into a premium tier.
|
||||
model.additional_speed_tiers.clear();
|
||||
model.service_tiers.clear();
|
||||
if matches!(
|
||||
(endpoint, model.slug.as_str()),
|
||||
(
|
||||
BedrockEndpoint::Mantle,
|
||||
AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID | AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID
|
||||
) | (
|
||||
BedrockEndpoint::Runtime,
|
||||
"global.openai.gpt-6-astra"
|
||||
| "us.openai.gpt-6-astra"
|
||||
| "global.openai.gpt-6.1-sol"
|
||||
| "us.openai.gpt-6.1-sol"
|
||||
)
|
||||
) {
|
||||
model.service_tiers.push(ModelServiceTier {
|
||||
id: "ultrafast".to_string(),
|
||||
name: "Ultrafast".to_string(),
|
||||
description: "The fastest available responses for latency-sensitive work."
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
model.default_service_tier = None;
|
||||
}
|
||||
normalize_bedrock_catalog(catalog)
|
||||
}
|
||||
|
||||
pub(super) fn normalize_bedrock_catalog(mut catalog: ModelsResponse) -> ModelsResponse {
|
||||
// Custom catalogs own their tier definitions; only normalize wire compatibility here.
|
||||
for model in &mut catalog.models {
|
||||
// Bedrock rejects the `search_content_types` field used by multimodal search.
|
||||
model.web_search_tool_type = WebSearchToolType::Text;
|
||||
}
|
||||
catalog
|
||||
}
|
||||
|
||||
fn gpt_5_bedrock_model(
|
||||
openai_slug: &str,
|
||||
bedrock_slug: &str,
|
||||
display_name: &str,
|
||||
priority: i32,
|
||||
) -> ModelInfo {
|
||||
let mut model = bundled_openai_model(openai_slug);
|
||||
model.slug = bedrock_slug.to_string();
|
||||
model.display_name = display_name.to_string();
|
||||
model.priority = priority;
|
||||
model.context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW);
|
||||
model.max_context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW);
|
||||
model.visibility = ModelVisibility::List;
|
||||
model.availability_nux = None;
|
||||
model.upgrade = None;
|
||||
model
|
||||
}
|
||||
|
||||
fn bedrock_model(
|
||||
mut model: ModelInfo,
|
||||
bedrock_slug: &str,
|
||||
display_name: &str,
|
||||
priority: i32,
|
||||
) -> ModelInfo {
|
||||
model.slug = bedrock_slug.to_string();
|
||||
model.display_name = display_name.to_string();
|
||||
model.priority = priority;
|
||||
model.visibility = ModelVisibility::List;
|
||||
model.availability_nux = None;
|
||||
model.upgrade = None;
|
||||
model.use_responses_lite = false;
|
||||
model.tool_mode = None;
|
||||
model
|
||||
}
|
||||
|
||||
fn bundled_openai_model(slug: &str) -> ModelInfo {
|
||||
bundled_models_response()
|
||||
.unwrap_or_else(|err| panic!("bundled models.json should parse: {err}"))
|
||||
.models
|
||||
.into_iter()
|
||||
.find(|model| model.slug == slug)
|
||||
.unwrap_or_else(|| panic!("bundled models.json should include {slug}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn catalog_uses_mantle_model_ids_in_priority_order() {
|
||||
let catalog = static_model_catalog();
|
||||
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| model.slug.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_5_MODEL_ID,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpt_5_bedrock_models_use_bedrock_context_window() {
|
||||
let catalog = static_model_catalog();
|
||||
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| (
|
||||
model.slug.as_str(),
|
||||
model.context_window,
|
||||
model.max_context_window,
|
||||
model.web_search_tool_type,
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID,
|
||||
Some(500_000),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(872_000),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_5_5_MODEL_ID,
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
Some(GPT_5_BEDROCK_CONTEXT_WINDOW),
|
||||
WebSearchToolType::Text,
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_bedrock_catalogs_normalize_unsupported_model_capabilities() {
|
||||
let models = [
|
||||
Some(MultiAgentVersion::V2),
|
||||
Some(MultiAgentVersion::V1),
|
||||
Some(MultiAgentVersion::Disabled),
|
||||
None,
|
||||
]
|
||||
.into_iter()
|
||||
.map(|version| {
|
||||
let mut model = bundled_openai_model(GPT_5_5_OPENAI_MODEL_ID);
|
||||
model.multi_agent_version = version;
|
||||
model
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut expected = models.clone();
|
||||
for model in &mut expected {
|
||||
model.web_search_tool_type = WebSearchToolType::Text;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
normalize_bedrock_catalog(ModelsResponse { models }),
|
||||
ModelsResponse { models: expected }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpt_5_bedrock_models_do_not_include_availability_nux_or_upgrade() {
|
||||
let catalog = static_model_catalog();
|
||||
|
||||
for model in catalog.models {
|
||||
assert_eq!((model.availability_nux, model.upgrade), (None, None));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpt_5_bedrock_models_are_visible() {
|
||||
let catalog = static_model_catalog();
|
||||
|
||||
for model in catalog.models {
|
||||
assert_eq!(model.visibility, ModelVisibility::List);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_models_preserve_source_metadata_with_supported_capabilities() {
|
||||
let catalog = static_model_catalog();
|
||||
|
||||
for (mut expected, slug, display_name, priority) in [
|
||||
(
|
||||
bundled_openai_model(GPT_6_1_SOL_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID,
|
||||
"GPT-6.1 Sol",
|
||||
0,
|
||||
),
|
||||
(
|
||||
bundled_openai_model(GPT_6_1_TERRA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID,
|
||||
"GPT-6.1 Terra",
|
||||
2,
|
||||
),
|
||||
(
|
||||
bundled_openai_model(GPT_6_SOL_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID,
|
||||
"GPT-6 Sol",
|
||||
3,
|
||||
),
|
||||
(
|
||||
bundled_openai_model(GPT_6_LUNA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID,
|
||||
"GPT-6 Luna",
|
||||
4,
|
||||
),
|
||||
(
|
||||
bundled_openai_model(GPT_5_6_SOL_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID,
|
||||
"GPT-5.6 Sol",
|
||||
5,
|
||||
),
|
||||
(
|
||||
bundled_openai_model(GPT_5_6_TERRA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID,
|
||||
"GPT-5.6 Terra",
|
||||
6,
|
||||
),
|
||||
(
|
||||
bundled_openai_model(GPT_5_6_LUNA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
"GPT-5.6 Luna",
|
||||
7,
|
||||
),
|
||||
(
|
||||
bundled_openai_model(GPT_6_ASTRA_OPENAI_MODEL_ID),
|
||||
AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID,
|
||||
"GPT-6-Astra",
|
||||
1,
|
||||
),
|
||||
] {
|
||||
expected.slug = slug.to_string();
|
||||
expected.display_name = display_name.to_string();
|
||||
expected.priority = priority;
|
||||
expected.visibility = ModelVisibility::List;
|
||||
expected.availability_nux = None;
|
||||
expected.upgrade = None;
|
||||
expected.use_responses_lite = false;
|
||||
expected.tool_mode = None;
|
||||
expected.additional_speed_tiers.clear();
|
||||
expected.service_tiers = if matches!(
|
||||
slug,
|
||||
AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID | AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID
|
||||
) {
|
||||
vec![ModelServiceTier {
|
||||
id: "ultrafast".to_string(),
|
||||
name: "Ultrafast".to_string(),
|
||||
description: "The fastest available responses for latency-sensitive work."
|
||||
.to_string(),
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
expected.default_service_tier = None;
|
||||
expected.web_search_tool_type = WebSearchToolType::Text;
|
||||
|
||||
assert_eq!(
|
||||
catalog.models.iter().find(|model| model.slug == slug),
|
||||
Some(&expected)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedrock_models_do_not_enable_priority_or_explicit_default_tiers() {
|
||||
let catalog = static_model_catalog();
|
||||
|
||||
for model in catalog.models {
|
||||
assert_eq!(model.additional_speed_tiers, Vec::<String>::new());
|
||||
assert_eq!(model.default_service_tier, None);
|
||||
assert_eq!(
|
||||
model.service_tier_for_request(Some("priority".to_string())),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
model
|
||||
.service_tier_for_request(Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string())),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
//! Caches Bedrock signing credentials and provides an exclusive refresh guard.
|
||||
//! The caller holds the guard across login and export to coalesce auth recovery.
|
||||
//! Exported secrets remain in memory; command output is bounded and never logged.
|
||||
|
||||
use std::io;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_aws_auth::AwsAccessKeys;
|
||||
use codex_aws_auth::AwsCredentialsProvider;
|
||||
use codex_model_provider_info::AwsCredentialExportConfig;
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::MutexGuard;
|
||||
|
||||
const DEFAULT_CREDENTIAL_LIFETIME: Duration = Duration::from_secs(60 * 60);
|
||||
const CREDENTIAL_REFRESH_WINDOW: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AwsCredentialExport {
|
||||
config: AwsCredentialExportConfig,
|
||||
cached: Mutex<Option<CachedCredentials>>,
|
||||
recovery_generation: AtomicU64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CachedCredentials {
|
||||
access_keys: AwsAccessKeys,
|
||||
refresh_at: SystemTime,
|
||||
}
|
||||
|
||||
/// Keeps cached credentials invalidated while the caller reauthenticates and exports.
|
||||
pub(super) struct CredentialExportRefresh<'a> {
|
||||
exporter: &'a AwsCredentialExport,
|
||||
cached: MutexGuard<'a, Option<CachedCredentials>>,
|
||||
}
|
||||
|
||||
impl CredentialExportRefresh<'_> {
|
||||
pub(super) async fn refresh(mut self) -> io::Result<()> {
|
||||
*self.cached = Some(self.exporter.export_credentials().await?);
|
||||
self.exporter
|
||||
.recovery_generation
|
||||
.fetch_add(1, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum CredentialOutput {
|
||||
Sts {
|
||||
#[serde(rename = "Credentials")]
|
||||
credentials: ExportedCredentials,
|
||||
},
|
||||
Process(ExportedCredentials),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct ExportedCredentials {
|
||||
access_key_id: String,
|
||||
secret_access_key: String,
|
||||
session_token: Option<String>,
|
||||
expiration: Option<String>,
|
||||
}
|
||||
|
||||
impl CachedCredentials {
|
||||
fn from_output(output: &[u8], now: SystemTime) -> io::Result<Self> {
|
||||
let output: CredentialOutput = serde_json::from_slice(output).map_err(|_| {
|
||||
// Serde's detailed errors may quote credential values.
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"AWS credential export returned invalid credentials JSON",
|
||||
)
|
||||
})?;
|
||||
let credentials = match output {
|
||||
CredentialOutput::Sts { credentials } | CredentialOutput::Process(credentials) => {
|
||||
credentials
|
||||
}
|
||||
};
|
||||
if credentials.access_key_id.trim().is_empty()
|
||||
|| credentials.secret_access_key.trim().is_empty()
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"AWS credential export returned empty access keys",
|
||||
));
|
||||
}
|
||||
let refresh_at = if let Some(expiration) = credentials.expiration {
|
||||
let expiration = DateTime::parse_from_rfc3339(&expiration).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"AWS credential export Expiration must be an RFC 3339 timestamp",
|
||||
)
|
||||
})?;
|
||||
let lifetime = expiration
|
||||
.signed_duration_since(DateTime::<Utc>::from(now))
|
||||
.to_std()
|
||||
.ok()
|
||||
.filter(|lifetime| !lifetime.is_zero())
|
||||
.ok_or_else(|| {
|
||||
io::Error::other("AWS credential export returned expired credentials")
|
||||
})?;
|
||||
now.checked_add(lifetime.saturating_sub(CREDENTIAL_REFRESH_WINDOW))
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"AWS credential export Expiration is out of range",
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
now + DEFAULT_CREDENTIAL_LIFETIME
|
||||
};
|
||||
Ok(Self {
|
||||
access_keys: AwsAccessKeys {
|
||||
access_key_id: credentials.access_key_id,
|
||||
secret_access_key: credentials.secret_access_key,
|
||||
session_token: credentials.session_token,
|
||||
},
|
||||
refresh_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AwsCredentialExport {
|
||||
pub(crate) fn new(config: AwsCredentialExportConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
cached: Mutex::new(None),
|
||||
recovery_generation: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns None when another overlapping recovery has already completed.
|
||||
/// Dropping the guard before refresh succeeds leaves the cache empty.
|
||||
pub(super) async fn begin_refresh(&self) -> Option<CredentialExportRefresh<'_>> {
|
||||
let generation = self.recovery_generation.load(Ordering::Acquire);
|
||||
let mut cached = self.cached.lock().await;
|
||||
if self.recovery_generation.load(Ordering::Acquire) != generation {
|
||||
return None;
|
||||
}
|
||||
*cached = None;
|
||||
Some(CredentialExportRefresh {
|
||||
exporter: self,
|
||||
cached,
|
||||
})
|
||||
}
|
||||
|
||||
async fn export_credentials(&self) -> io::Result<CachedCredentials> {
|
||||
let output = codex_login::run_credential_export(&self.config, "AWS").await?;
|
||||
CachedCredentials::from_output(&output, SystemTime::now())
|
||||
}
|
||||
}
|
||||
|
||||
impl AwsCredentialsProvider for AwsCredentialExport {
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "cache misses serialize command execution to avoid duplicate credential exports"
|
||||
)]
|
||||
async fn credentials(&self) -> std::io::Result<AwsAccessKeys> {
|
||||
let mut cached = self.cached.lock().await;
|
||||
if let Some(credentials) = cached.as_ref()
|
||||
&& SystemTime::now() < credentials.refresh_at
|
||||
{
|
||||
return Ok(credentials.access_keys.clone());
|
||||
}
|
||||
let credentials = self.export_credentials().await?;
|
||||
let access_keys = credentials.access_keys.clone();
|
||||
*cached = Some(credentials);
|
||||
Ok(access_keys)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "credential_export_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,378 +0,0 @@
|
||||
use std::future::Future;
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::Arc;
|
||||
use std::task::Context;
|
||||
use std::task::Waker;
|
||||
|
||||
use codex_model_provider_info::AwsAuthRefreshConfig;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::provider::ModelProvider;
|
||||
use crate::provider::ProviderUnauthorizedRecovery;
|
||||
|
||||
use super::super::AmazonBedrockModelProvider;
|
||||
use super::super::AwsAuthRecovery;
|
||||
use super::*;
|
||||
|
||||
const MAX_CREDENTIAL_OUTPUT_BYTES: usize = 64 * 1024;
|
||||
const SECRET: &str = "credential-export-secret";
|
||||
const VALID_OUTPUT: &[u8] = br#"{"AccessKeyId":"exported","SecretAccessKey":"credential-export-secret","SessionToken":"credential-export-secret"}"#;
|
||||
|
||||
fn exporter_fixture(
|
||||
output: &[u8],
|
||||
mode: &str,
|
||||
) -> io::Result<(tempfile::TempDir, AwsCredentialExport)> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let output_path = directory.path().join("output.json");
|
||||
std::fs::write(&output_path, output)?;
|
||||
|
||||
#[cfg(unix)]
|
||||
let (command, mut args) = {
|
||||
let script = directory.path().join("export.sh");
|
||||
std::fs::write(
|
||||
&script,
|
||||
r#"printf 'invoked\n' >> "$1"
|
||||
printf '%s\n' "$4" >&2
|
||||
cat "$2"
|
||||
case "$3" in
|
||||
fail) exit 7 ;;
|
||||
wait) while :; do :; done ;;
|
||||
esac
|
||||
"#,
|
||||
)?;
|
||||
(
|
||||
"sh".to_string(),
|
||||
vec![script.to_string_lossy().into_owned()],
|
||||
)
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let (command, mut args) = {
|
||||
let script = directory.path().join("export.cmd");
|
||||
std::fs::write(
|
||||
&script,
|
||||
"@echo off\r\n>> \"%~1\" echo invoked\r\n>&2 echo %~4\r\ntype \"%~2\"\r\nif \"%~3\"==\"fail\" exit /b 7\r\nif \"%~3\"==\"wait\" goto wait\r\nexit /b 0\r\n:wait\r\ngoto wait\r\n",
|
||||
)?;
|
||||
(
|
||||
"cmd.exe".to_string(),
|
||||
vec![
|
||||
"/D".to_string(),
|
||||
"/Q".to_string(),
|
||||
"/C".to_string(),
|
||||
script.to_string_lossy().into_owned(),
|
||||
],
|
||||
)
|
||||
};
|
||||
args.extend([
|
||||
directory
|
||||
.path()
|
||||
.join("invocations")
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
output_path.to_string_lossy().into_owned(),
|
||||
mode.to_string(),
|
||||
SECRET.to_string(),
|
||||
]);
|
||||
Ok((
|
||||
directory,
|
||||
AwsCredentialExport::new(AwsCredentialExportConfig {
|
||||
command,
|
||||
args: args.into_iter().map(Into::into).collect(),
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("non-zero timeout"),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_output_formats_expiration_and_sanitized_errors() {
|
||||
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
|
||||
for (optional_fields, refresh_after) in [
|
||||
(json!({}), 3_600),
|
||||
(json!({"SessionToken": null, "Expiration": null}), 3_600),
|
||||
(
|
||||
json!({"SessionToken": SECRET, "Expiration": "2023-11-14T23:13:20+00:00"}),
|
||||
3_300,
|
||||
),
|
||||
(
|
||||
json!({"SessionToken": SECRET, "Expiration": "2023-11-14T22:18:20Z"}),
|
||||
0,
|
||||
),
|
||||
(json!({"Expiration": "2023-11-14T22:15:20Z"}), 0),
|
||||
] {
|
||||
let mut credentials = json!({"AccessKeyId": "exported", "SecretAccessKey": SECRET});
|
||||
credentials
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(optional_fields.as_object().unwrap().clone());
|
||||
let mut process_output = credentials.clone();
|
||||
process_output["Version"] = json!(1);
|
||||
for output in [
|
||||
process_output,
|
||||
json!({"Credentials": credentials, "AssumedRoleUser": {"Arn": "test-role"}}),
|
||||
] {
|
||||
let cached = CachedCredentials::from_output(output.to_string().as_bytes(), now)
|
||||
.expect("valid credentials should parse");
|
||||
assert_eq!(
|
||||
(cached.access_keys, cached.refresh_at),
|
||||
(
|
||||
AwsAccessKeys {
|
||||
access_key_id: "exported".to_string(),
|
||||
secret_access_key: SECRET.to_string(),
|
||||
session_token: optional_fields
|
||||
.get("SessionToken")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_string),
|
||||
},
|
||||
now + Duration::from_secs(refresh_after)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut invalid_outputs = vec![(
|
||||
format!("{{\"SecretAccessKey\":\"{SECRET}\""),
|
||||
io::ErrorKind::InvalidData,
|
||||
)];
|
||||
for (field, value) in [
|
||||
("AccessKeyId", None),
|
||||
("SecretAccessKey", None),
|
||||
("AccessKeyId", Some(json!(" "))),
|
||||
("SecretAccessKey", Some(json!(" "))),
|
||||
("AccessKeyId", Some(json!([SECRET]))),
|
||||
("SecretAccessKey", Some(json!([SECRET]))),
|
||||
("SessionToken", Some(json!([SECRET]))),
|
||||
("Expiration", Some(json!([SECRET]))),
|
||||
("Expiration", Some(json!(SECRET))),
|
||||
] {
|
||||
let mut credentials: serde_json::Value = serde_json::from_slice(VALID_OUTPUT).unwrap();
|
||||
match value {
|
||||
Some(value) => {
|
||||
credentials[field] = value;
|
||||
}
|
||||
None => {
|
||||
credentials.as_object_mut().unwrap().remove(field);
|
||||
}
|
||||
}
|
||||
invalid_outputs.extend(
|
||||
[
|
||||
credentials.to_string(),
|
||||
json!({"Credentials": credentials}).to_string(),
|
||||
]
|
||||
.map(|output| (output, io::ErrorKind::InvalidData)),
|
||||
);
|
||||
}
|
||||
for expiration in ["2023-11-14T22:13:20Z", "2023-11-14T22:00:00Z"] {
|
||||
let credentials =
|
||||
json!({"AccessKeyId": "exported", "SecretAccessKey": SECRET, "Expiration": expiration});
|
||||
invalid_outputs.extend(
|
||||
[
|
||||
credentials.to_string(),
|
||||
json!({"Credentials": credentials}).to_string(),
|
||||
]
|
||||
.map(|output| (output, io::ErrorKind::Other)),
|
||||
);
|
||||
}
|
||||
for (output, expected_kind) in invalid_outputs {
|
||||
let error = CachedCredentials::from_output(output.as_bytes(), now)
|
||||
.expect_err("invalid credentials should be rejected");
|
||||
assert_eq!(error.kind(), expected_kind);
|
||||
assert!(!error.to_string().contains(SECRET));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_export_process_errors_are_bounded_and_sanitized() -> io::Result<()> {
|
||||
let oversized = format!("{SECRET}{}", "x".repeat(MAX_CREDENTIAL_OUTPUT_BYTES));
|
||||
for (mode, output, timeout_ms, expected_kind) in [
|
||||
("missing", VALID_OUTPUT, 5_000, io::ErrorKind::NotFound),
|
||||
("relative", VALID_OUTPUT, 5_000, io::ErrorKind::InvalidInput),
|
||||
(
|
||||
"normalized-relative",
|
||||
VALID_OUTPUT,
|
||||
5_000,
|
||||
io::ErrorKind::InvalidInput,
|
||||
),
|
||||
("fail", VALID_OUTPUT, 5_000, io::ErrorKind::Other),
|
||||
("wait", VALID_OUTPUT, 100, io::ErrorKind::TimedOut),
|
||||
(
|
||||
"wait",
|
||||
oversized.as_bytes(),
|
||||
5_000,
|
||||
io::ErrorKind::InvalidData,
|
||||
),
|
||||
] {
|
||||
let (directory, mut exporter) = exporter_fixture(output, mode)?;
|
||||
exporter.config.timeout_ms = NonZeroU64::new(timeout_ms).expect("non-zero timeout");
|
||||
if mode == "missing" {
|
||||
exporter.config.command = directory
|
||||
.path()
|
||||
.join("missing")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
} else if mode == "relative" {
|
||||
exporter.config.command = std::path::Path::new(".")
|
||||
.join("export-credentials")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
} else if mode == "normalized-relative" {
|
||||
exporter.config.command = std::path::Path::new("scripts")
|
||||
.join(".")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
}
|
||||
let error = exporter
|
||||
.credentials()
|
||||
.await
|
||||
.expect_err("export should fail");
|
||||
assert_eq!(error.kind(), expected_kind);
|
||||
assert!(!error.to_string().contains(SECRET));
|
||||
assert!(!format!("{exporter:?}").contains(SECRET));
|
||||
assert!(exporter.cached.lock().await.is_none());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_export_reuses_cache_and_coalesces_refreshes() -> io::Result<()> {
|
||||
let mut output = VALID_OUTPUT.to_vec();
|
||||
output.resize(MAX_CREDENTIAL_OUTPUT_BYTES, b' ');
|
||||
let (directory, exporter) = exporter_fixture(&output, "success")?;
|
||||
let original = AwsAccessKeys {
|
||||
access_key_id: "exported".to_string(),
|
||||
secret_access_key: SECRET.to_string(),
|
||||
session_token: Some(SECRET.to_string()),
|
||||
};
|
||||
let (first, second) = tokio::join!(exporter.credentials(), exporter.credentials());
|
||||
assert_eq!([first?, second?], [original.clone(), original.clone()]);
|
||||
let rotated = json!({"AccessKeyId": "rotated", "SecretAccessKey": SECRET});
|
||||
std::fs::write(directory.path().join("output.json"), rotated.to_string())?;
|
||||
assert_eq!(exporter.credentials().await?, original);
|
||||
|
||||
exporter
|
||||
.cached
|
||||
.lock()
|
||||
.await
|
||||
.as_mut()
|
||||
.expect("populated cache")
|
||||
.refresh_at = SystemTime::UNIX_EPOCH;
|
||||
let rotated = AwsAccessKeys {
|
||||
access_key_id: "rotated".to_string(),
|
||||
secret_access_key: SECRET.to_string(),
|
||||
session_token: None,
|
||||
};
|
||||
assert_eq!(exporter.credentials().await?, rotated);
|
||||
|
||||
let mut provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: Some(exporter.config.clone()),
|
||||
auth_refresh: None,
|
||||
})),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
let exporter = Arc::new(exporter);
|
||||
provider.credential_export = Some(exporter.clone());
|
||||
let controller = codex_http_client::NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
provider.http_client_factory = provider
|
||||
.http_client_factory
|
||||
.clone()
|
||||
.with_network_policy(policy.clone());
|
||||
controller.publish(
|
||||
policy.revision(),
|
||||
codex_http_client::DestinationPolicy::Restricted {
|
||||
allowed_hosts: Default::default(),
|
||||
},
|
||||
);
|
||||
let denied = provider
|
||||
.recover_from_unauthorized()
|
||||
.await
|
||||
.expect_err("restricted recovery must not launch the exporter");
|
||||
assert_eq!(denied.retry_delay(/*retry_count*/ 1), None);
|
||||
assert_eq!(
|
||||
denied.to_string(),
|
||||
"Fatal error: this SDK transport is disabled by application network restrictions"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(directory.path().join("invocations"))?
|
||||
.lines()
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["invoked", "invoked"]
|
||||
);
|
||||
controller.publish(
|
||||
policy.revision(),
|
||||
codex_http_client::DestinationPolicy::Unrestricted,
|
||||
);
|
||||
{
|
||||
let first = provider.recover_from_unauthorized();
|
||||
let second = provider.recover_from_unauthorized();
|
||||
tokio::pin!(first, second);
|
||||
{
|
||||
// Both callers must observe the same generation before either can export.
|
||||
let _cached = exporter.cached.lock().await;
|
||||
let mut context = Context::from_waker(Waker::noop());
|
||||
assert!(first.as_mut().poll(&mut context).is_pending());
|
||||
assert!(second.as_mut().poll(&mut context).is_pending());
|
||||
}
|
||||
let (first, second) = tokio::join!(first, second);
|
||||
assert_eq!(
|
||||
[
|
||||
first.expect("first recovery"),
|
||||
second.expect("second recovery")
|
||||
],
|
||||
[ProviderUnauthorizedRecovery::Recovered; 2],
|
||||
);
|
||||
}
|
||||
assert_eq!(exporter.credentials().await?, rotated);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(directory.path().join("invocations"))?
|
||||
.lines()
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["invoked", "invoked", "invoked"]
|
||||
);
|
||||
assert!(!format!("{exporter:?}").contains(SECRET));
|
||||
|
||||
provider.auth_recovery = Some(Arc::new(AwsAuthRecovery::new(AwsAuthRefreshConfig {
|
||||
command: "not-aws".to_string(),
|
||||
args: Vec::new(),
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("non-zero timeout"),
|
||||
})));
|
||||
let credentials = exporter.credentials();
|
||||
let refresh = provider.recover_from_unauthorized();
|
||||
tokio::pin!(credentials, refresh);
|
||||
{
|
||||
// A normal export completing must not make a queued login recovery look completed.
|
||||
let mut cached = exporter.cached.lock().await;
|
||||
cached.as_mut().expect("populated cache").refresh_at = SystemTime::UNIX_EPOCH;
|
||||
let mut context = Context::from_waker(Waker::noop());
|
||||
assert!(credentials.as_mut().poll(&mut context).is_pending());
|
||||
assert!(refresh.as_mut().poll(&mut context).is_pending());
|
||||
}
|
||||
let (credentials, refresh) = tokio::join!(credentials, refresh);
|
||||
assert_eq!(credentials?, rotated);
|
||||
assert_eq!(
|
||||
refresh
|
||||
.expect_err("queued login recovery must still run")
|
||||
.retry_delay(/*retry_count*/ 1),
|
||||
None
|
||||
);
|
||||
assert!(exporter.cached.lock().await.is_none());
|
||||
|
||||
// Cancellation also leaves the invalidated cache empty and releases the guard.
|
||||
exporter.credentials().await?;
|
||||
let refresh = exporter.begin_refresh().await.expect("new recovery");
|
||||
let credentials = exporter.credentials();
|
||||
tokio::pin!(credentials);
|
||||
assert!(
|
||||
credentials
|
||||
.as_mut()
|
||||
.poll(&mut Context::from_waker(Waker::noop()))
|
||||
.is_pending()
|
||||
);
|
||||
drop(refresh);
|
||||
assert_eq!(credentials.await?, rotated);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
use codex_api::ApiError;
|
||||
use codex_api::TransportError;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use http::StatusCode;
|
||||
|
||||
pub(super) const CREDENTIAL_EXPORT_CONFIG_ERROR_PREFIX: &str =
|
||||
"AWS credential export configuration error:";
|
||||
|
||||
pub(super) const BEDROCK_EXPIRED_SIGNATURE_MESSAGE: &str = concat!(
|
||||
"Amazon Bedrock rejected the request because its AWS signature has expired. ",
|
||||
"Refresh your AWS credentials and retry. If `AWS_BEARER_TOKEN_BEDROCK` is set, ",
|
||||
"update or unset it, then restart Codex",
|
||||
);
|
||||
|
||||
pub(super) fn map_api_error(error: ApiError) -> CodexErr {
|
||||
if let ApiError::Transport(TransportError::Build(message)) = &error
|
||||
&& message.starts_with(CREDENTIAL_EXPORT_CONFIG_ERROR_PREFIX)
|
||||
{
|
||||
return CodexErr::InvalidRequest(message.clone());
|
||||
}
|
||||
let error = codex_api::map_api_error(error);
|
||||
if let CodexErrorDetails::UnexpectedStatus(response) = error.details()
|
||||
&& response.status == StatusCode::UNAUTHORIZED
|
||||
&& response.body.contains("Signature expired:")
|
||||
{
|
||||
let mut response = response.clone();
|
||||
response.user_message = Some(BEDROCK_EXPIRED_SIGNATURE_MESSAGE.to_string());
|
||||
let mapped_error = CodexErr::new(CodexErrorDetails::UnexpectedStatus(response));
|
||||
return match error.retry_after() {
|
||||
Some(retry_after) => mapped_error.with_retry_after(retry_after),
|
||||
None => mapped_error,
|
||||
};
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
pub(super) fn is_refreshable_auth_error(error: &TransportError) -> bool {
|
||||
match error {
|
||||
TransportError::Build(message) | TransportError::Network(message) => {
|
||||
message.starts_with("failed to load AWS credentials:")
|
||||
}
|
||||
TransportError::Http { status, .. } if *status == StatusCode::UNAUTHORIZED => true,
|
||||
TransportError::Http {
|
||||
status,
|
||||
body: Some(body),
|
||||
..
|
||||
} if *status == StatusCode::FORBIDDEN => {
|
||||
let body = body.to_ascii_lowercase();
|
||||
[
|
||||
"expiredtoken",
|
||||
"unrecognizedclientexception",
|
||||
"invalidclienttokenid",
|
||||
]
|
||||
.iter()
|
||||
.any(|error_code| body.contains(error_code))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
use std::num::NonZeroU64;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_api::ApiError;
|
||||
use codex_api::TransportError;
|
||||
use codex_http_client::RetryAfter;
|
||||
use codex_model_provider_info::AwsCredentialExportConfig;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::AmazonBedrockModelProvider;
|
||||
use super::error::BEDROCK_EXPIRED_SIGNATURE_MESSAGE;
|
||||
use super::error::CREDENTIAL_EXPORT_CONFIG_ERROR_PREFIX;
|
||||
use super::error::is_refreshable_auth_error;
|
||||
use super::error::map_api_error;
|
||||
use crate::ModelProvider;
|
||||
|
||||
const BEDROCK_RESPONSES_URL: &str = "https://bedrock-mantle.us-east-2.api.aws/openai/v1/responses";
|
||||
|
||||
fn http_error(status: StatusCode, body: &str) -> ApiError {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("x-request-id", HeaderValue::from_static("req-bedrock"));
|
||||
ApiError::Transport(TransportError::Http {
|
||||
retry_after: None,
|
||||
status,
|
||||
url: Some(BEDROCK_RESPONSES_URL.to_string()),
|
||||
headers: Some(headers),
|
||||
body: Some(body.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_signature_has_actionable_guidance() {
|
||||
let error = map_api_error(http_error(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Signature expired: 20260609T133205Z is now earlier than 20260614T062525Z",
|
||||
));
|
||||
|
||||
let CodexErrorDetails::UnexpectedStatus(response) = error.details() else {
|
||||
panic!("expected unexpected status error, got {error:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
response.user_message.as_deref(),
|
||||
Some(BEDROCK_EXPIRED_SIGNATURE_MESSAGE)
|
||||
);
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"{BEDROCK_EXPIRED_SIGNATURE_MESSAGE}, url: {BEDROCK_RESPONSES_URL}, request id: req-bedrock"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// Rewording an expired-signature error must not replace the server's original deadline.
|
||||
#[test]
|
||||
fn expired_signature_preserves_the_retry_deadline() {
|
||||
let advice = RetryAfter::from_delay(Duration::from_secs(10)).expect("retry advice");
|
||||
let error = map_api_error(ApiError::Transport(TransportError::Http {
|
||||
status: StatusCode::UNAUTHORIZED,
|
||||
url: None,
|
||||
headers: None,
|
||||
body: Some("Signature expired: old is now earlier than new".into()),
|
||||
retry_after: Some(advice),
|
||||
}));
|
||||
assert_eq!(error.retry_after(), Some(advice));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_unauthorized_errors_remain_generic() {
|
||||
let error = map_api_error(http_error(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"The security token included in the request is invalid",
|
||||
));
|
||||
|
||||
let CodexErrorDetails::UnexpectedStatus(response) = error.details() else {
|
||||
panic!("expected unexpected status error, got {error:?}");
|
||||
};
|
||||
assert_eq!(response.user_message, None);
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"unexpected status 401 Unauthorized: The security token included in the request is invalid, url: {BEDROCK_RESPONSES_URL}, request id: req-bedrock"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signature_errors_with_other_statuses_remain_generic() {
|
||||
let error = map_api_error(http_error(
|
||||
StatusCode::FORBIDDEN,
|
||||
"Signature expired: old is now earlier than new",
|
||||
));
|
||||
|
||||
let CodexErrorDetails::UnexpectedStatus(response) = error.details() else {
|
||||
panic!("expected unexpected status error, got {error:?}");
|
||||
};
|
||||
assert_eq!(response.user_message, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_only_refreshable_bedrock_auth_failures() {
|
||||
let cases = [
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Some("ExpiredTokenException"),
|
||||
true,
|
||||
),
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Some("AccessDeniedException"),
|
||||
true,
|
||||
),
|
||||
(StatusCode::UNAUTHORIZED, Some(""), true),
|
||||
(StatusCode::UNAUTHORIZED, None, true),
|
||||
(StatusCode::FORBIDDEN, Some("ExpiredTokenException"), true),
|
||||
(
|
||||
StatusCode::FORBIDDEN,
|
||||
Some("UnrecognizedClientException"),
|
||||
true,
|
||||
),
|
||||
(StatusCode::FORBIDDEN, Some("InvalidClientTokenId"), true),
|
||||
(StatusCode::FORBIDDEN, Some("AccessDeniedException"), false),
|
||||
(
|
||||
StatusCode::FORBIDDEN,
|
||||
Some("The security token included in the request is invalid"),
|
||||
false,
|
||||
),
|
||||
(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
Some("ExpiredTokenException"),
|
||||
false,
|
||||
),
|
||||
(StatusCode::BAD_REQUEST, Some("RequestExpired"), false),
|
||||
];
|
||||
|
||||
for (status, body, expected) in cases {
|
||||
let error = TransportError::Http {
|
||||
retry_after: None,
|
||||
status,
|
||||
url: Some(BEDROCK_RESPONSES_URL.to_string()),
|
||||
headers: None,
|
||||
body: body.map(str::to_string),
|
||||
};
|
||||
assert_eq!(
|
||||
is_refreshable_auth_error(&error),
|
||||
expected,
|
||||
"{status}: {body:?}"
|
||||
);
|
||||
}
|
||||
|
||||
for (error, expected) in [
|
||||
(
|
||||
TransportError::Build("failed to load AWS credentials: expired".to_string()),
|
||||
true,
|
||||
),
|
||||
(
|
||||
TransportError::Network("failed to load AWS credentials: unavailable".to_string()),
|
||||
true,
|
||||
),
|
||||
(
|
||||
TransportError::Build("request URL is not a valid URI".to_string()),
|
||||
false,
|
||||
),
|
||||
] {
|
||||
assert_eq!(is_refreshable_auth_error(&error), expected, "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_export_errors_distinguish_configuration_failures_from_retryable_auth() {
|
||||
let provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: Some(AwsCredentialExportConfig {
|
||||
command: "export-credentials".to_string(),
|
||||
args: Vec::new(),
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("non-zero timeout"),
|
||||
}),
|
||||
auth_refresh: None,
|
||||
})),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
for (error, recoverable, retryable) in [
|
||||
(
|
||||
ApiError::Transport(TransportError::Build(format!(
|
||||
"{CREDENTIAL_EXPORT_CONFIG_ERROR_PREFIX} invalid credentials JSON"
|
||||
))),
|
||||
false,
|
||||
false,
|
||||
),
|
||||
(
|
||||
ApiError::Transport(TransportError::Build(
|
||||
"failed to load AWS credentials: export command exited with status 1".to_string(),
|
||||
)),
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(
|
||||
http_error(StatusCode::UNAUTHORIZED, "ExpiredTokenException"),
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(
|
||||
http_error(StatusCode::FORBIDDEN, "ExpiredTokenException"),
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(
|
||||
http_error(StatusCode::FORBIDDEN, "AccessDeniedException"),
|
||||
false,
|
||||
true,
|
||||
),
|
||||
(
|
||||
ApiError::Transport(TransportError::Network("offline".to_string())),
|
||||
false,
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let ApiError::Transport(transport) = &error else {
|
||||
unreachable!("all test cases are transport errors");
|
||||
};
|
||||
assert_eq!(provider.is_recoverable_auth_error(transport), recoverable);
|
||||
assert_eq!(
|
||||
provider
|
||||
.map_api_error(error)
|
||||
.retry_delay(/*retry_count*/ 1)
|
||||
.is_some(),
|
||||
retryable
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
use codex_aws_auth::AwsAuthConfig;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
|
||||
use super::BedrockEndpoint;
|
||||
use super::auth::BedrockAuthSource;
|
||||
use super::auth::resolve_region;
|
||||
|
||||
const BEDROCK_MANTLE_SERVICE_NAME: &str = "bedrock-mantle";
|
||||
const BEDROCK_MANTLE_SUPPORTED_REGIONS: [&str; 12] = [
|
||||
"us-east-2",
|
||||
"us-east-1",
|
||||
"us-west-2",
|
||||
"ap-southeast-3",
|
||||
"ap-south-1",
|
||||
"ap-northeast-1",
|
||||
"eu-central-1",
|
||||
"eu-west-1",
|
||||
"eu-west-2",
|
||||
"eu-south-1",
|
||||
"eu-north-1",
|
||||
"sa-east-1",
|
||||
];
|
||||
const BEDROCK_GOV_CLOUD_SUPPORTED_REGIONS: [&str; 2] = ["us-gov-east-1", "us-gov-west-1"];
|
||||
|
||||
pub(super) fn aws_auth_config(aws: &ModelProviderAwsAuthInfo) -> AwsAuthConfig {
|
||||
AwsAuthConfig {
|
||||
profile: aws.profile.clone(),
|
||||
region: region_from_config(aws),
|
||||
service: BEDROCK_MANTLE_SERVICE_NAME.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn region_from_config(aws: &ModelProviderAwsAuthInfo) -> Option<String> {
|
||||
aws.region
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|region| !region.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
/// Returns whether Amazon Bedrock Mantle is available in `region`.
|
||||
pub fn is_supported_amazon_bedrock_region(region: &str) -> bool {
|
||||
BEDROCK_MANTLE_SUPPORTED_REGIONS.contains(®ion) || is_amazon_bedrock_gov_cloud_region(region)
|
||||
}
|
||||
|
||||
/// Returns whether `region` is a supported Amazon Bedrock GovCloud region.
|
||||
pub fn is_amazon_bedrock_gov_cloud_region(region: &str) -> bool {
|
||||
BEDROCK_GOV_CLOUD_SUPPORTED_REGIONS.contains(®ion)
|
||||
}
|
||||
|
||||
pub(super) fn base_url(region: &str) -> Result<String> {
|
||||
if is_supported_amazon_bedrock_region(region) {
|
||||
Ok(format!("https://bedrock-mantle.{region}.api.aws/openai/v1"))
|
||||
} else {
|
||||
Err(CodexErr::Fatal(format!(
|
||||
"Amazon Bedrock does not support region `{region}`"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn bedrock_mantle_runtime_base_url(
|
||||
source: BedrockAuthSource,
|
||||
managed_auth: Option<&CodexAuth>,
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
http_client_factory: &codex_http_client::HttpClientFactory,
|
||||
) -> Result<String> {
|
||||
let region = resolve_region(
|
||||
source,
|
||||
managed_auth,
|
||||
aws,
|
||||
BedrockEndpoint::Mantle,
|
||||
http_client_factory,
|
||||
)
|
||||
.await?;
|
||||
base_url(®ion)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base_url_uses_region_endpoint() {
|
||||
for (region, expected) in [
|
||||
(
|
||||
"ap-northeast-1",
|
||||
"https://bedrock-mantle.ap-northeast-1.api.aws/openai/v1",
|
||||
),
|
||||
(
|
||||
"us-gov-east-1",
|
||||
"https://bedrock-mantle.us-gov-east-1.api.aws/openai/v1",
|
||||
),
|
||||
(
|
||||
"us-gov-west-1",
|
||||
"https://bedrock-mantle.us-gov-west-1.api.aws/openai/v1",
|
||||
),
|
||||
] {
|
||||
assert_eq!(base_url(region).expect("supported region"), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_url_rejects_unsupported_region() {
|
||||
let err = base_url("us-west-1").expect_err("unsupported region");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"Fatal error: Amazon Bedrock does not support region `us-west-1`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aws_auth_config_uses_profile_and_mantle_service() {
|
||||
assert_eq!(
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: None,
|
||||
service: "bedrock-mantle".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aws_auth_config_uses_configured_region() {
|
||||
assert_eq!(
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some(" us-west-2 ".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
service: "bedrock-mantle".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,785 +0,0 @@
|
||||
mod auth;
|
||||
mod auth_refresh;
|
||||
mod catalog;
|
||||
mod credential_export;
|
||||
mod error;
|
||||
mod mantle;
|
||||
mod region;
|
||||
mod runtime;
|
||||
mod runtime_catalog;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_api::ApiError;
|
||||
use codex_api::Provider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_api::TransportError;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_LUNA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_TERRA_MODEL_ID;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_models_manager::manager::StaticModelsManager;
|
||||
use codex_protocol::account::ProviderAccount;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
|
||||
use crate::ProviderCapabilities;
|
||||
use crate::RemoteCompactionSupport;
|
||||
use crate::auth::auth_manager_for_provider;
|
||||
use crate::auth::resolve_provider_auth as resolve_configured_provider_auth;
|
||||
use crate::provider::ModelProvider;
|
||||
use crate::provider::ModelProviderFuture;
|
||||
use crate::provider::ProviderAccountResult;
|
||||
use crate::provider::ProviderAccountState;
|
||||
use crate::provider::ProviderAuthRecoveryMessages;
|
||||
use crate::provider::ProviderUnauthorizedRecovery;
|
||||
use crate::shared_state::process_shared_state;
|
||||
use auth::resolve_provider_auth as resolve_bedrock_provider_auth;
|
||||
pub(crate) use auth_refresh::AwsAuthRecovery;
|
||||
use catalog::normalize_bedrock_catalog;
|
||||
use catalog::static_gov_model_catalog;
|
||||
pub(crate) use catalog::static_model_catalog;
|
||||
pub(crate) use credential_export::AwsCredentialExport;
|
||||
use mantle::bedrock_mantle_runtime_base_url;
|
||||
pub use mantle::is_amazon_bedrock_gov_cloud_region;
|
||||
pub use mantle::is_supported_amazon_bedrock_region;
|
||||
pub use region::resolve_amazon_bedrock_region;
|
||||
use runtime::bedrock_runtime_base_url;
|
||||
use runtime_catalog::static_runtime_model_catalog;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum BedrockEndpoint {
|
||||
Mantle,
|
||||
Runtime,
|
||||
}
|
||||
|
||||
/// Runtime provider for Amazon Bedrock's OpenAI-compatible endpoints.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct AmazonBedrockModelProvider {
|
||||
http_client_factory: codex_http_client::HttpClientFactory,
|
||||
pub(crate) info: ModelProviderInfo,
|
||||
aws: ModelProviderAwsAuthInfo,
|
||||
endpoint: BedrockEndpoint,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
credential_export: Option<Arc<AwsCredentialExport>>,
|
||||
auth_recovery: Option<Arc<AwsAuthRecovery>>,
|
||||
}
|
||||
|
||||
impl AmazonBedrockModelProvider {
|
||||
pub(crate) fn new(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
) -> Self {
|
||||
let endpoint = if provider_info.is_amazon_bedrock_runtime() {
|
||||
BedrockEndpoint::Runtime
|
||||
} else {
|
||||
BedrockEndpoint::Mantle
|
||||
};
|
||||
let aws = provider_info
|
||||
.aws
|
||||
.clone()
|
||||
.unwrap_or(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
});
|
||||
let auth_source = auth::auth_source(&provider_info, auth_manager.as_deref(), std::env::var);
|
||||
let credential_export = if auth_source == auth::BedrockAuthSource::CredentialExport {
|
||||
process_shared_state().aws_credential_export(&aws)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let uses_aws_sdk_auth = matches!(
|
||||
auth_source,
|
||||
auth::BedrockAuthSource::CredentialExport
|
||||
| auth::BedrockAuthSource::ConfiguredAwsProfile
|
||||
| auth::BedrockAuthSource::AwsSdk
|
||||
);
|
||||
let auth_recovery = if uses_aws_sdk_auth && aws.auth_refresh.is_some() {
|
||||
process_shared_state().aws_auth_recovery(&aws)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let http_client_factory = auth_manager
|
||||
.as_ref()
|
||||
.map(|manager| {
|
||||
manager
|
||||
.http_client_factory()
|
||||
.with_network_policy(manager.application_network_policy())
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
codex_http_client::HttpClientFactory::new(
|
||||
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
)
|
||||
});
|
||||
let auth_manager = auth_manager_for_provider(auth_manager, &provider_info);
|
||||
Self {
|
||||
http_client_factory,
|
||||
info: provider_info,
|
||||
aws,
|
||||
endpoint,
|
||||
auth_manager,
|
||||
credential_export,
|
||||
auth_recovery,
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_source(&self) -> auth::BedrockAuthSource {
|
||||
auth::auth_source(&self.info, self.auth_manager.as_deref(), std::env::var)
|
||||
}
|
||||
|
||||
fn managed_auth(&self) -> Option<CodexAuth> {
|
||||
let source = self.auth_source();
|
||||
self.auth_manager
|
||||
.as_deref()
|
||||
.and_then(AuthManager::auth_cached)
|
||||
.filter(|auth| {
|
||||
matches!(
|
||||
(source, auth),
|
||||
(
|
||||
auth::BedrockAuthSource::ManagedBearerToken,
|
||||
CodexAuth::BedrockApiKey(_)
|
||||
) | (
|
||||
auth::BedrockAuthSource::ManagedAccessKeys,
|
||||
CodexAuth::BedrockAccessKeys(_)
|
||||
)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn uses_aws_auth_recovery(&self) -> bool {
|
||||
let source = self.auth_source();
|
||||
source == auth::BedrockAuthSource::CredentialExport
|
||||
|| (self.auth_recovery.is_some()
|
||||
&& matches!(
|
||||
source,
|
||||
auth::BedrockAuthSource::ConfiguredAwsProfile | auth::BedrockAuthSource::AwsSdk
|
||||
))
|
||||
}
|
||||
|
||||
async fn auth(&self) -> Option<CodexAuth> {
|
||||
match self.auth_source() {
|
||||
auth::BedrockAuthSource::CommandBearerToken => match self.auth_manager.as_ref() {
|
||||
Some(auth_manager) => auth_manager.auth().await,
|
||||
None => None,
|
||||
},
|
||||
auth::BedrockAuthSource::ManagedBearerToken
|
||||
| auth::BedrockAuthSource::ManagedAccessKeys => self.managed_auth(),
|
||||
auth::BedrockAuthSource::CredentialExport
|
||||
| auth::BedrockAuthSource::ConfiguredAwsProfile
|
||||
| auth::BedrockAuthSource::EnvBearerToken
|
||||
| auth::BedrockAuthSource::EnvAwsCredentials
|
||||
| auth::BedrockAuthSource::AwsSdk => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn api_provider(&self) -> Result<Provider> {
|
||||
let mut api_provider_info = self.info.clone();
|
||||
api_provider_info.base_url = self.runtime_base_url().await?;
|
||||
api_provider_info.to_api_provider()
|
||||
}
|
||||
|
||||
async fn runtime_base_url(&self) -> Result<Option<String>> {
|
||||
if let Some(base_url) = self.info.base_url.clone() {
|
||||
return Ok(Some(base_url));
|
||||
}
|
||||
let http_client_factory = self.http_client_factory.clone().with_network_policy(
|
||||
self.http_client_factory
|
||||
.network_policy()
|
||||
.clone()
|
||||
.for_current_account(),
|
||||
);
|
||||
let auth_source = self.auth_source();
|
||||
let managed_auth = self.managed_auth();
|
||||
let base_url = match self.endpoint {
|
||||
BedrockEndpoint::Mantle => {
|
||||
bedrock_mantle_runtime_base_url(
|
||||
auth_source,
|
||||
managed_auth.as_ref(),
|
||||
&self.aws,
|
||||
&http_client_factory,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
BedrockEndpoint::Runtime => {
|
||||
bedrock_runtime_base_url(
|
||||
auth_source,
|
||||
managed_auth.as_ref(),
|
||||
&self.aws,
|
||||
&http_client_factory,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
};
|
||||
Ok(Some(base_url))
|
||||
}
|
||||
|
||||
async fn api_auth(&self) -> Result<SharedAuthProvider> {
|
||||
let http_client_factory = self.http_client_factory.clone().with_network_policy(
|
||||
self.http_client_factory
|
||||
.network_policy()
|
||||
.clone()
|
||||
.for_current_account(),
|
||||
);
|
||||
let source = self.auth_source();
|
||||
if source == auth::BedrockAuthSource::CommandBearerToken {
|
||||
let auth = self.auth().await;
|
||||
return resolve_configured_provider_auth(auth.as_ref(), &self.info);
|
||||
}
|
||||
|
||||
let managed_auth = self.managed_auth();
|
||||
resolve_bedrock_provider_auth(
|
||||
source,
|
||||
managed_auth.as_ref(),
|
||||
&self.aws,
|
||||
self.endpoint,
|
||||
&http_client_factory,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn default_model_catalog(&self) -> ModelsResponse {
|
||||
match self.endpoint {
|
||||
BedrockEndpoint::Mantle => {
|
||||
let endpoint = self
|
||||
.info
|
||||
.base_url
|
||||
.as_deref()
|
||||
.and_then(|base_url| url::Url::parse(base_url).ok());
|
||||
let is_govcloud =
|
||||
endpoint
|
||||
.as_ref()
|
||||
.and_then(url::Url::host_str)
|
||||
.is_some_and(|host| {
|
||||
host.starts_with("bedrock-mantle.us-gov-") && host.ends_with(".api.aws")
|
||||
});
|
||||
if is_govcloud {
|
||||
static_gov_model_catalog()
|
||||
} else {
|
||||
static_model_catalog()
|
||||
}
|
||||
}
|
||||
BedrockEndpoint::Runtime => static_runtime_model_catalog(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelProvider for AmazonBedrockModelProvider {
|
||||
fn info(&self) -> &ModelProviderInfo {
|
||||
&self.info
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> ProviderCapabilities {
|
||||
ProviderCapabilities {
|
||||
reasoning_summaries: true,
|
||||
web_search: self.endpoint == BedrockEndpoint::Mantle,
|
||||
external_web_access: false,
|
||||
remote_compaction: RemoteCompactionSupport::V2,
|
||||
}
|
||||
}
|
||||
|
||||
fn approval_review_preferred_model(&self) -> &'static str {
|
||||
match self.endpoint {
|
||||
BedrockEndpoint::Mantle => AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
BedrockEndpoint::Runtime => AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_LUNA_MODEL_ID,
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_extraction_preferred_model(&self) -> &'static str {
|
||||
match self.endpoint {
|
||||
BedrockEndpoint::Mantle => AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
BedrockEndpoint::Runtime => AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_LUNA_MODEL_ID,
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_consolidation_preferred_model(&self) -> &'static str {
|
||||
match self.endpoint {
|
||||
BedrockEndpoint::Mantle => AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID,
|
||||
BedrockEndpoint::Runtime => AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_TERRA_MODEL_ID,
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_manager(&self) -> Option<Arc<AuthManager>> {
|
||||
match self.auth_source() {
|
||||
auth::BedrockAuthSource::CommandBearerToken
|
||||
| auth::BedrockAuthSource::ManagedBearerToken
|
||||
| auth::BedrockAuthSource::ManagedAccessKeys => self.auth_manager.clone(),
|
||||
auth::BedrockAuthSource::CredentialExport
|
||||
| auth::BedrockAuthSource::ConfiguredAwsProfile
|
||||
| auth::BedrockAuthSource::EnvBearerToken
|
||||
| auth::BedrockAuthSource::EnvAwsCredentials
|
||||
| auth::BedrockAuthSource::AwsSdk => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_recoverable_auth_error(&self, error: &TransportError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
TransportError::Http { status, .. } if *status == http::StatusCode::UNAUTHORIZED
|
||||
) || (self.uses_aws_auth_recovery() && error::is_refreshable_auth_error(error))
|
||||
}
|
||||
|
||||
fn auth_recovery_messages(&self) -> Option<ProviderAuthRecoveryMessages> {
|
||||
self.uses_aws_auth_recovery()
|
||||
.then_some(ProviderAuthRecoveryMessages {
|
||||
started: "AWS session has expired. Reauthenticating...",
|
||||
succeeded: "Signed in with AWS.",
|
||||
})
|
||||
}
|
||||
|
||||
fn recover_from_unauthorized(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, Result<ProviderUnauthorizedRecovery>> {
|
||||
Box::pin(async move {
|
||||
if !self.uses_aws_auth_recovery() {
|
||||
return Ok(ProviderUnauthorizedRecovery::NotConfigured);
|
||||
}
|
||||
|
||||
// Hold the cache guard across both steps so concurrent callers share recovery.
|
||||
let export_refresh = if let Some(exporter) = &self.credential_export {
|
||||
let refresh = exporter.begin_refresh().await;
|
||||
if refresh.is_none() {
|
||||
// Another caller completed recovery while we were waiting.
|
||||
return Ok(ProviderUnauthorizedRecovery::Recovered);
|
||||
}
|
||||
refresh
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let network_policy = self
|
||||
.http_client_factory
|
||||
.network_policy()
|
||||
.clone()
|
||||
.for_current_account();
|
||||
let permit = network_policy
|
||||
.acquire_for_unsupported_sdk()
|
||||
.map_err(|error| CodexErr::Fatal(error.to_string()))?;
|
||||
let result: std::io::Result<()> = permit
|
||||
.run(async {
|
||||
if let Some(recovery) = &self.auth_recovery {
|
||||
recovery.refresh().await?;
|
||||
}
|
||||
if let Some(exporter) = export_refresh {
|
||||
exporter.refresh().await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| CodexErr::Fatal(error.to_string()))?;
|
||||
result.map_err(|error| {
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::InvalidData
|
||||
| std::io::ErrorKind::InvalidInput
|
||||
| std::io::ErrorKind::NotFound
|
||||
| std::io::ErrorKind::PermissionDenied
|
||||
) {
|
||||
CodexErr::InvalidRequest(error.to_string())
|
||||
} else {
|
||||
CodexErr::Io(error)
|
||||
}
|
||||
})?;
|
||||
Ok(ProviderUnauthorizedRecovery::Recovered)
|
||||
})
|
||||
}
|
||||
|
||||
fn auth(&self) -> ModelProviderFuture<'_, Option<CodexAuth>> {
|
||||
Box::pin(AmazonBedrockModelProvider::auth(self))
|
||||
}
|
||||
|
||||
fn account_state(&self) -> ProviderAccountResult {
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::AmazonBedrock {
|
||||
uses_codex_managed_credentials: matches!(
|
||||
self.auth_source(),
|
||||
auth::BedrockAuthSource::ManagedBearerToken
|
||||
| auth::BedrockAuthSource::ManagedAccessKeys
|
||||
),
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn map_api_error(&self, error: ApiError) -> CodexErr {
|
||||
error::map_api_error(error)
|
||||
}
|
||||
|
||||
fn api_provider(&self) -> ModelProviderFuture<'_, Result<Provider>> {
|
||||
Box::pin(AmazonBedrockModelProvider::api_provider(self))
|
||||
}
|
||||
|
||||
fn runtime_base_url(&self) -> ModelProviderFuture<'_, Result<Option<String>>> {
|
||||
Box::pin(AmazonBedrockModelProvider::runtime_base_url(self))
|
||||
}
|
||||
|
||||
fn api_auth(&self) -> ModelProviderFuture<'_, Result<SharedAuthProvider>> {
|
||||
Box::pin(AmazonBedrockModelProvider::api_auth(self))
|
||||
}
|
||||
|
||||
fn models_manager(
|
||||
&self,
|
||||
_codex_home: PathBuf,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager {
|
||||
let origin = if config_model_catalog.is_some() {
|
||||
codex_models_manager::ModelOrigin::ExplicitConfig
|
||||
} else {
|
||||
codex_models_manager::ModelOrigin::Provider
|
||||
};
|
||||
Arc::new(StaticModelsManager::new(
|
||||
/*auth_manager*/ None,
|
||||
config_model_catalog
|
||||
.map_or_else(|| self.default_model_catalog(), normalize_bedrock_catalog),
|
||||
origin,
|
||||
))
|
||||
}
|
||||
|
||||
fn models_manager_without_cache(
|
||||
&self,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager {
|
||||
self.models_manager(PathBuf::new(), config_model_catalog)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "error_tests.rs"]
|
||||
mod error_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::num::NonZeroU64;
|
||||
|
||||
use codex_login::auth::BedrockAccessKeysAuth;
|
||||
use codex_login::auth::BedrockApiKeyAuth;
|
||||
use codex_model_provider_info::AwsAuthRefreshConfig;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn command_auth_provider(base_url: Option<&str>) -> ModelProviderInfo {
|
||||
let mut provider = ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None);
|
||||
provider.base_url = base_url.map(str::to_string);
|
||||
provider.auth = Some(ModelProviderAuthInfo {
|
||||
command: "token-fetcher".to_string(),
|
||||
args: vec!["fetch".into()],
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("timeout should be non-zero"),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: std::env::current_dir()
|
||||
.expect("current directory should be available")
|
||||
.try_into()
|
||||
.expect("current directory should be absolute"),
|
||||
});
|
||||
provider
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_provider_for_bedrock_bearer_token_uses_configured_region_endpoint() {
|
||||
let region = "eu-central-1";
|
||||
let mut api_provider_info =
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None);
|
||||
api_provider_info.base_url = Some(mantle::base_url(region).expect("supported region"));
|
||||
let api_provider = api_provider_info
|
||||
.to_api_provider()
|
||||
.expect("api provider should build");
|
||||
|
||||
assert_eq!(
|
||||
api_provider.base_url,
|
||||
"https://bedrock-mantle.eu-central-1.api.aws/openai/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn command_auth_resolves_configured_and_regional_base_urls() {
|
||||
let mut provider_info = command_auth_provider(Some("https://proxy.example.com/v1"));
|
||||
provider_info.aws = Some(ModelProviderAwsAuthInfo {
|
||||
profile: Some("aws-profile-that-should-not-be-loaded".to_string()),
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: Some(AwsAuthRefreshConfig {
|
||||
command: "aws".to_string(),
|
||||
args: vec!["login".into()],
|
||||
timeout_ms: NonZeroU64::new(1_000).expect("timeout should be non-zero"),
|
||||
}),
|
||||
});
|
||||
let provider = AmazonBedrockModelProvider::new(provider_info, /*auth_manager*/ None);
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.expect("configured base URL should resolve"),
|
||||
Some("https://proxy.example.com/v1".to_string())
|
||||
);
|
||||
assert!(
|
||||
provider
|
||||
.auth_manager()
|
||||
.expect("command auth manager should be exposed")
|
||||
.has_external_auth()
|
||||
);
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
);
|
||||
|
||||
let mut regional_provider_info = command_auth_provider(/*base_url*/ None);
|
||||
regional_provider_info.aws = Some(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
});
|
||||
let regional_provider =
|
||||
AmazonBedrockModelProvider::new(regional_provider_info, /*auth_manager*/ None);
|
||||
|
||||
assert_eq!(
|
||||
regional_provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.expect("configured AWS region should resolve for command auth"),
|
||||
Some("https://bedrock-mantle.us-west-2.api.aws/openai/v1".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_profile_takes_precedence_over_managed_auth() {
|
||||
let managed_auth = BedrockApiKeyAuth {
|
||||
api_key: "managed-bedrock-api-key".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
};
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::BedrockApiKey(managed_auth.clone()));
|
||||
let aws = ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: Some(AwsAuthRefreshConfig {
|
||||
command: "aws".to_string(),
|
||||
args: vec!["login".into()],
|
||||
timeout_ms: NonZeroU64::new(1_000).expect("timeout should be non-zero"),
|
||||
}),
|
||||
};
|
||||
let provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(aws.clone())),
|
||||
Some(auth_manager.clone()),
|
||||
);
|
||||
|
||||
assert!(Arc::ptr_eq(
|
||||
&provider
|
||||
.auth_manager()
|
||||
.expect("managed Bedrock auth manager should be exposed"),
|
||||
&auth_manager,
|
||||
));
|
||||
assert_eq!(
|
||||
provider.auth().await,
|
||||
Some(CodexAuth::BedrockApiKey(managed_auth))
|
||||
);
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::AmazonBedrock {
|
||||
uses_codex_managed_credentials: true,
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.expect("managed Bedrock region should resolve"),
|
||||
Some("https://bedrock-mantle.us-east-1.api.aws/openai/v1".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.api_auth()
|
||||
.await
|
||||
.expect("managed Bedrock auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap()
|
||||
.get(http::header::AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer managed-bedrock-api-key"))
|
||||
);
|
||||
assert!(!provider.uses_aws_auth_recovery());
|
||||
|
||||
let access_keys_auth_manager = AuthManager::from_auth_for_testing(
|
||||
CodexAuth::BedrockAccessKeys(BedrockAccessKeysAuth {
|
||||
access_key_id: "managed-access-key-id".to_string(),
|
||||
secret_access_key: "managed-secret-access-key".to_string(),
|
||||
session_token: None,
|
||||
}),
|
||||
);
|
||||
|
||||
for auth_manager in [auth_manager, access_keys_auth_manager] {
|
||||
let configured_profile_provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: Some("configured-aws-profile".to_string()),
|
||||
..aws.clone()
|
||||
})),
|
||||
Some(auth_manager),
|
||||
);
|
||||
|
||||
assert!(configured_profile_provider.auth_manager().is_none());
|
||||
assert_eq!(configured_profile_provider.auth().await, None);
|
||||
assert_eq!(
|
||||
configured_profile_provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
configured_profile_provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.expect("configured AWS profile region should resolve"),
|
||||
Some("https://bedrock-mantle.us-west-2.api.aws/openai/v1".to_string())
|
||||
);
|
||||
assert!(
|
||||
configured_profile_provider
|
||||
.api_auth()
|
||||
.await
|
||||
.expect("configured AWS profile auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap()
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.is_none()
|
||||
);
|
||||
assert!(configured_profile_provider.uses_aws_auth_recovery());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn openai_auth_is_not_exposed_to_bedrock() {
|
||||
let provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
);
|
||||
|
||||
assert!(provider.auth_manager().is_none());
|
||||
assert_eq!(provider.auth().await, None);
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capabilities_enable_web_search() {
|
||||
let provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.capabilities(),
|
||||
ProviderCapabilities {
|
||||
reasoning_summaries: true,
|
||||
web_search: true,
|
||||
external_web_access: false,
|
||||
remote_compaction: RemoteCompactionSupport::V2,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_capabilities_disable_web_search_and_support_v2_remote_compaction() {
|
||||
let provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_runtime_provider(/*aws*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.capabilities(),
|
||||
ProviderCapabilities {
|
||||
reasoning_summaries: true,
|
||||
web_search: false,
|
||||
external_web_access: false,
|
||||
remote_compaction: RemoteCompactionSupport::V2,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_managed_auth_resolves_runtime_endpoint() {
|
||||
let managed_auth = BedrockApiKeyAuth {
|
||||
api_key: "managed-bedrock-api-key".to_string(),
|
||||
region: "eu-west-1".to_string(),
|
||||
};
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::BedrockApiKey(managed_auth));
|
||||
let provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_runtime_provider(/*aws*/ None),
|
||||
Some(auth_manager),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.expect("managed Bedrock Runtime region should resolve"),
|
||||
Some("https://bedrock-runtime.eu-west-1.amazonaws.com/openai/v1".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_background_models_match_bedrock_endpoint() {
|
||||
let mantle_provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
let runtime_provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_runtime_provider(/*aws*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
mantle_provider.approval_review_preferred_model(),
|
||||
mantle_provider.memory_extraction_preferred_model(),
|
||||
mantle_provider.memory_consolidation_preferred_model(),
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID,
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
runtime_provider.approval_review_preferred_model(),
|
||||
runtime_provider.memory_extraction_preferred_model(),
|
||||
runtime_provider.memory_consolidation_preferred_model(),
|
||||
),
|
||||
(
|
||||
AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_LUNA_MODEL_ID,
|
||||
AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_LUNA_MODEL_ID,
|
||||
AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_TERRA_MODEL_ID,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
//! Resolves the active Bedrock region using the same authentication precedence as requests.
|
||||
//! This does not validate model availability or issue an inference request.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::Result;
|
||||
|
||||
use super::AmazonBedrockModelProvider;
|
||||
use super::auth::resolve_region;
|
||||
|
||||
/// Resolves a Bedrock provider's region independently of endpoint availability.
|
||||
pub async fn resolve_amazon_bedrock_region(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
) -> Result<String> {
|
||||
let provider = AmazonBedrockModelProvider::new(provider_info, auth_manager);
|
||||
let managed_auth = provider.managed_auth();
|
||||
let factory = provider.http_client_factory.clone().with_network_policy(
|
||||
provider
|
||||
.http_client_factory
|
||||
.network_policy()
|
||||
.clone()
|
||||
.for_current_account(),
|
||||
);
|
||||
resolve_region(
|
||||
provider.auth_source(),
|
||||
managed_auth.as_ref(),
|
||||
&provider.aws,
|
||||
provider.endpoint,
|
||||
&factory,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
use codex_aws_auth::AwsAuthConfig;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_protocol::error::Result;
|
||||
|
||||
use super::BedrockEndpoint;
|
||||
use super::auth::BedrockAuthSource;
|
||||
use super::auth::resolve_region;
|
||||
use super::mantle::region_from_config;
|
||||
|
||||
const BEDROCK_RUNTIME_SERVICE_NAME: &str = "bedrock";
|
||||
|
||||
pub(super) fn aws_auth_config(aws: &ModelProviderAwsAuthInfo) -> AwsAuthConfig {
|
||||
AwsAuthConfig {
|
||||
profile: aws.profile.clone(),
|
||||
region: region_from_config(aws),
|
||||
service: BEDROCK_RUNTIME_SERVICE_NAME.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn base_url(region: &str) -> String {
|
||||
format!("https://bedrock-runtime.{region}.amazonaws.com/openai/v1")
|
||||
}
|
||||
|
||||
pub(super) async fn bedrock_runtime_base_url(
|
||||
source: BedrockAuthSource,
|
||||
managed_auth: Option<&CodexAuth>,
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
http_client_factory: &codex_http_client::HttpClientFactory,
|
||||
) -> Result<String> {
|
||||
let region = resolve_region(
|
||||
source,
|
||||
managed_auth,
|
||||
aws,
|
||||
BedrockEndpoint::Runtime,
|
||||
http_client_factory,
|
||||
)
|
||||
.await?;
|
||||
Ok(base_url(®ion))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "runtime_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,52 +0,0 @@
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
|
||||
use super::BedrockEndpoint;
|
||||
use super::catalog::normalize_bundled_bedrock_catalog;
|
||||
use super::catalog::static_model_catalog;
|
||||
|
||||
const ROUTING_VARIANTS: [(&str, &str, i32); 2] =
|
||||
[("global.", "Global", 0), ("us.", "US cross-region", 1)];
|
||||
|
||||
pub(super) fn static_runtime_model_catalog() -> ModelsResponse {
|
||||
let base_models = static_model_catalog()
|
||||
.models
|
||||
.into_iter()
|
||||
.filter(|model| {
|
||||
matches!(
|
||||
model.slug.as_str(),
|
||||
AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID
|
||||
| AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID
|
||||
| AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID
|
||||
| AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID
|
||||
| AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID
|
||||
| AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID
|
||||
| AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID
|
||||
| AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut models = Vec::with_capacity(ROUTING_VARIANTS.len() * base_models.len());
|
||||
for (prefix, routing_label, routing_priority) in ROUTING_VARIANTS {
|
||||
for model in &base_models {
|
||||
let mut variant = model.clone();
|
||||
variant.slug = format!("{prefix}{}", model.slug);
|
||||
variant.display_name = format!("{} ({routing_label})", model.display_name);
|
||||
variant.priority = routing_priority * base_models.len() as i32 + model.priority;
|
||||
variant.supports_search_tool = false;
|
||||
models.push(variant);
|
||||
}
|
||||
}
|
||||
normalize_bundled_bedrock_catalog(ModelsResponse { models }, BedrockEndpoint::Runtime)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "runtime_catalog_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,167 +0,0 @@
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::static_runtime_model_catalog;
|
||||
|
||||
#[test]
|
||||
fn runtime_catalog_includes_supported_cross_region_models_in_priority_order() {
|
||||
let catalog = static_runtime_model_catalog();
|
||||
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| (
|
||||
model.slug.as_str(),
|
||||
model.display_name.as_str(),
|
||||
model.priority,
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("global.openai.gpt-6.1-sol", "GPT-6.1 Sol (Global)", 0),
|
||||
("global.openai.gpt-6-astra", "GPT-6-Astra (Global)", 1),
|
||||
("global.openai.gpt-6.1-terra", "GPT-6.1 Terra (Global)", 2),
|
||||
("global.openai.gpt-6-sol", "GPT-6 Sol (Global)", 3),
|
||||
("global.openai.gpt-6-luna", "GPT-6 Luna (Global)", 4),
|
||||
("global.openai.gpt-5.6-sol", "GPT-5.6 Sol (Global)", 5),
|
||||
("global.openai.gpt-5.6-terra", "GPT-5.6 Terra (Global)", 6),
|
||||
("global.openai.gpt-5.6-luna", "GPT-5.6 Luna (Global)", 7),
|
||||
("us.openai.gpt-6.1-sol", "GPT-6.1 Sol (US cross-region)", 8),
|
||||
("us.openai.gpt-6-astra", "GPT-6-Astra (US cross-region)", 9),
|
||||
(
|
||||
"us.openai.gpt-6.1-terra",
|
||||
"GPT-6.1 Terra (US cross-region)",
|
||||
10
|
||||
),
|
||||
("us.openai.gpt-6-sol", "GPT-6 Sol (US cross-region)", 11),
|
||||
("us.openai.gpt-6-luna", "GPT-6 Luna (US cross-region)", 12),
|
||||
("us.openai.gpt-5.6-sol", "GPT-5.6 Sol (US cross-region)", 13),
|
||||
(
|
||||
"us.openai.gpt-5.6-terra",
|
||||
"GPT-5.6 Terra (US cross-region)",
|
||||
14
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-5.6-luna",
|
||||
"GPT-5.6 Luna (US cross-region)",
|
||||
15
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_catalog_disables_web_search_without_overriding_review_models() {
|
||||
let catalog = static_runtime_model_catalog();
|
||||
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| (
|
||||
model.slug.as_str(),
|
||||
model.auto_review_model_override.as_deref(),
|
||||
model.supports_search_tool,
|
||||
model.multi_agent_version,
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
(
|
||||
"global.openai.gpt-6.1-sol",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"global.openai.gpt-6-astra",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"global.openai.gpt-6.1-terra",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"global.openai.gpt-6-sol",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"global.openai.gpt-6-luna",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"global.openai.gpt-5.6-sol",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"global.openai.gpt-5.6-terra",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"global.openai.gpt-5.6-luna",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V1),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-6.1-sol",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-6-astra",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-6.1-terra",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-6-sol",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-6-luna",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-5.6-sol",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-5.6-terra",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V2),
|
||||
),
|
||||
(
|
||||
"us.openai.gpt-5.6-luna",
|
||||
None,
|
||||
false,
|
||||
Some(MultiAgentVersion::V1),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
use codex_aws_auth::AwsAuthConfig;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::aws_auth_config;
|
||||
use super::base_url;
|
||||
|
||||
#[test]
|
||||
fn base_url_uses_regional_runtime_endpoint() {
|
||||
assert_eq!(
|
||||
base_url("us-west-2"),
|
||||
"https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aws_auth_config_uses_bedrock_service() {
|
||||
assert_eq!(
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: Some("runtime-profile".to_string()),
|
||||
region: Some(" eu-west-1 ".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
profile: Some("runtime-profile".to_string()),
|
||||
region: Some("eu-west-1".to_string()),
|
||||
service: "bedrock".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_api::AuthError;
|
||||
@@ -9,14 +8,10 @@ use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use http::HeaderMap;
|
||||
|
||||
use crate::bearer_auth_provider::BearerAuthProvider;
|
||||
|
||||
const BEDROCK_API_KEY_UNSUPPORTED_MESSAGE: &str =
|
||||
"Bedrock API key auth is only supported by the Amazon Bedrock model provider";
|
||||
|
||||
/// Credential ownership for one harness/thread context.
|
||||
/// Publish this so auxiliary clients cannot select another thread's credentials.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -170,24 +165,11 @@ pub(crate) fn auth_manager_for_provider(
|
||||
provider: &ModelProviderInfo,
|
||||
) -> Option<Arc<AuthManager>> {
|
||||
match provider.auth.clone() {
|
||||
Some(config) => {
|
||||
if provider.is_gcp() {
|
||||
let mut env = HashMap::new();
|
||||
if let Some(credential_file) = &provider.credential_file {
|
||||
env.insert(
|
||||
"GOOGLE_APPLICATION_CREDENTIALS".to_string(),
|
||||
credential_file.as_os_str().to_os_string(),
|
||||
);
|
||||
}
|
||||
Some(AuthManager::external_bearer_only_with_env(config, env))
|
||||
} else {
|
||||
Some(match auth_manager {
|
||||
Some(manager) => crate::shared_state::process_shared_state()
|
||||
.command_credentials(&config, &manager.runtime_config()),
|
||||
None => AuthManager::external_bearer_only(config),
|
||||
})
|
||||
}
|
||||
}
|
||||
Some(config) => Some(match auth_manager {
|
||||
Some(manager) => crate::shared_state::process_shared_state()
|
||||
.command_credentials(&config, &manager.runtime_config()),
|
||||
None => AuthManager::external_bearer_only(config),
|
||||
}),
|
||||
None => auth_manager,
|
||||
}
|
||||
}
|
||||
@@ -204,15 +186,6 @@ pub(crate) fn resolve_provider_auth(
|
||||
return Ok(unauthenticated_auth_provider());
|
||||
}
|
||||
|
||||
if matches!(
|
||||
auth,
|
||||
Some(CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_))
|
||||
) {
|
||||
return Err(CodexErr::UnsupportedOperation(
|
||||
BEDROCK_API_KEY_UNSUPPORTED_MESSAGE.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(match auth {
|
||||
Some(auth) => auth_provider_from_auth(auth),
|
||||
None => unauthenticated_auth_provider(),
|
||||
@@ -233,23 +206,6 @@ pub(crate) fn bearer_auth_for_provider(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Whether the selected API key enables OpenAI's default FedRAMP endpoints.
|
||||
/// Command-backed providers retain their configured routing across token refreshes.
|
||||
pub(crate) fn uses_fedramp_api_key(
|
||||
auth: Option<&CodexAuth>,
|
||||
provider: &ModelProviderInfo,
|
||||
) -> codex_protocol::error::Result<bool> {
|
||||
if !provider.is_openai() || provider.has_command_auth() {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(auth) = bearer_auth_for_provider(provider)? {
|
||||
return Ok(auth.is_fedramp_account);
|
||||
}
|
||||
Ok(provider.requires_openai_auth
|
||||
&& matches!(auth, Some(CodexAuth::ApiKey(_)))
|
||||
&& auth.is_some_and(CodexAuth::is_fedramp_account))
|
||||
}
|
||||
|
||||
/// Builds request auth for an already selected credential.
|
||||
pub fn auth_provider_for_request(auth: &CodexAuth) -> ResolvedProviderAuth {
|
||||
let mut resolved = ResolvedProviderAuth::new(auth_provider_from_auth(auth));
|
||||
@@ -261,12 +217,8 @@ pub fn auth_provider_for_request(auth: &CodexAuth) -> ResolvedProviderAuth {
|
||||
pub fn auth_provider_from_auth(auth: &CodexAuth) -> SharedAuthProvider {
|
||||
match auth {
|
||||
CodexAuth::Headers(auth) => Arc::new(HeaderAuthProvider { auth: auth.clone() }),
|
||||
CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_) => {
|
||||
unreachable!("{BEDROCK_API_KEY_UNSUPPORTED_MESSAGE}")
|
||||
}
|
||||
CodexAuth::ApiKey(_) => Arc::new(BearerAuthProvider {
|
||||
token: auth.get_token().ok(),
|
||||
is_fedramp_account: auth.is_fedramp_account(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthDotJson;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::auth::BedrockApiKeyAuth;
|
||||
use codex_login::save_auth;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_model_provider_info::create_oss_provider_with_base_url;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use http::HeaderValue;
|
||||
use http::header::AUTHORIZATION;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -48,8 +46,6 @@ fn api_key_auth_json(api_key: &str) -> AuthDotJson {
|
||||
AuthDotJson {
|
||||
auth_mode: Some(AuthMode::ApiKey),
|
||||
openai_api_key: Some(api_key.to_string()),
|
||||
bedrock_api_key: None,
|
||||
bedrock_access_keys: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,43 +82,7 @@ fn custom_provider_does_not_inherit_ambient_auth_headers() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_does_not_inherit_ambient_bedrock_auth() {
|
||||
let provider =
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
||||
let ambient_auth = CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "bedrock-api-key-test".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
});
|
||||
|
||||
let auth = resolve_provider_auth(Some(&ambient_auth), &provider).expect("auth should resolve");
|
||||
|
||||
assert!(auth.to_auth_headers().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_uses_explicit_bearer_instead_of_ambient_auth() {
|
||||
let mut provider =
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
||||
provider.experimental_bearer_token = Some("provider-token".into());
|
||||
let ambient_auth = CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "bedrock-api-key-test".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
});
|
||||
|
||||
let headers = resolve_provider_auth(Some(&ambient_auth), &provider)
|
||||
.expect("auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
headers.get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer provider-token"))
|
||||
);
|
||||
assert_eq!(headers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_fedramp_routing_follows_the_selected_provider_credential() {
|
||||
fn selected_provider_credential_wins_without_openai_routing_headers() {
|
||||
let project_key = "sk-proj-fedramp-synthetic-test-key";
|
||||
let service_account_key = "sk-svcacct-fedramp-synthetic-test-key";
|
||||
let legacy_key = "sk-proj-synthetic-test-key";
|
||||
@@ -135,7 +95,8 @@ fn api_key_fedramp_routing_follows_the_selected_provider_credential() {
|
||||
(legacy_key, Some(project_key), true),
|
||||
(legacy_key, Some(service_account_key), true),
|
||||
] {
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let mut provider =
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None);
|
||||
provider.experimental_bearer_token = provider_key.map(Into::into);
|
||||
let ambient_auth = CodexAuth::from_api_key(ambient_key);
|
||||
|
||||
@@ -145,13 +106,12 @@ fn api_key_fedramp_routing_follows_the_selected_provider_credential() {
|
||||
.unwrap();
|
||||
|
||||
let key = provider_key.unwrap_or(ambient_key);
|
||||
let mut expected_headers = HeaderMap::from_iter([(
|
||||
// FedRAMP-looking keys no longer add OpenAI routing headers.
|
||||
let _ = expected_fedramp;
|
||||
let expected_headers = HeaderMap::from_iter([(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {key}")).unwrap(),
|
||||
)]);
|
||||
if expected_fedramp {
|
||||
expected_headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
||||
}
|
||||
assert_eq!(headers, expected_headers);
|
||||
}
|
||||
}
|
||||
@@ -185,7 +145,7 @@ fn custom_provider_uses_command_resolved_auth() {
|
||||
|
||||
#[test]
|
||||
fn openai_provider_preserves_ambient_auth_headers() {
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let provider = ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None);
|
||||
let mut expected = HeaderMap::new();
|
||||
expected.insert(
|
||||
AUTHORIZATION,
|
||||
@@ -217,101 +177,6 @@ fn header_auth_adds_predefined_headers() {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_rejects_bedrock_api_key_auth() {
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let auth = CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "bedrock-api-key-test".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
});
|
||||
|
||||
match resolve_provider_auth(Some(&auth), &provider) {
|
||||
Err(err) => match err.details() {
|
||||
CodexErrorDetails::UnsupportedOperation(message) => {
|
||||
assert_eq!(message, BEDROCK_API_KEY_UNSUPPORTED_MESSAGE);
|
||||
}
|
||||
details => panic!("unexpected auth error: {details:?}"),
|
||||
},
|
||||
Ok(_) => panic!("Bedrock API key auth should be rejected"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_manager_provider_follows_reloads_but_not_credential_kind_switches() {
|
||||
let codex_home = test_codex_home();
|
||||
save_ephemeral_auth(&codex_home, api_key_auth_json("first-key"));
|
||||
let auth_manager = Arc::new(
|
||||
AuthManager::new(
|
||||
codex_home.clone(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let expected_auth = auth_manager
|
||||
.auth_cached()
|
||||
.expect("initial auth should be cached");
|
||||
let provider = auth_provider_from_auth_manager(Arc::clone(&auth_manager), &expected_auth);
|
||||
let initial_headers = provider
|
||||
.apply_auth_headers(HeaderMap::new())
|
||||
.await
|
||||
.expect("initial auth headers");
|
||||
|
||||
assert_eq!(
|
||||
provider.to_auth_headers().unwrap().get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer first-key"))
|
||||
);
|
||||
|
||||
save_ephemeral_auth(&codex_home, api_key_auth_json("reloaded-key"));
|
||||
|
||||
// Ordinary requests retain the manager's cache until a reload runs.
|
||||
assert_eq!(
|
||||
provider
|
||||
.apply_auth_headers(HeaderMap::new())
|
||||
.await
|
||||
.expect("cached auth headers"),
|
||||
initial_headers
|
||||
);
|
||||
// Stored API keys cannot be refreshed after a 401.
|
||||
assert!(!provider.refresh_after_unauthorized(initial_headers).await);
|
||||
|
||||
auth_manager.reload().await;
|
||||
let resolved_headers = provider
|
||||
.apply_auth_headers(HeaderMap::new())
|
||||
.await
|
||||
.expect("managed auth headers should resolve");
|
||||
assert_eq!(
|
||||
resolved_headers.get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer reloaded-key"))
|
||||
);
|
||||
|
||||
save_ephemeral_auth(
|
||||
&codex_home,
|
||||
AuthDotJson {
|
||||
auth_mode: Some(AuthMode::BedrockApiKey),
|
||||
openai_api_key: None,
|
||||
bedrock_api_key: Some(BedrockApiKeyAuth {
|
||||
api_key: "bedrock-api-key-test".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
}),
|
||||
bedrock_access_keys: None,
|
||||
},
|
||||
);
|
||||
assert!(!provider.refresh_after_unauthorized(resolved_headers).await);
|
||||
auth_manager.reload().await;
|
||||
|
||||
assert!(matches!(
|
||||
provider.to_auth_headers(),
|
||||
Err(AuthError::Transient(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
provider.apply_auth_headers(HeaderMap::new()).await,
|
||||
Err(AuthError::Transient(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RefreshFailure {
|
||||
Transient,
|
||||
@@ -404,3 +269,132 @@ async fn failed_refresh_retries_only_with_newer_credentials() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_does_not_inherit_ambient_stored_auth() {
|
||||
let provider =
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
||||
let ambient_auth = CodexAuth::from_api_key("ambient-stored-key");
|
||||
|
||||
let auth = resolve_provider_auth(Some(&ambient_auth), &provider).expect("auth should resolve");
|
||||
|
||||
assert!(auth.to_auth_headers().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_uses_explicit_bearer_instead_of_ambient_auth() {
|
||||
let mut provider =
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
||||
provider.experimental_bearer_token = Some("provider-token".into());
|
||||
let ambient_auth = CodexAuth::from_api_key("ambient-stored-key");
|
||||
|
||||
let headers = resolve_provider_auth(Some(&ambient_auth), &provider)
|
||||
.expect("auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
headers.get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer provider-token"))
|
||||
);
|
||||
assert_eq!(headers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyring_provider_key_is_sent_instead_of_ambient_auth() {
|
||||
codex_model_provider_info::set_provider_keyring_store_for_testing(std::sync::Arc::new(
|
||||
codex_keyring_store::tests::MockKeyringStore::default(),
|
||||
));
|
||||
codex_model_provider_info::save_provider_api_key("auth-tests-keyring", "keyring-secret")
|
||||
.expect("store key");
|
||||
let mut provider =
|
||||
create_oss_provider_with_base_url("http://192.0.2.10:8080/v1", WireApi::Responses);
|
||||
provider.api_key = Some(codex_model_provider_info::ProviderApiKeySource::Keyring);
|
||||
provider.keyring_account = Some(codex_model_provider_info::provider_api_key_keyring_account(
|
||||
"auth-tests-keyring",
|
||||
));
|
||||
let ambient_auth = CodexAuth::from_api_key("ambient-stored-key");
|
||||
|
||||
let headers = resolve_provider_auth(Some(&ambient_auth), &provider)
|
||||
.expect("auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
headers.get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer keyring-secret"))
|
||||
);
|
||||
assert_eq!(headers.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_manager_provider_follows_reloads_and_logouts() {
|
||||
let codex_home = test_codex_home();
|
||||
save_ephemeral_auth(&codex_home, api_key_auth_json("first-key"));
|
||||
let auth_manager = Arc::new(
|
||||
AuthManager::new(
|
||||
codex_home.clone(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let expected_auth = auth_manager
|
||||
.auth_cached()
|
||||
.expect("initial auth should be cached");
|
||||
let provider = auth_provider_from_auth_manager(Arc::clone(&auth_manager), &expected_auth);
|
||||
let initial_headers = provider
|
||||
.apply_auth_headers(HeaderMap::new())
|
||||
.await
|
||||
.expect("initial auth headers");
|
||||
|
||||
assert_eq!(
|
||||
provider.to_auth_headers().unwrap().get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer first-key"))
|
||||
);
|
||||
|
||||
save_ephemeral_auth(&codex_home, api_key_auth_json("reloaded-key"));
|
||||
|
||||
// Ordinary requests retain the manager's cache until a reload runs.
|
||||
assert_eq!(
|
||||
provider
|
||||
.apply_auth_headers(HeaderMap::new())
|
||||
.await
|
||||
.expect("cached auth headers"),
|
||||
initial_headers
|
||||
);
|
||||
// Stored API keys cannot be refreshed after a 401.
|
||||
assert!(!provider.refresh_after_unauthorized(initial_headers).await);
|
||||
|
||||
auth_manager.reload().await;
|
||||
let resolved_headers = provider
|
||||
.apply_auth_headers(HeaderMap::new())
|
||||
.await
|
||||
.expect("managed auth headers should resolve");
|
||||
assert_eq!(
|
||||
resolved_headers.get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer reloaded-key"))
|
||||
);
|
||||
|
||||
// A record without a usable credential (logged out) never falls back to stale headers.
|
||||
save_ephemeral_auth(
|
||||
&codex_home,
|
||||
AuthDotJson {
|
||||
auth_mode: None,
|
||||
openai_api_key: None,
|
||||
},
|
||||
);
|
||||
assert!(!provider.refresh_after_unauthorized(resolved_headers).await);
|
||||
auth_manager.reload().await;
|
||||
|
||||
assert!(matches!(
|
||||
provider.to_auth_headers(),
|
||||
Err(AuthError::Transient(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
provider.apply_auth_headers(HeaderMap::new()).await,
|
||||
Err(AuthError::Transient(_))
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use codex_api::AuthProvider;
|
||||
use codex_login::auth::is_fedramp_api_key;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
|
||||
@@ -7,22 +6,16 @@ use http::HeaderValue;
|
||||
#[derive(Clone, Default)]
|
||||
pub struct BearerAuthProvider {
|
||||
pub token: Option<String>,
|
||||
pub is_fedramp_account: bool,
|
||||
}
|
||||
|
||||
impl BearerAuthProvider {
|
||||
pub fn new(token: String) -> Self {
|
||||
let is_fedramp_account = is_fedramp_api_key(&token);
|
||||
Self {
|
||||
token: Some(token),
|
||||
is_fedramp_account,
|
||||
}
|
||||
Self { token: Some(token) }
|
||||
}
|
||||
|
||||
pub fn for_test(token: Option<&str>) -> Self {
|
||||
Self {
|
||||
token: token.map(str::to_string),
|
||||
is_fedramp_account: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,9 +27,6 @@ impl AuthProvider for BearerAuthProvider {
|
||||
{
|
||||
let _ = headers.insert(http::header::AUTHORIZATION, header);
|
||||
}
|
||||
if self.is_fedramp_account {
|
||||
let _ = headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ use pretty_assertions::assert_eq;
|
||||
fn bearer_auth_provider_reports_when_auth_header_will_attach() {
|
||||
let auth = BearerAuthProvider {
|
||||
token: Some("access-token".to_string()),
|
||||
is_fedramp_account: false,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
@@ -36,19 +35,12 @@ fn bearer_auth_provider_adds_auth_headers() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_auth_provider_adds_fedramp_routing_header_for_fedramp_accounts() {
|
||||
let auth = BearerAuthProvider {
|
||||
token: Some("access-token".to_string()),
|
||||
is_fedramp_account: true,
|
||||
};
|
||||
fn bearer_auth_provider_never_adds_openai_routing_headers() {
|
||||
let auth = BearerAuthProvider::new("sk-proj-fedramp-synthetic-test-key".to_string());
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
auth.add_auth_headers(&mut headers).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("X-OpenAI-Fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("true")
|
||||
);
|
||||
assert_eq!(headers.get("X-OpenAI-Fedramp"), None);
|
||||
assert_eq!(headers.len(), 1);
|
||||
}
|
||||
|
||||
@@ -31,8 +31,7 @@ impl Default for ProviderCapabilities {
|
||||
impl ProviderCapabilities {
|
||||
pub(crate) fn from_config(info: &ModelProviderInfo) -> Self {
|
||||
let defaults = Self {
|
||||
remote_compaction: if info.is_openai()
|
||||
|| is_azure_responses_provider(&info.name, info.base_url.as_deref())
|
||||
remote_compaction: if is_azure_responses_provider(&info.name, info.base_url.as_deref())
|
||||
{
|
||||
RemoteCompactionSupport::V2
|
||||
} else {
|
||||
|
||||
@@ -7,7 +7,7 @@ use pretty_assertions::assert_eq;
|
||||
fn capability_overrides_preserve_unspecified_provider_defaults() {
|
||||
for info in [
|
||||
ModelProviderInfo::default(),
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
ModelProviderInfo {
|
||||
name: "Azure".to_string(),
|
||||
..Default::default()
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
//! Resolves ChatGPT backend defaults from the credentials used for a request.
|
||||
//! Explicit endpoints remain authoritative across credential changes.
|
||||
|
||||
use codex_login::CodexAuth;
|
||||
|
||||
pub const DEFAULT_CHATGPT_BASE_URL: &str = "https://chatgpt.com/backend-api/";
|
||||
const FEDRAMP_CHATGPT_BASE_URL: &str = "https://gov.chatgpt.com/backend-api/";
|
||||
|
||||
/// A backend endpoint that retains whether configuration supplied an override.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ChatgptBaseUrl {
|
||||
#[default]
|
||||
Default,
|
||||
Configured(String),
|
||||
}
|
||||
|
||||
impl ChatgptBaseUrl {
|
||||
/// Resolve with the same captured credentials that will authenticate the request.
|
||||
pub fn resolve(&self, auth: &CodexAuth) -> &str {
|
||||
match self {
|
||||
Self::Configured(url) => url,
|
||||
Self::Default if auth.is_api_key_auth() && auth.is_fedramp_account() => {
|
||||
FEDRAMP_CHATGPT_BASE_URL
|
||||
}
|
||||
Self::Default => DEFAULT_CHATGPT_BASE_URL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ChatgptBaseUrl {
|
||||
fn from(url: String) -> Self {
|
||||
Self::Configured(url)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for ChatgptBaseUrl {
|
||||
fn from(url: &str) -> Self {
|
||||
Self::Configured(url.to_owned())
|
||||
}
|
||||
}
|
||||
@@ -1,337 +0,0 @@
|
||||
use codex_models_manager::ModelsManagerConfig;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::openai_models::ApplyPatchToolType;
|
||||
use codex_protocol::openai_models::ModelOrigin;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vertex_base_url_defaults_to_global_location() {
|
||||
assert_eq!(
|
||||
vertex_base_url(
|
||||
&ModelProviderInfo::default(),
|
||||
Some("example-project"),
|
||||
/*environment_location*/ None
|
||||
)
|
||||
.expect("project should resolve a Vertex endpoint"),
|
||||
"https://aiplatform.googleapis.com/v1/projects/example-project/locations/global/publishers/openai/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_base_url_uses_explicit_location() {
|
||||
assert_eq!(
|
||||
vertex_base_url(
|
||||
&ModelProviderInfo::default(),
|
||||
Some("example-project"),
|
||||
Some("us-central1")
|
||||
)
|
||||
.expect("project and location should resolve a Vertex endpoint"),
|
||||
"https://aiplatform.googleapis.com/v1/projects/example-project/locations/us-central1/publishers/openai/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_base_url_explains_missing_project() {
|
||||
let error = vertex_base_url(
|
||||
&ModelProviderInfo::default(),
|
||||
/*environment_project*/ None,
|
||||
/*environment_location*/ None,
|
||||
)
|
||||
.expect_err("missing project should be rejected");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"Missing environment variable: `GOOGLE_CLOUD_PROJECT`. Set model_providers.gcp.project_id or GOOGLE_CLOUD_PROJECT to your Google Cloud project ID, or configure model_providers.gcp.base_url."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_base_url_rejects_path_components() {
|
||||
let error = vertex_base_url(
|
||||
&ModelProviderInfo::default(),
|
||||
Some("example-project/other"),
|
||||
/*environment_location*/ None,
|
||||
)
|
||||
.expect_err("project must not add endpoint path components");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"GOOGLE_CLOUD_PROJECT must be non-empty and contain only ASCII letters, digits, and hyphens"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_vertex_endpoint_resolves_each_field_independently() {
|
||||
for (project_id, location, expected) in [
|
||||
(
|
||||
Some("configured-project"),
|
||||
Some("us-east4"),
|
||||
"https://aiplatform.googleapis.com/v1/projects/configured-project/locations/us-east4/publishers/openai/v1",
|
||||
),
|
||||
(
|
||||
Some("configured-project"),
|
||||
None,
|
||||
"https://aiplatform.googleapis.com/v1/projects/configured-project/locations/us-central1/publishers/openai/v1",
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some("us-east4"),
|
||||
"https://aiplatform.googleapis.com/v1/projects/environment-project/locations/us-east4/publishers/openai/v1",
|
||||
),
|
||||
] {
|
||||
let info = ModelProviderInfo {
|
||||
project_id: project_id.map(str::to_string),
|
||||
location: location.map(str::to_string),
|
||||
..ModelProviderInfo::default()
|
||||
};
|
||||
assert_eq!(
|
||||
vertex_base_url(&info, Some("environment-project"), Some("us-central1"))
|
||||
.expect("configured fields should take precedence over environment values"),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_configured_project_does_not_fall_back_to_environment() {
|
||||
let info = ModelProviderInfo {
|
||||
project_id: Some(String::new()),
|
||||
..ModelProviderInfo::default()
|
||||
};
|
||||
let error = vertex_base_url(&info, Some("environment-project"), Some("us-central1"))
|
||||
.expect_err("invalid explicit config should not fall back to environment values");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"model_providers.gcp.project_id must be non-empty and contain only ASCII letters, digits, and hyphens"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_project_and_location_build_api_provider() {
|
||||
let provider = GcpModelProvider::new(
|
||||
ModelProviderInfo {
|
||||
project_id: Some("configured-project".to_string()),
|
||||
location: Some("us-east4".to_string()),
|
||||
..ModelProviderInfo::create_gcp_provider()
|
||||
},
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.api_provider()
|
||||
.await
|
||||
.expect("configured endpoint should build")
|
||||
.base_url,
|
||||
"https://aiplatform.googleapis.com/v1/projects/configured-project/locations/us-east4/publishers/openai/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_base_url_bypasses_project_discovery() {
|
||||
let mut provider_info = ModelProviderInfo::create_gcp_provider();
|
||||
provider_info.base_url = Some("https://vertex.example.com/v1".to_string());
|
||||
provider_info.auth = Some(ModelProviderAuthInfo {
|
||||
command: "print-token".to_string(),
|
||||
args: Vec::new(),
|
||||
timeout_ms: std::num::NonZeroU64::new(5_000).expect("timeout should be non-zero"),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: std::env::current_dir()
|
||||
.expect("current directory should be available")
|
||||
.try_into()
|
||||
.expect("current directory should be absolute"),
|
||||
});
|
||||
provider_info.project_id = Some("configured-project".to_string());
|
||||
provider_info.location = Some("us-east4".to_string());
|
||||
let provider = GcpModelProvider::new(provider_info, /*auth_manager*/ None);
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.api_provider()
|
||||
.await
|
||||
.expect("configured endpoint should build")
|
||||
.base_url,
|
||||
"https://vertex.example.com/v1"
|
||||
);
|
||||
assert!(
|
||||
provider
|
||||
.auth_manager()
|
||||
.expect("GCP should create a command-backed auth manager")
|
||||
.has_external_auth()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_files_scope_token_caches_and_refreshes() {
|
||||
let tempdir = tempfile::tempdir().unwrap();
|
||||
let first_file = tempdir.path().join("first credentials.json");
|
||||
let second_file = tempdir.path().join("second credentials.json");
|
||||
std::fs::write(&first_file, "first-token").unwrap();
|
||||
std::fs::write(&second_file, "second-token").unwrap();
|
||||
|
||||
#[cfg(unix)]
|
||||
let (command, args) = (
|
||||
"sh".to_string(),
|
||||
vec![
|
||||
"-c".into(),
|
||||
"cat \"$GOOGLE_APPLICATION_CREDENTIALS\"".into(),
|
||||
],
|
||||
);
|
||||
#[cfg(windows)]
|
||||
let (command, args) = {
|
||||
std::fs::write(
|
||||
tempdir.path().join("read-token.cmd"),
|
||||
"@type \"%GOOGLE_APPLICATION_CREDENTIALS%\"\r\n",
|
||||
)
|
||||
.unwrap();
|
||||
(
|
||||
"cmd.exe".to_string(),
|
||||
vec!["/d".into(), "/c".into(), r".\read-token.cmd".into()],
|
||||
)
|
||||
};
|
||||
let mut first_info = ModelProviderInfo::create_gcp_provider();
|
||||
first_info.auth = Some(ModelProviderAuthInfo {
|
||||
command,
|
||||
args,
|
||||
timeout_ms: std::num::NonZeroU64::new(5_000).unwrap(),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: tempdir.path().try_into().unwrap(),
|
||||
});
|
||||
first_info.credential_file = Some(first_file.clone());
|
||||
let mut second_info = first_info.clone();
|
||||
second_info.credential_file = Some(second_file);
|
||||
let primary = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("openai-key"));
|
||||
let first = GcpModelProvider::new(first_info, Some(Arc::clone(&primary)));
|
||||
let second = GcpModelProvider::new(second_info, Some(primary));
|
||||
|
||||
assert_eq!(
|
||||
(first.auth().await, second.auth().await),
|
||||
(
|
||||
Some(CodexAuth::from_api_key("first-token")),
|
||||
Some(CodexAuth::from_api_key("second-token")),
|
||||
),
|
||||
);
|
||||
std::fs::write(first_file, "refreshed-token").unwrap();
|
||||
assert_eq!(
|
||||
first.auth().await,
|
||||
Some(CodexAuth::from_api_key("first-token"))
|
||||
);
|
||||
first
|
||||
.auth_manager()
|
||||
.unwrap()
|
||||
.unauthorized_recovery()
|
||||
.next()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(first.auth().await, second.auth().await),
|
||||
(
|
||||
Some(CodexAuth::from_api_key("refreshed-token")),
|
||||
Some(CodexAuth::from_api_key("second-token")),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bundled_vertex_models_filter_catalog_and_normalize_unsupported_tool_metadata() {
|
||||
let provider = GcpModelProvider::new(
|
||||
ModelProviderInfo::create_gcp_provider(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
let manager = provider.models_manager(
|
||||
PathBuf::from("unused-codex-home"),
|
||||
/*config_model_catalog*/ None,
|
||||
);
|
||||
let bundled_models = codex_models_manager::bundled_models_response()
|
||||
.expect("bundled model catalog should deserialize")
|
||||
.models;
|
||||
let mut expected: Vec<_> = ["gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-luna"]
|
||||
.into_iter()
|
||||
.map(|slug| {
|
||||
bundled_models
|
||||
.iter()
|
||||
.find(|model| model.slug == slug)
|
||||
.expect("bundled catalog should contain the supported Vertex model")
|
||||
.clone()
|
||||
})
|
||||
.collect();
|
||||
for model in &mut expected {
|
||||
model.use_responses_lite = false;
|
||||
model.tool_mode = Some(ToolMode::Direct);
|
||||
model.apply_patch_tool_type = None;
|
||||
}
|
||||
|
||||
assert_eq!(manager.get_remote_models().await, expected);
|
||||
assert_eq!(
|
||||
manager
|
||||
.try_list_models()
|
||||
.expect("static models should be available")
|
||||
.into_iter()
|
||||
.map(|model| (model.model, model.show_in_picker))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("gpt-6.1-sol".to_string(), true),
|
||||
("gpt-6-astra".to_string(), true),
|
||||
("gpt-6-luna".to_string(), true),
|
||||
("gpt-6.1-terra".to_string(), true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_vertex_models_filter_catalog_and_normalize_tool_metadata_without_cache() {
|
||||
for model in ["gpt-6.1-sol", "gpt-6.1-terra"] {
|
||||
let provider = GcpModelProvider::new(
|
||||
ModelProviderInfo::create_gcp_provider(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
let mut configured_model = codex_models_manager::bundled_models_response()
|
||||
.expect("bundled model catalog should deserialize")
|
||||
.models
|
||||
.into_iter()
|
||||
.find(|info| info.slug == model)
|
||||
.expect("bundled model catalog should contain the supported Vertex model");
|
||||
configured_model.use_responses_lite = true;
|
||||
configured_model.tool_mode = Some(ToolMode::CodeModeOnly);
|
||||
configured_model.apply_patch_tool_type = Some(ApplyPatchToolType::Freeform);
|
||||
configured_model.multi_agent_version = Some(MultiAgentVersion::V2);
|
||||
let mut expected_model = configured_model.clone();
|
||||
expected_model.use_responses_lite = false;
|
||||
expected_model.tool_mode = Some(ToolMode::Direct);
|
||||
expected_model.apply_patch_tool_type = None;
|
||||
let mut unsupported_model = configured_model.clone();
|
||||
unsupported_model.slug = "gpt-6-sol".to_string();
|
||||
let mut unsupported_variant = configured_model.clone();
|
||||
unsupported_variant.slug = format!("{model}-extra");
|
||||
let manager = provider.models_manager_without_cache(Some(ModelsResponse {
|
||||
models: vec![unsupported_model, configured_model, unsupported_variant],
|
||||
}));
|
||||
|
||||
assert_eq!(manager.get_remote_models().await, vec![expected_model]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_vertex_models_use_static_catalog_fallback() {
|
||||
let provider = GcpModelProvider::new(
|
||||
ModelProviderInfo::create_gcp_provider(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
let manager = provider.models_manager(
|
||||
PathBuf::from("unused-codex-home"),
|
||||
Some(ModelsResponse::default()),
|
||||
);
|
||||
|
||||
let model = manager
|
||||
.get_model_info("vertex-test-model", &ModelsManagerConfig::default())
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
(model.slug.as_str(), model.origin),
|
||||
("vertex-test-model", ModelOrigin::Synthetic)
|
||||
);
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
//! Vertex AI provider routing, command-backed credentials, and supported model capabilities.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_api::Provider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_models_manager::manager::StaticModelsManager;
|
||||
use codex_protocol::account::ProviderAccount;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::EnvVarError;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_protocol::openai_models::ToolMode;
|
||||
|
||||
use crate::ProviderCapabilities;
|
||||
use crate::RemoteCompactionSupport;
|
||||
use crate::auth::auth_manager_for_provider;
|
||||
use crate::auth::resolve_provider_auth;
|
||||
use crate::provider::ModelProvider;
|
||||
use crate::provider::ModelProviderFuture;
|
||||
use crate::provider::ProviderAccountResult;
|
||||
use crate::provider::ProviderAccountState;
|
||||
|
||||
const GOOGLE_CLOUD_PROJECT_ENV_VAR: &str = "GOOGLE_CLOUD_PROJECT";
|
||||
const GOOGLE_CLOUD_LOCATION_ENV_VAR: &str = "GOOGLE_CLOUD_LOCATION";
|
||||
const DEFAULT_GOOGLE_CLOUD_LOCATION: &str = "global";
|
||||
|
||||
/// Runtime provider for Google Cloud Vertex AI's OpenAI-compatible endpoint.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct GcpModelProvider {
|
||||
info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
}
|
||||
|
||||
impl GcpModelProvider {
|
||||
pub(crate) fn new(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
) -> Self {
|
||||
let auth_manager = auth_manager_for_provider(auth_manager, &provider_info);
|
||||
Self {
|
||||
info: provider_info,
|
||||
auth_manager,
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth(&self) -> Option<CodexAuth> {
|
||||
match self.auth_manager.as_ref() {
|
||||
Some(auth_manager) => auth_manager.auth().await,
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn api_provider(&self) -> Result<Provider> {
|
||||
let mut provider_info = self.info.clone();
|
||||
provider_info.base_url = self.runtime_base_url().await?;
|
||||
provider_info.to_api_provider()
|
||||
}
|
||||
|
||||
async fn runtime_base_url(&self) -> Result<Option<String>> {
|
||||
if let Some(base_url) = self.info.base_url.clone() {
|
||||
return Ok(Some(base_url));
|
||||
}
|
||||
|
||||
let project = std::env::var(GOOGLE_CLOUD_PROJECT_ENV_VAR).ok();
|
||||
let location = std::env::var(GOOGLE_CLOUD_LOCATION_ENV_VAR).ok();
|
||||
vertex_base_url(&self.info, project.as_deref(), location.as_deref()).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelProvider for GcpModelProvider {
|
||||
fn info(&self) -> &ModelProviderInfo {
|
||||
&self.info
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> ProviderCapabilities {
|
||||
ProviderCapabilities {
|
||||
reasoning_summaries: false,
|
||||
web_search: false,
|
||||
external_web_access: false,
|
||||
remote_compaction: RemoteCompactionSupport::V2,
|
||||
}
|
||||
}
|
||||
|
||||
fn approval_review_preferred_model(&self) -> &'static str {
|
||||
// TODO: Switch Guardian to gpt-5.6-luna once it is available on GCP.
|
||||
"gpt-6-luna"
|
||||
}
|
||||
|
||||
fn memory_extraction_preferred_model(&self) -> &'static str {
|
||||
"gpt-6-luna"
|
||||
}
|
||||
|
||||
fn memory_consolidation_preferred_model(&self) -> &'static str {
|
||||
"gpt-6.1-terra"
|
||||
}
|
||||
|
||||
fn auth_manager(&self) -> Option<Arc<AuthManager>> {
|
||||
self.auth_manager.clone()
|
||||
}
|
||||
|
||||
fn auth(&self) -> ModelProviderFuture<'_, Option<CodexAuth>> {
|
||||
Box::pin(GcpModelProvider::auth(self))
|
||||
}
|
||||
|
||||
fn account_state(&self) -> ProviderAccountResult {
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::Gcp),
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn api_provider(&self) -> ModelProviderFuture<'_, Result<Provider>> {
|
||||
Box::pin(GcpModelProvider::api_provider(self))
|
||||
}
|
||||
|
||||
fn api_auth(&self) -> ModelProviderFuture<'_, Result<SharedAuthProvider>> {
|
||||
Box::pin(async move {
|
||||
let auth = self.auth().await.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(
|
||||
"Google Cloud credentials are unavailable or expired. Run \
|
||||
`gcloud auth application-default login` to reauthenticate."
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
resolve_provider_auth(Some(&auth), &self.info)
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_base_url(&self) -> ModelProviderFuture<'_, Result<Option<String>>> {
|
||||
Box::pin(GcpModelProvider::runtime_base_url(self))
|
||||
}
|
||||
|
||||
fn models_manager(
|
||||
&self,
|
||||
_codex_home: PathBuf,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager {
|
||||
self.models_manager_without_cache(config_model_catalog)
|
||||
}
|
||||
|
||||
fn models_manager_without_cache(
|
||||
&self,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager {
|
||||
let origin = if config_model_catalog.is_some() {
|
||||
codex_models_manager::ModelOrigin::ExplicitConfig
|
||||
} else {
|
||||
codex_models_manager::ModelOrigin::Provider
|
||||
};
|
||||
let mut model_catalog = config_model_catalog
|
||||
.or_else(|| codex_models_manager::bundled_models_response().ok())
|
||||
.unwrap_or_default();
|
||||
model_catalog.models.retain(|model| {
|
||||
matches!(
|
||||
model.slug.as_str(),
|
||||
"gpt-6-astra" | "gpt-6-luna" | "gpt-6.1-sol" | "gpt-6.1-terra"
|
||||
)
|
||||
});
|
||||
// Vertex supports function tools, namespaces, and client-side tool search, but not
|
||||
// Responses Lite or custom tools.
|
||||
for model in &mut model_catalog.models {
|
||||
model.use_responses_lite = false;
|
||||
model.tool_mode = Some(ToolMode::Direct);
|
||||
model.apply_patch_tool_type = None;
|
||||
}
|
||||
Arc::new(StaticModelsManager::new(
|
||||
self.auth_manager.clone(),
|
||||
model_catalog,
|
||||
origin,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn vertex_base_url(
|
||||
info: &ModelProviderInfo,
|
||||
environment_project: Option<&str>,
|
||||
environment_location: Option<&str>,
|
||||
) -> Result<String> {
|
||||
let project = info
|
||||
.project_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.or_else(|| {
|
||||
environment_project
|
||||
.map(str::trim)
|
||||
.filter(|project| !project.is_empty())
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
CodexErr::EnvVar(EnvVarError {
|
||||
var: GOOGLE_CLOUD_PROJECT_ENV_VAR.to_string(),
|
||||
instructions: Some(
|
||||
"Set model_providers.gcp.project_id or GOOGLE_CLOUD_PROJECT to your Google \
|
||||
Cloud project ID, or configure model_providers.gcp.base_url."
|
||||
.to_string(),
|
||||
),
|
||||
})
|
||||
})?;
|
||||
let location = info
|
||||
.location
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.or_else(|| {
|
||||
environment_location
|
||||
.map(str::trim)
|
||||
.filter(|location| !location.is_empty())
|
||||
})
|
||||
.unwrap_or(DEFAULT_GOOGLE_CLOUD_LOCATION);
|
||||
|
||||
for (name, value) in [
|
||||
(
|
||||
if info.project_id.is_some() {
|
||||
"model_providers.gcp.project_id"
|
||||
} else {
|
||||
GOOGLE_CLOUD_PROJECT_ENV_VAR
|
||||
},
|
||||
project,
|
||||
),
|
||||
(
|
||||
if info.location.is_some() {
|
||||
"model_providers.gcp.location"
|
||||
} else {
|
||||
GOOGLE_CLOUD_LOCATION_ENV_VAR
|
||||
},
|
||||
location,
|
||||
),
|
||||
] {
|
||||
if value.is_empty()
|
||||
|| !value
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_alphanumeric() || character == '-')
|
||||
{
|
||||
return Err(CodexErr::InvalidRequest(format!(
|
||||
"{name} must be non-empty and contain only ASCII letters, digits, and hyphens"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(format!(
|
||||
"https://aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/openai/v1"
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gcp_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,14 +1,11 @@
|
||||
mod amazon_bedrock;
|
||||
mod auth;
|
||||
mod bearer_auth_provider;
|
||||
mod capabilities;
|
||||
mod catalog_factory;
|
||||
mod chatgpt_base_url;
|
||||
mod combined_auth;
|
||||
mod connection_key;
|
||||
mod gateway_auth;
|
||||
mod gateway_export;
|
||||
mod gcp;
|
||||
mod models_endpoint;
|
||||
mod models_identity;
|
||||
mod provider;
|
||||
@@ -17,9 +14,6 @@ mod request_setup;
|
||||
mod shared_state;
|
||||
pub mod test_support;
|
||||
|
||||
pub use amazon_bedrock::is_amazon_bedrock_gov_cloud_region;
|
||||
pub use amazon_bedrock::is_supported_amazon_bedrock_region;
|
||||
pub use amazon_bedrock::resolve_amazon_bedrock_region;
|
||||
pub use auth::ProviderAuthContext;
|
||||
pub use auth::ResolvedProviderAuth;
|
||||
pub use auth::auth_provider_for_request;
|
||||
@@ -30,14 +24,9 @@ pub use bearer_auth_provider::BearerAuthProvider;
|
||||
pub use bearer_auth_provider::BearerAuthProvider as CoreAuthProvider;
|
||||
pub use capabilities::ProviderCapabilities;
|
||||
pub use catalog_factory::ModelCatalogFactory;
|
||||
pub use connection_key::ResponsesConnectionKey;
|
||||
pub use chatgpt_base_url::ChatgptBaseUrl;
|
||||
pub use chatgpt_base_url::DEFAULT_CHATGPT_BASE_URL;
|
||||
pub use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
pub use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
pub use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
pub use codex_model_provider_info::RemoteCompactionSupport;
|
||||
pub use codex_protocol::account::ProviderAccount;
|
||||
pub use connection_key::ResponsesConnectionKey;
|
||||
pub use gateway_auth::GatewayAuthManager;
|
||||
pub use provider::ModelProvider;
|
||||
pub use provider::ModelProviderFuture;
|
||||
|
||||
@@ -63,8 +63,8 @@ impl ModelsTransportBuilder for CaptureModelsUrl {
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_discovery_respects_provider_routing_and_never_uses_codex_backend() {
|
||||
// There is no default endpoint (and no FedRAMP rerouting): only configured base URLs.
|
||||
for (api_key, name, base_url, inference_url) in [
|
||||
("test-api-key", "OpenAI", None, "https://api.openai.com/v1"),
|
||||
(
|
||||
"test-api-key",
|
||||
"OpenAI",
|
||||
@@ -77,37 +77,19 @@ async fn api_key_discovery_respects_provider_routing_and_never_uses_codex_backen
|
||||
Some("https://example.openai.azure.com/openai/v1"),
|
||||
"https://example.openai.azure.com/openai/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
Some("https://example.com/codex"),
|
||||
"https://example.com/codex",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
"Azure",
|
||||
None,
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
] {
|
||||
let capture = Arc::new(CaptureModelsUrl(Mutex::new(/*t*/ None)));
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key(api_key));
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo {
|
||||
name: name.to_string(),
|
||||
..ModelProviderInfo::create_openai_provider(base_url.map(str::to_string))
|
||||
..ModelProviderInfo::create_responses_provider("mock", base_url.map(str::to_string))
|
||||
},
|
||||
auth_manager: Some(auth.clone()),
|
||||
gateway_auth_manager: None,
|
||||
@@ -137,21 +119,17 @@ async fn api_key_discovery_respects_provider_routing_and_never_uses_codex_backen
|
||||
#[tokio::test]
|
||||
async fn provider_api_key_without_endpoint_overrides_never_contacts_codex_backend() {
|
||||
for (api_key, auth, inference_url) in [
|
||||
("provider-key", None, "https://api.openai.com/v1"),
|
||||
("provider-key", None, ()),
|
||||
(
|
||||
"provider-key",
|
||||
Some(CodexAuth::from_api_key("sk-proj-fedramp-ambient-key")),
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-provider-key",
|
||||
None,
|
||||
"https://gov.api.openai.com/v1",
|
||||
(),
|
||||
),
|
||||
("sk-proj-fedramp-provider-key", None, ()),
|
||||
(
|
||||
"sk-svcacct-fedramp-provider-key",
|
||||
Some(CodexAuth::from_api_key("legacy-ambient-key")),
|
||||
"https://gov.api.openai.com/v1",
|
||||
(),
|
||||
),
|
||||
] {
|
||||
let capture = Arc::new(CaptureModelsUrl(Mutex::new(/*t*/ None)));
|
||||
@@ -159,7 +137,7 @@ async fn provider_api_key_without_endpoint_overrides_never_contacts_codex_backen
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo {
|
||||
experimental_bearer_token: Some(api_key.into()),
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
..ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None)
|
||||
},
|
||||
auth_manager: auth_manager.clone(),
|
||||
gateway_auth_manager: None,
|
||||
@@ -177,11 +155,11 @@ async fn provider_api_key_without_endpoint_overrides_never_contacts_codex_backen
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
// Without a base_url nothing is contacted: neither the Codex backend nor a default
|
||||
// OpenAI endpoint.
|
||||
let () = inference_url;
|
||||
assert_eq!(*capture.0.lock().unwrap(), None);
|
||||
assert_eq!(
|
||||
provider.api_provider().await.unwrap().base_url,
|
||||
inference_url
|
||||
);
|
||||
assert!(provider.api_provider().await.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +176,10 @@ fn provider_info_with_command_auth() -> ModelProviderInfo {
|
||||
.expect("current dir should be absolute"),
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
..ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("https://llm.example/v1".to_string()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,18 +193,19 @@ fn command_auth_provider_reports_command_auth_without_cached_auth() {
|
||||
|
||||
assert!(endpoint.has_command_auth());
|
||||
let auth = CodexAuth::from_api_key("sk-proj-fedramp-command-key");
|
||||
// FedRAMP-looking keys never reroute a configured endpoint.
|
||||
assert_eq!(
|
||||
resolve_api_provider(&endpoint.provider_info, Some(&auth))
|
||||
.unwrap()
|
||||
.base_url,
|
||||
"https://api.openai.com/v1"
|
||||
"https://llm.example/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_without_command_auth_reports_no_command_auth() {
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
/*auth_manager*/ None,
|
||||
/*gateway_auth_manager*/ None,
|
||||
);
|
||||
@@ -246,7 +228,7 @@ async fn model_request_uses_request_time_proxy_policy_and_exact_url() {
|
||||
|
||||
let observed_request = Arc::new(Mutex::new(None));
|
||||
let endpoint = OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo::create_openai_provider(Some(server.uri())),
|
||||
provider_info: ModelProviderInfo::create_responses_provider("mock", Some(server.uri())),
|
||||
auth_manager: None,
|
||||
gateway_auth_manager: None,
|
||||
transport_builder: Arc::new(RecordingTransportBuilder {
|
||||
@@ -286,7 +268,8 @@ async fn model_discovery_enforces_managed_residency_over_provider_headers() {
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let mut provider_info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
let mut provider_info =
|
||||
ModelProviderInfo::create_responses_provider("mock", Some(server.uri()));
|
||||
provider_info.http_headers = Some(std::collections::HashMap::from([(
|
||||
RESIDENCY_HEADER_NAME.to_string(),
|
||||
"eu".into(),
|
||||
@@ -479,7 +462,10 @@ async fn explicit_catalog_reuses_auth_headers_and_query_parameters() {
|
||||
"us".into(),
|
||||
),
|
||||
])),
|
||||
..ModelProviderInfo::create_openai_provider(Some(format!("{}/v1", server.uri())))
|
||||
..ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some(format!("{}/v1", server.uri())),
|
||||
)
|
||||
};
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
|
||||
@@ -526,6 +512,7 @@ async fn explicit_catalog_requires_unique_nonempty_slugs() {
|
||||
.await;
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
ModelProviderInfo {
|
||||
base_url: Some(server.uri()),
|
||||
model_catalog_url: Some(format!("{}/codex/models", server.uri()).into()),
|
||||
..ModelProviderInfo::default()
|
||||
},
|
||||
|
||||
@@ -21,7 +21,7 @@ async fn catalog_deadline_returns_request_timeout() {
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
ModelProviderInfo::create_openai_provider(Some(server.uri())),
|
||||
ModelProviderInfo::create_responses_provider("mock", Some(server.uri())),
|
||||
/*auth_manager*/ None,
|
||||
/*gateway_auth_manager*/ None,
|
||||
);
|
||||
|
||||
@@ -5,7 +5,8 @@ use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn cache_identity_tracks_credential_kind_and_value() {
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let mut provider =
|
||||
ModelProviderInfo::create_responses_provider("mock", Some("https://one.example/v1".into()));
|
||||
// The endpoint residency test temporarily sets the process default to US.
|
||||
provider.http_headers = Some(std::collections::HashMap::from([(
|
||||
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
|
||||
@@ -34,7 +35,8 @@ fn cache_identity_tracks_credential_kind_and_value() {
|
||||
#[test]
|
||||
fn cache_identity_tracks_provider_routing_and_effective_api_credentials() {
|
||||
let auth = CodexAuth::from_api_key("sk-proj-fedramp-synthetic-test-key");
|
||||
let provider = ModelProviderInfo::create_openai_provider(Some("https://one.example/v1".into()));
|
||||
let provider =
|
||||
ModelProviderInfo::create_responses_provider("mock", Some("https://one.example/v1".into()));
|
||||
let key = identity(&provider, Some(&auth)).unwrap();
|
||||
let other_key = CodexAuth::from_api_key("sk-proj-fedramp-rotated-test-key");
|
||||
assert_ne!(identity(&provider, Some(&other_key)).unwrap(), key);
|
||||
@@ -51,23 +53,15 @@ fn cache_identity_tracks_provider_routing_and_effective_api_credentials() {
|
||||
)]));
|
||||
assert_ne!(identity(&other_provider, Some(&auth)).unwrap(), key);
|
||||
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
// Keep identities stable while the endpoint residency test runs in parallel.
|
||||
provider.http_headers = Some(std::collections::HashMap::from([(
|
||||
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
|
||||
"us".into(),
|
||||
)]));
|
||||
let key = identity(&provider, Some(&auth)).unwrap();
|
||||
provider.base_url = Some("https://gov.api.openai.com/v1".into());
|
||||
assert_eq!(identity(&provider, Some(&auth)).unwrap(), key);
|
||||
provider.base_url = Some("https://api.openai.com/v1".into());
|
||||
assert_ne!(identity(&provider, Some(&auth)).unwrap(), key);
|
||||
// A provider without an endpoint has no identity: it is never contacted.
|
||||
let unconfigured = ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None);
|
||||
assert!(identity(&unconfigured, Some(&auth)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_identity_distinguishes_auth_requirements() {
|
||||
let mut provider =
|
||||
ModelProviderInfo::create_openai_provider(Some("https://example.com/v1".into()));
|
||||
ModelProviderInfo::create_responses_provider("mock", Some("https://example.com/v1".into()));
|
||||
let auth = CodexAuth::from_api_key("api-key");
|
||||
let key = identity(&provider, Some(&auth)).unwrap();
|
||||
provider.requires_openai_auth = false;
|
||||
@@ -77,8 +71,10 @@ fn cache_identity_distinguishes_auth_requirements() {
|
||||
#[test]
|
||||
fn cache_identity_tracks_catalog_url() {
|
||||
let auth = CodexAuth::from_api_key("test-key");
|
||||
let mut provider =
|
||||
ModelProviderInfo::create_openai_provider(Some("https://gateway.example/v1".into()));
|
||||
let mut provider = ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("https://gateway.example/v1".into()),
|
||||
);
|
||||
let bundled = identity(&provider, Some(&auth)).unwrap();
|
||||
provider.model_catalog_url = Some("https://gateway.example/catalog-one".into());
|
||||
let first = identity(&provider, Some(&auth)).unwrap();
|
||||
@@ -90,8 +86,10 @@ fn cache_identity_tracks_catalog_url() {
|
||||
|
||||
#[test]
|
||||
fn provider_key_catalog_identity_does_not_depend_on_unused_login() {
|
||||
let mut provider =
|
||||
ModelProviderInfo::create_openai_provider(Some("https://api.openai.com/v1".into()));
|
||||
let mut provider = ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("https://api.openai.com/v1".into()),
|
||||
);
|
||||
// Keep this input stable while the residency test changes the process default.
|
||||
provider.http_headers = Some(std::collections::HashMap::from([(
|
||||
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
|
||||
|
||||
@@ -20,7 +20,7 @@ use wiremock::matchers::path;
|
||||
async fn originator_managers_share_api_key_discovery_policy() {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
let mut provider = ModelProviderInfo::create_responses_provider("mock", Some(server.uri()));
|
||||
provider.model_catalog_url = Some(format!("{}/models", server.uri()).into());
|
||||
provider.http_headers = Some(std::collections::HashMap::from([(
|
||||
codex_model_provider_info::RESIDENCY_HEADER_NAME.to_string(),
|
||||
@@ -97,7 +97,7 @@ async fn originator_managers_share_api_key_discovery_policy() {
|
||||
async fn originator_catalogs_are_isolated_and_reused_from_disk() {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
let mut provider = ModelProviderInfo::create_responses_provider("mock", Some(server.uri()));
|
||||
provider.model_catalog_url = Some(format!("{}/models", server.uri()).into());
|
||||
// The managed-residency test toggles the process-wide US policy. Keep this
|
||||
// provider's cache identity stable whether that policy is enabled or disabled.
|
||||
|
||||
@@ -22,13 +22,10 @@ use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
|
||||
use crate::ProviderCapabilities;
|
||||
use crate::amazon_bedrock::AmazonBedrockModelProvider;
|
||||
use crate::auth::ResolvedProviderAuth;
|
||||
use crate::auth::auth_manager_for_provider;
|
||||
use crate::auth::resolve_provider_auth;
|
||||
use crate::auth::uses_fedramp_api_key;
|
||||
use crate::combined_auth::compose_auth;
|
||||
use crate::gcp::GcpModelProvider;
|
||||
use crate::models_endpoint::OpenAiModelsEndpoint;
|
||||
use crate::request_setup::resolve_request_auth;
|
||||
|
||||
@@ -57,20 +54,11 @@ pub struct ProviderAuthRecoveryMessages {
|
||||
|
||||
/// Error returned when a provider cannot construct its app-visible account state.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProviderAccountError {
|
||||
UnsupportedBedrockApiKeyAuth,
|
||||
}
|
||||
pub enum ProviderAccountError {}
|
||||
|
||||
impl fmt::Display for ProviderAccountError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::UnsupportedBedrockApiKeyAuth => {
|
||||
write!(
|
||||
f,
|
||||
"Bedrock API key auth is only supported by the Amazon Bedrock model provider"
|
||||
)
|
||||
}
|
||||
}
|
||||
fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,8 +72,6 @@ pub const DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL: &str = "codex-auto-review";
|
||||
|
||||
const API_KEY_APPROVAL_REVIEW_PREFERRED_MODEL: &str = "gpt-5.6-luna";
|
||||
|
||||
const FEDRAMP_API_BASE_URL: &str = "https://gov.api.openai.com/v1";
|
||||
|
||||
/// Default model used for memory extraction when a provider does not require a
|
||||
/// backend-specific model ID.
|
||||
pub const DEFAULT_MEMORY_EXTRACTION_PREFERRED_MODEL: &str = "gpt-6-luna";
|
||||
@@ -108,11 +94,8 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
|
||||
|
||||
/// Returns whether the resolved Responses provider may receive internal tool metadata.
|
||||
fn include_internal_metadata(&self, provider: &Provider) -> bool {
|
||||
let _ = provider;
|
||||
self.info().include_internal_metadata
|
||||
|| url::Url::parse(&provider.base_url).ok().is_some_and(|url| {
|
||||
url.scheme() == "https"
|
||||
&& url.host_str() == Some("api.openai.com")
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the provider-owned capability upper bounds.
|
||||
@@ -310,21 +293,17 @@ pub fn resolve_api_provider(
|
||||
info: &ModelProviderInfo,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> codex_protocol::error::Result<Provider> {
|
||||
let mut provider = info.to_api_provider()?;
|
||||
if info.base_url.is_none() && uses_fedramp_api_key(auth, info)? {
|
||||
provider.base_url = FEDRAMP_API_BASE_URL.to_string();
|
||||
}
|
||||
Ok(provider)
|
||||
let _ = auth;
|
||||
info.to_api_provider()
|
||||
}
|
||||
|
||||
/// Whether requests use the credential stored by `codex login --with-api-key` (or supplied
|
||||
/// by a host) rather than provider-owned env, bearer, command, or AWS credentials.
|
||||
/// by a host) rather than provider-owned env, bearer, or command credentials.
|
||||
pub fn provider_uses_stored_auth(provider: &ModelProviderInfo) -> bool {
|
||||
provider.requires_openai_auth
|
||||
&& provider.env_key.is_none()
|
||||
&& provider.experimental_bearer_token.is_none()
|
||||
&& provider.auth.is_none()
|
||||
&& provider.aws.is_none()
|
||||
}
|
||||
|
||||
/// Creates the default model provider for configured provider metadata.
|
||||
@@ -332,12 +311,6 @@ pub fn create_model_provider(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
) -> SharedModelProvider {
|
||||
if provider_info.is_amazon_bedrock() {
|
||||
return Arc::new(AmazonBedrockModelProvider::new(provider_info, auth_manager));
|
||||
}
|
||||
if provider_info.is_gcp() {
|
||||
return Arc::new(GcpModelProvider::new(provider_info, auth_manager));
|
||||
}
|
||||
Arc::new(ConfiguredModelProvider::new(provider_info, auth_manager))
|
||||
}
|
||||
|
||||
@@ -446,9 +419,7 @@ impl ModelProvider for ConfiguredModelProvider {
|
||||
fn api_auth(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<SharedAuthProvider>> {
|
||||
Box::pin(async move {
|
||||
Ok(self.resolve_auth().await?.auth)
|
||||
})
|
||||
Box::pin(async move { Ok(self.resolve_auth().await?.auth) })
|
||||
}
|
||||
|
||||
fn compose_auth(
|
||||
@@ -477,15 +448,11 @@ impl ModelProvider for ConfiguredModelProvider {
|
||||
Some(auth)
|
||||
})
|
||||
.map(|auth| match &auth {
|
||||
CodexAuth::ApiKey(_) => Ok(ProviderAccount::ApiKey),
|
||||
CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_) => {
|
||||
Err(ProviderAccountError::UnsupportedBedrockApiKeyAuth)
|
||||
}
|
||||
CodexAuth::ApiKey(_) => ProviderAccount::ApiKey,
|
||||
CodexAuth::Headers(_) => {
|
||||
unreachable!("header auth is filtered out above")
|
||||
}
|
||||
})
|
||||
.transpose()?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -1,26 +1,17 @@
|
||||
//! Unit tests for the provider module.
|
||||
|
||||
use std::future::Future;
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::task::Context;
|
||||
use std::task::Waker;
|
||||
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::auth::BedrockApiKeyAuth;
|
||||
use codex_model_provider_info::AwsAuthRefreshConfig;
|
||||
use codex_model_provider_info::AwsCredentialExportConfig;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_model_provider_info::create_oss_provider_with_base_url;
|
||||
use codex_models_manager::ModelsManagerConfig;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_utils_redacted_string::RedactedString;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
@@ -32,7 +23,6 @@ use wiremock::matchers::path;
|
||||
|
||||
use super::*;
|
||||
use crate::RemoteCompactionSupport;
|
||||
use crate::shared_state::process_shared_state;
|
||||
|
||||
fn provider_info_with_command_auth() -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
@@ -47,7 +37,7 @@ fn provider_info_with_command_auth() -> ModelProviderInfo {
|
||||
.expect("current dir should be absolute"),
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
..ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +55,7 @@ fn provider_for(base_url: String) -> ModelProviderInfo {
|
||||
experimental_bearer_token: None,
|
||||
auth: None,
|
||||
gateway_oauth: None,
|
||||
aws: None,
|
||||
api_key: None,
|
||||
wire_api: WireApi::Responses,
|
||||
query_params: None,
|
||||
http_headers: None,
|
||||
@@ -78,9 +68,8 @@ fn provider_for(base_url: String) -> ModelProviderInfo {
|
||||
supports_websockets: false,
|
||||
supports_standalone_web_search: false,
|
||||
capabilities: None,
|
||||
project_id: None,
|
||||
location: None,
|
||||
credential_file: None,
|
||||
merge_system_messages: None,
|
||||
keyring_account: None,
|
||||
include_internal_metadata: false,
|
||||
}
|
||||
}
|
||||
@@ -109,13 +98,6 @@ fn remote_model(slug: &str) -> ModelInfo {
|
||||
.expect("valid model")
|
||||
}
|
||||
|
||||
fn bedrock_api_key_auth() -> CodexAuth {
|
||||
CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "bedrock-api-key-test".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_auth_adds_no_headers_for_non_openai_provider() {
|
||||
let provider = create_model_provider(
|
||||
@@ -128,29 +110,9 @@ async fn request_auth_adds_no_headers_for_non_openai_provider() {
|
||||
assert!(auth.auth.to_auth_headers().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_enables_remote_compaction() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.capabilities(),
|
||||
ProviderCapabilities {
|
||||
remote_compaction: RemoteCompactionSupport::V2,
|
||||
..ProviderCapabilities::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_provider_remote_compaction_matches_provider_support() {
|
||||
let cases = [
|
||||
(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
RemoteCompactionSupport::V2,
|
||||
),
|
||||
(
|
||||
ModelProviderInfo {
|
||||
name: "Azure".to_string(),
|
||||
@@ -182,7 +144,7 @@ fn configured_provider_remote_compaction_matches_provider_support() {
|
||||
#[test]
|
||||
fn configured_provider_uses_default_approval_review_preferred_model() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
@@ -195,7 +157,7 @@ fn configured_provider_uses_default_approval_review_preferred_model() {
|
||||
#[test]
|
||||
fn configured_provider_uses_luna_for_approval_review_with_api_key_auth() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
@@ -207,7 +169,7 @@ fn configured_provider_uses_luna_for_approval_review_with_api_key_auth() {
|
||||
#[test]
|
||||
fn configured_provider_uses_default_approval_review_model_with_header_auth() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::Headers(
|
||||
codex_login::AuthHeaders::new(http::HeaderMap::new()),
|
||||
))),
|
||||
@@ -265,22 +227,29 @@ async fn configured_provider_resolves_default_and_explicit_endpoints() {
|
||||
"https://example.test/v1"
|
||||
);
|
||||
|
||||
// Stored and host-supplied keys never reroute a configured endpoint (no FedRAMP or
|
||||
// default OpenAI endpoints), and a provider without base_url is never contacted.
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let auth = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("initial-key"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
let unconfigured = create_model_provider(
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
for (api_key, expected_base_url) in [
|
||||
("legacy-key", "https://api.openai.com/v1"),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"https://gov.api.openai.com/v1",
|
||||
assert!(unconfigured.request_provider_and_auth().await.is_err());
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("https://llm.example/v1".to_string()),
|
||||
),
|
||||
("commercial-key", "https://api.openai.com/v1"),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
for api_key in [
|
||||
"legacy-key",
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"commercial-key",
|
||||
] {
|
||||
codex_login::login_with_api_key(
|
||||
home.path(),
|
||||
@@ -291,25 +260,20 @@ async fn configured_provider_resolves_default_and_explicit_endpoints() {
|
||||
.unwrap();
|
||||
auth.reload().await;
|
||||
let (api_provider, resolved) = provider.request_provider_and_auth().await.unwrap();
|
||||
assert_eq!(api_provider.base_url, expected_base_url);
|
||||
assert_eq!(api_provider.base_url, "https://llm.example/v1");
|
||||
let headers = resolved.auth.to_auth_headers().unwrap();
|
||||
assert_eq!(
|
||||
headers[http::header::AUTHORIZATION].to_str().unwrap(),
|
||||
format!("Bearer {api_key}")
|
||||
);
|
||||
}
|
||||
assert_eq!(provider.info().base_url, None);
|
||||
|
||||
let rotating_auth = Arc::new(RotatingAuth(AtomicUsize::new(0)));
|
||||
auth.set_external_auth(rotating_auth.clone()).await.unwrap();
|
||||
for (api_key, expected_base_url, expected_fedramp_header) in [
|
||||
("commercial-key", "https://api.openai.com/v1", None),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"https://gov.api.openai.com/v1",
|
||||
Some("true"),
|
||||
),
|
||||
("commercial-key", "https://api.openai.com/v1", None),
|
||||
for api_key in [
|
||||
"commercial-key",
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"commercial-key",
|
||||
] {
|
||||
let reads_before = rotating_auth.0.load(Ordering::SeqCst);
|
||||
let (api_provider, resolved) = provider.request_provider_and_auth().await.unwrap();
|
||||
@@ -322,14 +286,12 @@ async fn configured_provider_resolves_default_and_explicit_endpoints() {
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
headers
|
||||
.get("X-OpenAI-Fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
headers.get("X-OpenAI-Fedramp"),
|
||||
),
|
||||
(
|
||||
expected_base_url,
|
||||
"https://llm.example/v1",
|
||||
Some(expected_authorization.as_str()),
|
||||
expected_fedramp_header,
|
||||
None,
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -349,272 +311,10 @@ fn create_model_provider_builds_command_auth_manager_without_base_manager() {
|
||||
assert!(auth_manager.has_external_auth());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_model_provider_does_not_use_openai_auth_manager_for_amazon_bedrock_provider() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
})),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
);
|
||||
|
||||
assert!(provider.auth_manager().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_bedrock_auth_refresh_is_reused_only_for_matching_configuration() {
|
||||
const TEST_NAME: &str =
|
||||
"provider::tests::shared_bedrock_auth_refresh_is_reused_only_for_matching_configuration";
|
||||
const HELPER_ARG: &str = "CODEX_BEDROCK_SHARED_AUTH_REFRESH_COMMAND";
|
||||
const SUBPROCESS_ARG: &str = "CODEX_BEDROCK_SHARED_AUTH_REFRESH_SUBPROCESS";
|
||||
let arguments = std::env::args().collect::<Vec<_>>();
|
||||
if let Some(index) = arguments.iter().position(|argument| argument == HELPER_ARG) {
|
||||
let counter = &arguments[index + 2];
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
let mut counter = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(counter)
|
||||
.expect("refresh invocation counter should open");
|
||||
std::io::Write::write_all(&mut counter, b"1").expect("write invocation counter");
|
||||
return;
|
||||
}
|
||||
|
||||
let counter = std::env::temp_dir().join(format!("bedrock-refresh-{}", std::process::id()));
|
||||
if !arguments.iter().any(|argument| argument == SUBPROCESS_ARG) {
|
||||
std::fs::create_dir(&counter).expect("AWS command directory should be created");
|
||||
let executable = std::env::current_exe().expect("test executable should be available");
|
||||
let aws = counter.join(format!("aws{}", std::env::consts::EXE_SUFFIX));
|
||||
std::fs::hard_link(&executable, &aws)
|
||||
.or_else(|_| codex_utils_cargo_bin::copy_executable(&executable, &aws))
|
||||
.expect("test executable should be installed as aws");
|
||||
let existing_path = std::env::var_os("PATH").unwrap_or_default();
|
||||
let path = std::env::join_paths(
|
||||
std::iter::once(counter.clone()).chain(std::env::split_paths(&existing_path)),
|
||||
)
|
||||
.expect("test executable PATH should be valid");
|
||||
let output = tokio::process::Command::new(executable)
|
||||
.args(["--exact", TEST_NAME, "--skip", SUBPROCESS_ARG])
|
||||
.env("PATH", path)
|
||||
.env_remove("AWS_ACCESS_KEY_ID")
|
||||
.env_remove("AWS_SECRET_ACCESS_KEY")
|
||||
.output()
|
||||
.await
|
||||
.expect("isolated AWS refresh test should run");
|
||||
std::fs::remove_dir_all(&counter).expect("AWS command directory should be removed");
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
return;
|
||||
}
|
||||
let _ = std::fs::remove_file(&counter);
|
||||
let aws = ModelProviderAwsAuthInfo {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: Some(AwsAuthRefreshConfig {
|
||||
command: "aws".to_string(),
|
||||
args: Vec::from(
|
||||
[
|
||||
"--exact",
|
||||
TEST_NAME,
|
||||
"--skip",
|
||||
HELPER_ARG,
|
||||
"--skip",
|
||||
counter.to_str().expect("counter path should be UTF-8"),
|
||||
]
|
||||
.map(RedactedString::from),
|
||||
),
|
||||
timeout_ms: NonZeroU64::new(10_000).expect("timeout should be non-zero"),
|
||||
}),
|
||||
};
|
||||
let provider_info = ModelProviderInfo::create_amazon_bedrock_provider(Some(aws.clone()));
|
||||
|
||||
let first = create_model_provider(
|
||||
provider_info.clone(),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
);
|
||||
let second = create_model_provider(provider_info.clone(), /*auth_manager*/ None);
|
||||
let shared_state = process_shared_state();
|
||||
let shared_recovery = shared_state
|
||||
.aws_auth_recovery(&aws)
|
||||
.expect("test provider should have refresh configured");
|
||||
assert_eq!(Arc::strong_count(&shared_recovery), 3);
|
||||
assert!(first.auth_manager().is_none() && second.auth_manager().is_none());
|
||||
|
||||
for provider in [&first, &second] {
|
||||
for (status, body, recoverable) in [
|
||||
(http::StatusCode::UNAUTHORIZED, "ExpiredToken", true),
|
||||
(http::StatusCode::FORBIDDEN, "InvalidClientTokenId", true),
|
||||
(http::StatusCode::FORBIDDEN, "AccessDeniedException", false),
|
||||
] {
|
||||
let error = TransportError::Http {
|
||||
retry_after: None,
|
||||
status,
|
||||
url: None,
|
||||
headers: None,
|
||||
body: Some(body.to_string()),
|
||||
};
|
||||
assert_eq!(provider.is_recoverable_auth_error(&error), recoverable);
|
||||
}
|
||||
}
|
||||
|
||||
let mut invalid_aws = aws.clone();
|
||||
invalid_aws.auth_refresh.as_mut().expect("refresh").command = "not-aws".into();
|
||||
let invalid_provider = create_model_provider(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(invalid_aws)),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
let error = invalid_provider
|
||||
.recover_from_unauthorized()
|
||||
.await
|
||||
.expect_err("non-aws command should be rejected");
|
||||
assert_eq!(error.retry_delay(/*retry_count*/ 1), None);
|
||||
assert_eq!(error.to_string(), "AWS auth refresh command must be `aws`");
|
||||
|
||||
let (first_result, second_result) = tokio::join!(
|
||||
first.recover_from_unauthorized(),
|
||||
second.recover_from_unauthorized()
|
||||
);
|
||||
assert_eq!(
|
||||
[first_result, second_result].map(|result| result.expect("provider should recover")),
|
||||
[ProviderUnauthorizedRecovery::Recovered; 2]
|
||||
);
|
||||
let read_counter = || std::fs::read_to_string(&counter).expect("read counter");
|
||||
assert_eq!(read_counter(), "1");
|
||||
|
||||
assert_eq!(
|
||||
first
|
||||
.recover_from_unauthorized()
|
||||
.await
|
||||
.expect("later generation should recover"),
|
||||
ProviderUnauthorizedRecovery::Recovered
|
||||
);
|
||||
assert_eq!(read_counter(), "11");
|
||||
|
||||
let fixture = tempfile::tempdir().expect("export fixture should be created");
|
||||
let export_counter = fixture.path().join("exports");
|
||||
let export_gate = fixture.path().join("release");
|
||||
#[cfg(unix)]
|
||||
let (command, mut args) = (
|
||||
"sh".to_string(),
|
||||
vec![
|
||||
"-c".to_string(),
|
||||
r#"printf '1\n' >> "$1"
|
||||
while [ ! -e "$2" ]; do :; done
|
||||
printf '%s\n' '{"AccessKeyId":"exported","SecretAccessKey":"secret"}'
|
||||
"#
|
||||
.to_string(),
|
||||
"export-credentials".to_string(),
|
||||
],
|
||||
);
|
||||
#[cfg(windows)]
|
||||
let (command, mut args) = {
|
||||
let script = fixture.path().join("export.cmd");
|
||||
std::fs::write(
|
||||
&script,
|
||||
concat!(
|
||||
"@echo off\r\n>> \"%~1\" echo 1\r\n",
|
||||
":wait\r\nif not exist \"%~2\" goto wait\r\n",
|
||||
"echo {\"AccessKeyId\":\"exported\",\"SecretAccessKey\":\"secret\"}\r\n",
|
||||
),
|
||||
)
|
||||
.expect("export script should be written");
|
||||
(
|
||||
"cmd.exe".to_string(),
|
||||
vec![
|
||||
"/D".to_string(),
|
||||
"/Q".to_string(),
|
||||
"/C".to_string(),
|
||||
script.to_string_lossy().into_owned(),
|
||||
],
|
||||
)
|
||||
};
|
||||
args.extend([&export_counter, &export_gate].map(|path| path.to_string_lossy().into_owned()));
|
||||
let provider_info =
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
credential_export: Some(AwsCredentialExportConfig {
|
||||
command,
|
||||
args: args.into_iter().map(RedactedString::from).collect(),
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("timeout should be non-zero"),
|
||||
}),
|
||||
..aws.clone()
|
||||
}));
|
||||
let first_export = create_model_provider(provider_info.clone(), /*auth_manager*/ None);
|
||||
let second_export = create_model_provider(provider_info, /*auth_manager*/ None);
|
||||
let first_refresh = first_export.recover_from_unauthorized();
|
||||
let second_refresh = second_export.recover_from_unauthorized();
|
||||
tokio::pin!(first_refresh, second_refresh);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
tokio::select! {
|
||||
result = &mut first_refresh => panic!("export should wait for its gate: {result:?}"),
|
||||
() = async {
|
||||
while !export_counter.exists() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
} => {}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("export should start after login");
|
||||
assert_eq!(read_counter(), "111");
|
||||
{
|
||||
// Queue another recovery after login finishes, while export still holds the lock.
|
||||
let mut context = Context::from_waker(Waker::noop());
|
||||
assert!(second_refresh.as_mut().poll(&mut context).is_pending());
|
||||
}
|
||||
std::fs::write(&export_gate, []).expect("export gate should open");
|
||||
let (first_result, second_result) = tokio::join!(first_refresh, second_refresh);
|
||||
assert_eq!(
|
||||
[first_result, second_result].map(|result| result.expect("provider should recover")),
|
||||
[ProviderUnauthorizedRecovery::Recovered; 2]
|
||||
);
|
||||
assert_eq!(read_counter(), "111");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(export_counter)
|
||||
.expect("read export counter")
|
||||
.lines()
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["1"]
|
||||
);
|
||||
std::fs::remove_file(&counter).expect("refresh invocation counter should be removed");
|
||||
|
||||
let different_profile = ModelProviderAwsAuthInfo {
|
||||
profile: Some("another-bedrock-profile".to_string()),
|
||||
..aws.clone()
|
||||
};
|
||||
let other_recovery = shared_state
|
||||
.aws_auth_recovery(&different_profile)
|
||||
.expect("test provider should have refresh configured");
|
||||
assert!(!Arc::ptr_eq(&shared_recovery, &other_recovery));
|
||||
|
||||
let released_recovery = Arc::downgrade(&shared_recovery);
|
||||
drop((first, second, shared_recovery));
|
||||
assert!(released_recovery.upgrade().is_none());
|
||||
assert!(shared_state.aws_auth_recovery(&aws).is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_model_provider_uses_managed_auth_for_amazon_bedrock_provider() {
|
||||
let auth = bedrock_api_key_auth();
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(auth.clone())),
|
||||
);
|
||||
|
||||
assert_eq!(provider.auth().await, Some(auth));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_returns_unauthenticated_openai_account_state() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
@@ -630,7 +330,7 @@ fn openai_provider_returns_unauthenticated_openai_account_state() {
|
||||
#[test]
|
||||
fn openai_provider_returns_api_key_account_state() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
@@ -648,7 +348,7 @@ fn openai_provider_returns_api_key_account_state() {
|
||||
#[test]
|
||||
fn openai_provider_returns_no_account_state_for_header_auth() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo::create_responses_provider("mock", /*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::Headers(
|
||||
codex_login::AuthHeaders::new(http::HeaderMap::new()),
|
||||
))),
|
||||
@@ -663,19 +363,6 @@ fn openai_provider_returns_no_account_state_for_header_auth() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_rejects_bedrock_api_key_account_state() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(bedrock_api_key_auth())),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Err(ProviderAccountError::UnsupportedBedrockApiKeyAuth)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_non_openai_provider_returns_no_account_state() {
|
||||
let provider = create_model_provider(
|
||||
@@ -698,169 +385,6 @@ fn custom_non_openai_provider_returns_no_account_state() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amazon_bedrock_provider_returns_bedrock_account_state() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn amazon_bedrock_provider_creates_static_models_manager() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
let manager = provider.models_manager(test_codex_home(), /*config_model_catalog*/ None);
|
||||
let uncached_manager =
|
||||
provider.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
|
||||
let catalog = manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
let uncached_catalog = uncached_manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(uncached_catalog, catalog);
|
||||
for slug in [
|
||||
"openai.gpt-6.1-sol",
|
||||
"openai.gpt-6.1-terra",
|
||||
"openai.gpt-6-sol",
|
||||
"openai.gpt-6-luna",
|
||||
"openai.gpt-5.6-sol",
|
||||
"openai.gpt-6-astra",
|
||||
] {
|
||||
let model_info = manager
|
||||
.get_model_info(
|
||||
slug,
|
||||
&ModelsManagerConfig {
|
||||
model_context_window: Some(1_000_000),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let mut expected_model_info = manager
|
||||
.get_model_info(slug, &ModelsManagerConfig::default())
|
||||
.await;
|
||||
expected_model_info.context_window = Some(872_000);
|
||||
assert_eq!(model_info, expected_model_info);
|
||||
}
|
||||
|
||||
let models = catalog
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| (model.slug.as_str(), model.display_name.as_str()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
models,
|
||||
vec![
|
||||
("openai.gpt-6.1-sol", "GPT-6.1 Sol"),
|
||||
("openai.gpt-6-astra", "GPT-6-Astra"),
|
||||
("openai.gpt-6.1-terra", "GPT-6.1 Terra"),
|
||||
("openai.gpt-6-sol", "GPT-6 Sol"),
|
||||
("openai.gpt-6-luna", "GPT-6 Luna"),
|
||||
("openai.gpt-5.6-sol", "GPT-5.6 Sol"),
|
||||
("openai.gpt-5.6-terra", "GPT-5.6 Terra"),
|
||||
("openai.gpt-5.6-luna", "GPT-5.6 Luna"),
|
||||
("openai.gpt-5.5", "GPT-5.5"),
|
||||
]
|
||||
);
|
||||
|
||||
let available_models = manager
|
||||
.list_models(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
available_models
|
||||
.iter()
|
||||
.map(|preset| preset.model.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"openai.gpt-6.1-sol",
|
||||
"openai.gpt-6-astra",
|
||||
"openai.gpt-6.1-terra",
|
||||
"openai.gpt-6-sol",
|
||||
"openai.gpt-6-luna",
|
||||
"openai.gpt-5.6-sol",
|
||||
"openai.gpt-5.6-terra",
|
||||
"openai.gpt-5.6-luna",
|
||||
"openai.gpt-5.5",
|
||||
]
|
||||
);
|
||||
|
||||
let default_model = available_models
|
||||
.iter()
|
||||
.find(|preset| preset.is_default)
|
||||
.expect("Bedrock catalog should have a default model");
|
||||
|
||||
assert_eq!(default_model.model, "openai.gpt-6.1-sol");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_bedrock_catalog_preserves_service_tiers() {
|
||||
let mut configured_model = codex_models_manager::bundled_models_response()
|
||||
.expect("bundled models should parse")
|
||||
.models
|
||||
.into_iter()
|
||||
.find(|model| model.slug == "gpt-5.5")
|
||||
.expect("bundled models should include GPT-5.5");
|
||||
configured_model.service_tiers = vec![codex_protocol::openai_models::ModelServiceTier {
|
||||
id: "custom-tier".to_string(),
|
||||
name: "Custom tier".to_string(),
|
||||
description: "User-defined tier description.".to_string(),
|
||||
}];
|
||||
configured_model.default_service_tier = Some("custom-tier".to_string());
|
||||
let configured_catalog = ModelsResponse {
|
||||
models: vec![configured_model],
|
||||
};
|
||||
let mut expected = configured_catalog.clone();
|
||||
expected.models[0].web_search_tool_type =
|
||||
codex_protocol::openai_models::WebSearchToolType::Text;
|
||||
|
||||
let mut gov_provider = ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None);
|
||||
gov_provider.base_url =
|
||||
Some("https://bedrock-mantle.us-gov-west-1.api.aws/openai/v1".to_string());
|
||||
for provider_info in [
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
ModelProviderInfo::create_amazon_bedrock_runtime_provider(/*aws*/ None),
|
||||
gov_provider,
|
||||
] {
|
||||
let provider = create_model_provider(provider_info, /*auth_manager*/ None);
|
||||
for manager in [
|
||||
provider.models_manager(test_codex_home(), Some(configured_catalog.clone())),
|
||||
provider.models_manager_without_cache(Some(configured_catalog.clone())),
|
||||
] {
|
||||
let catalog = manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(catalog, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_provider_models_manager_uses_provider_bearer_token() {
|
||||
let server = MockServer::start().await;
|
||||
@@ -919,3 +443,114 @@ async fn configured_provider_models_manager_uses_provider_bearer_token() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_provider_lists_openai_format_models_with_provider_auth() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/v1/models"))
|
||||
.and(header_regex("authorization", "^Bearer local-token$"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"object": "list",
|
||||
"data": [{
|
||||
"id": "/opt/llm/models/Qwen.gguf",
|
||||
"object": "model",
|
||||
"owned_by": "llamacpp",
|
||||
"meta": {"n_ctx_train": 262144},
|
||||
"max_model_len": 131072,
|
||||
}],
|
||||
"models": [{"slug": "codex-format-entries-are-ignored"}],
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/props"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(0)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let info = ModelProviderInfo {
|
||||
experimental_bearer_token: Some("local-token".into()),
|
||||
..provider_for(format!("{}/v1", server.uri()))
|
||||
};
|
||||
let manager = create_model_provider(info, /*auth_manager*/ None)
|
||||
.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
|
||||
let catalog = manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| (model.slug.as_str(), model.context_window))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![("/opt/llm/models/Qwen.gguf", Some(131_072))]
|
||||
);
|
||||
|
||||
// The configured alias of a single-model server gets local metadata, not a fallback.
|
||||
let model = manager
|
||||
.get_model_info("qwen3.6-35b-a3b", &Default::default())
|
||||
.await;
|
||||
assert_eq!(model.origin, codex_models_manager::ModelOrigin::Provider);
|
||||
assert_eq!(model.context_window, Some(131_072));
|
||||
assert_eq!(
|
||||
model.apply_patch_tool_type,
|
||||
Some(codex_protocol::openai_models::ApplyPatchToolType::Function)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_provider_reads_llama_cpp_props_when_models_lack_context() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/v1/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"object": "list",
|
||||
"data": [{"id": "a"}, {"id": "b"}],
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/props"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"default_generation_settings": {"n_ctx": 65536},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let manager = create_model_provider(
|
||||
provider_for(format!("{}/v1", server.uri())),
|
||||
/*auth_manager*/ None,
|
||||
)
|
||||
.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
manager
|
||||
.ensure_initialized(HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault))
|
||||
.await;
|
||||
|
||||
let model = manager.get_model_info("b", &Default::default()).await;
|
||||
assert_eq!(model.context_window, Some(65_536));
|
||||
// `/props` is read once and remembered.
|
||||
let again = manager.get_model_info("a", &Default::default()).await;
|
||||
assert_eq!(again.context_window, Some(65_536));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_provider_without_server_uses_conservative_context() {
|
||||
// Nothing listens here; the lookup fails quickly and metadata stays local.
|
||||
let manager = create_model_provider(
|
||||
provider_for("http://127.0.0.1:9/v1".to_string()),
|
||||
/*auth_manager*/ None,
|
||||
)
|
||||
.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
let model = manager.get_model_info("local", &Default::default()).await;
|
||||
assert_eq!(model.origin, codex_models_manager::ModelOrigin::Provider);
|
||||
assert_eq!(
|
||||
model.context_window,
|
||||
Some(codex_models_manager::model_info::DEFAULT_LOCAL_CONTEXT_WINDOW)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ async fn explicit_provider_token_survives_a_stored_credential_switch_during_setu
|
||||
let home = TempDir::new().unwrap();
|
||||
let initial = CodexAuth::from_api_key("stored-key-a");
|
||||
let manager = AuthManager::from_auth_for_testing_with_home(initial, home.path().to_path_buf());
|
||||
let mut info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let mut info = ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("https://llm.example/v1".to_string()),
|
||||
);
|
||||
info.experimental_bearer_token = Some("provider-token".into());
|
||||
let provider = create_model_provider(info, Some(manager.clone()));
|
||||
|
||||
|
||||
@@ -48,9 +48,7 @@ pub(crate) async fn resolve_request_auth(
|
||||
/// Capture the selected source's owner before starting work such as a turn or classification.
|
||||
/// Request preparation returns the owner it actually used so callers can detect a source change.
|
||||
pub fn request_auth_owner(provider: &dyn ModelProvider) -> Option<AuthOwner> {
|
||||
provider
|
||||
.auth_manager()
|
||||
.map(|manager| manager.auth_owner())
|
||||
provider.auth_manager().map(|manager| manager.auth_owner())
|
||||
}
|
||||
|
||||
pub struct ResolvedProviderRequest {
|
||||
|
||||
@@ -11,19 +11,13 @@ use codex_login::GatewayAuthConfig;
|
||||
use codex_login::OAuthSessionManager;
|
||||
use codex_model_provider_info::CredentialExportConfig;
|
||||
use codex_model_provider_info::GatewayOAuthSettings;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
|
||||
use crate::amazon_bedrock::AwsAuthRecovery;
|
||||
use crate::amazon_bedrock::AwsCredentialExport;
|
||||
|
||||
/// Provider-owned runtime state shared across independently configured sessions.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ModelProviderSharedState {
|
||||
command_credentials: Mutex<Vec<(ModelProviderAuthInfo, AuthRuntimeConfig, Weak<AuthManager>)>>,
|
||||
aws_credential_exports: Mutex<Vec<(ModelProviderAwsAuthInfo, Weak<AwsCredentialExport>)>>,
|
||||
aws_auth_recoveries: Mutex<Vec<(ModelProviderAwsAuthInfo, Weak<AwsAuthRecovery>)>>,
|
||||
gateway_exports: Mutex<Vec<GatewayExportEntry>>,
|
||||
oauth_sessions: Mutex<
|
||||
Vec<(
|
||||
@@ -139,54 +133,6 @@ impl ModelProviderSharedState {
|
||||
});
|
||||
export
|
||||
}
|
||||
|
||||
pub(crate) fn aws_credential_export(
|
||||
&self,
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
) -> Option<Arc<AwsCredentialExport>> {
|
||||
let config = aws.credential_export.as_ref()?;
|
||||
let mut exports = self
|
||||
.aws_credential_exports
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
exports.retain(|(_, export)| export.strong_count() != 0);
|
||||
|
||||
if let Some(export) = exports
|
||||
.iter()
|
||||
.find(|(cached_aws, _)| cached_aws == aws)
|
||||
.and_then(|(_, export)| export.upgrade())
|
||||
{
|
||||
return Some(export);
|
||||
}
|
||||
|
||||
let export = Arc::new(AwsCredentialExport::new(config.clone()));
|
||||
exports.push((aws.clone(), Arc::downgrade(&export)));
|
||||
Some(export)
|
||||
}
|
||||
|
||||
pub(crate) fn aws_auth_recovery(
|
||||
&self,
|
||||
aws: &ModelProviderAwsAuthInfo,
|
||||
) -> Option<Arc<AwsAuthRecovery>> {
|
||||
let config = aws.auth_refresh.as_ref()?;
|
||||
let mut recoveries = self
|
||||
.aws_auth_recoveries
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
recoveries.retain(|(_, recovery)| recovery.strong_count() != 0);
|
||||
|
||||
if let Some(recovery) = recoveries
|
||||
.iter()
|
||||
.find(|(cached_aws, _)| cached_aws == aws)
|
||||
.and_then(|(_, recovery)| recovery.upgrade())
|
||||
{
|
||||
return Some(recovery);
|
||||
}
|
||||
|
||||
let recovery = Arc::new(AwsAuthRecovery::new(config.clone()));
|
||||
recoveries.push((aws.clone(), Arc::downgrade(&recovery)));
|
||||
Some(recovery)
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "shared_state_test_support.rs"]
|
||||
|
||||
@@ -80,7 +80,7 @@ async fn gateway_credentials_accompany_primary_auth_in_models_and_responses() {
|
||||
let info = ModelProviderInfo {
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(config)),
|
||||
model_catalog_url: Some(format!("{}/models", server.uri()).into()),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary-token"),
|
||||
@@ -189,7 +189,7 @@ async fn gateway_preserves_primary_auth_and_rejects_header_collisions() {
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let _gateway = seed_gateway_auth(
|
||||
&info,
|
||||
@@ -253,7 +253,7 @@ async fn gateway_refresh_preserves_primary_auth_and_hides_issuer_errors() {
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let body = if succeeds {
|
||||
json!({"access_token": "rotated-token", "expires_in": 3600})
|
||||
@@ -350,7 +350,7 @@ async fn models_cache_is_reused_only_for_matching_gateway_configuration() {
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let mut model = codex_models_manager::bundled_models_response()
|
||||
@@ -434,7 +434,7 @@ async fn models_observe_gateway_rotation(instance: ProviderInstance) {
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let gateway = seed_gateway_auth(
|
||||
&info,
|
||||
@@ -550,7 +550,7 @@ async fn gateway_setup_errors_are_reported_when_authentication_is_requested() {
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let provider = create_model_provider(info.clone(), /*auth_manager*/ None);
|
||||
assert_eq!(
|
||||
@@ -622,7 +622,7 @@ async fn gateway_login_required_invalidates_the_last_successful_catalog() {
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let login_control = codex_login::GatewayLoginControl::for_runtime(&primary.runtime_config());
|
||||
login_control.require_explicit_login();
|
||||
@@ -708,7 +708,7 @@ async fn gateway_login_states_stop_request_retries() {
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
..ModelProviderInfo::create_responses_provider("mock", Some(server.uri()))
|
||||
};
|
||||
let login_control = codex_login::GatewayLoginControl::for_runtime(&primary.runtime_config());
|
||||
login_control.require_explicit_login();
|
||||
|
||||
Reference in New Issue
Block a user