Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
codex-rs/model-provider/BUILD.bazel
Normal file
6
codex-rs/model-provider/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "model-provider",
|
||||
crate_name = "codex_model_provider",
|
||||
)
|
||||
52
codex-rs/model-provider/Cargo.toml
Normal file
52
codex-rs/model-provider/Cargo.toml
Normal file
@@ -0,0 +1,52 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "codex-model-provider"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "codex_model_provider"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
codex-utils-process = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-agent-identity = { workspace = true }
|
||||
codex-aws-auth = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-feedback = { workspace = true }
|
||||
codex-features = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-runtime-agent-instance = { workspace = true }
|
||||
codex-keyring-store = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
codex-models-manager = { workspace = true }
|
||||
codex-otel = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-response-debug-context = { workspace = true }
|
||||
codex-secrets = { workspace = true }
|
||||
http = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tokio = { workspace = true, features = ["io-util", "process", "sync", "time"] }
|
||||
tracing = { workspace = true, features = ["log"] }
|
||||
url = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
base64 = { workspace = true }
|
||||
codex-utils-cargo-bin = { workspace = true }
|
||||
codex-utils-redacted-string = { workspace = true }
|
||||
codex-utils-rustls-provider = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
rcgen = { workspace = true }
|
||||
rustls = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
wiremock = { workspace = true }
|
||||
619
codex-rs/model-provider/src/amazon_bedrock/auth.rs
Normal file
619
codex-rs/model-provider/src/amazon_bedrock/auth.rs
Normal file
@@ -0,0 +1,619 @@
|
||||
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),
|
||||
account_id: None,
|
||||
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),
|
||||
account_id: None,
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
90
codex-rs/model-provider/src/amazon_bedrock/auth_refresh.rs
Normal file
90
codex-rs/model-provider/src/amazon_bedrock/auth_refresh.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
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}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
443
codex-rs/model-provider/src/amazon_bedrock/catalog.rs
Normal file
443
codex-rs/model-provider/src/amazon_bedrock/catalog.rs
Normal file
@@ -0,0 +1,443 @@
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
180
codex-rs/model-provider/src/amazon_bedrock/credential_export.rs
Normal file
180
codex-rs/model-provider/src/amazon_bedrock/credential_export.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
//! 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;
|
||||
@@ -0,0 +1,378 @@
|
||||
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(())
|
||||
}
|
||||
60
codex-rs/model-provider/src/amazon_bedrock/error.rs
Normal file
60
codex-rs/model-provider/src/amazon_bedrock/error.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
237
codex-rs/model-provider/src/amazon_bedrock/error_tests.rs
Normal file
237
codex-rs/model-provider/src/amazon_bedrock/error_tests.rs
Normal file
@@ -0,0 +1,237 @@
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
150
codex-rs/model-provider/src/amazon_bedrock/mantle.rs
Normal file
150
codex-rs/model-provider/src/amazon_bedrock/mantle.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
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(),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
788
codex-rs/model-provider/src/amazon_bedrock/mod.rs
Normal file
788
codex-rs/model-provider/src/amazon_bedrock/mod.rs
Normal file
@@ -0,0 +1,788 @@
|
||||
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(/*auth_mode*/ None)
|
||||
}
|
||||
|
||||
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,
|
||||
image_generation: false,
|
||||
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(/*auth_mode*/ None)
|
||||
.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_but_disable_image_generation() {
|
||||
let provider = AmazonBedrockModelProvider::new(
|
||||
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.capabilities(),
|
||||
ProviderCapabilities {
|
||||
reasoning_summaries: true,
|
||||
image_generation: false,
|
||||
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,
|
||||
image_generation: false,
|
||||
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,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
35
codex-rs/model-provider/src/amazon_bedrock/region.rs
Normal file
35
codex-rs/model-provider/src/amazon_bedrock/region.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! 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
|
||||
}
|
||||
44
codex-rs/model-provider/src/amazon_bedrock/runtime.rs
Normal file
44
codex-rs/model-provider/src/amazon_bedrock/runtime.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
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;
|
||||
@@ -0,0 +1,52 @@
|
||||
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;
|
||||
@@ -0,0 +1,167 @@
|
||||
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),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
31
codex-rs/model-provider/src/amazon_bedrock/runtime_tests.rs
Normal file
31
codex-rs/model-provider/src/amazon_bedrock/runtime_tests.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
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(),
|
||||
}
|
||||
);
|
||||
}
|
||||
565
codex-rs/model-provider/src/auth.rs
Normal file
565
codex-rs/model-provider/src/auth.rs
Normal file
@@ -0,0 +1,565 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_agent_identity::AgentIdentityKey;
|
||||
use codex_agent_identity::authorization_header_for_agent_task;
|
||||
use codex_api::AgentIdentityTelemetry;
|
||||
use codex_api::AuthError;
|
||||
use codex_api::AuthHeadersFuture;
|
||||
use codex_api::AuthProvider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::auth::AgentIdentityAuth;
|
||||
use codex_login::auth::AgentIdentityAuthError;
|
||||
use codex_login::auth::AgentIdentityAuthPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_runtime_agent_instance::RuntimeAuth;
|
||||
use codex_runtime_agent_instance::RuntimeAuthError;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
|
||||
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 and optional OpenAI runtime auth for one harness/thread context.
|
||||
/// Publish these together so auxiliary clients cannot select another thread's credentials.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ProviderAuthContext {
|
||||
pub credentials: Arc<AuthManager>,
|
||||
pub runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
}
|
||||
|
||||
impl ProviderAuthContext {
|
||||
pub fn model_provider(&self, info: ModelProviderInfo) -> crate::SharedModelProvider {
|
||||
crate::provider::create_model_provider_with_runtime(
|
||||
info,
|
||||
Some(Arc::clone(&self.credentials)),
|
||||
self.runtime_auth.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ProviderAuthScope {
|
||||
pub agent_identity_policy: AgentIdentityAuthPolicy,
|
||||
pub session_source: SessionSource,
|
||||
pub agent_identity_session_fallback: AgentIdentitySessionFallback,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AgentIdentitySessionFallback {
|
||||
engaged: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AgentIdentitySessionFallback {
|
||||
pub fn is_engaged(&self) -> bool {
|
||||
self.engaged.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn engage(&self) -> bool {
|
||||
!self.engaged.swap(true, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider auth resolved for a request, plus metadata describing the effective auth.
|
||||
#[derive(Clone)]
|
||||
pub struct ResolvedProviderAuth {
|
||||
/// Login selected with these headers; routing must use the same credential.
|
||||
pub credential: Option<CodexAuth>,
|
||||
pub auth: SharedAuthProvider,
|
||||
pub agent_identity_telemetry: Option<AgentIdentityTelemetry>,
|
||||
pub runtime: Option<RuntimeAuth>,
|
||||
}
|
||||
|
||||
impl ResolvedProviderAuth {
|
||||
pub(crate) fn new(auth: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
credential: None,
|
||||
auth,
|
||||
agent_identity_telemetry: None,
|
||||
runtime: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn for_runtime(selected: RuntimeAuth, mode: RuntimeAuthMode) -> Self {
|
||||
Self {
|
||||
credential: Some(selected.auth().clone()),
|
||||
auth: selected.clone().into_auth_provider(mode),
|
||||
agent_identity_telemetry: None,
|
||||
runtime: Some(selected),
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve the caller's transport configuration and bind it to the selected login.
|
||||
pub fn bind_http_client_factory(
|
||||
&self,
|
||||
factory: HttpClientFactory,
|
||||
) -> Result<HttpClientFactory, AuthError> {
|
||||
match &self.runtime {
|
||||
Some(runtime) => runtime.bind_http_client_factory(factory),
|
||||
None => Ok(factory),
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve the caller's connection pool and bind it to the selected login.
|
||||
pub fn bind_http_client_pool(
|
||||
&self,
|
||||
pool: &RouteAwareClientPool,
|
||||
) -> Result<RouteAwareClientPool, AuthError> {
|
||||
match &self.runtime {
|
||||
Some(runtime) => pool
|
||||
.with_account_binding(runtime.http_client_factory().network_policy())
|
||||
.ok_or_else(|| {
|
||||
AuthError::Build(
|
||||
"runtime credentials and transport must share the application network policy"
|
||||
.to_string(),
|
||||
)
|
||||
}),
|
||||
None => Ok(pool.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject account selectors that disagree with the selected runtime.
|
||||
pub fn validate_headers(&self, headers: &HeaderMap) -> codex_protocol::error::Result<()> {
|
||||
if let Some(runtime) = &self.runtime {
|
||||
crate::validate_runtime_selectors(headers, runtime.runtime().actor().info())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn for_agent_identity(auth: AgentIdentityAuth) -> Self {
|
||||
let agent_identity_telemetry = agent_identity_telemetry(&auth);
|
||||
Self {
|
||||
credential: None,
|
||||
auth: Arc::new(AgentIdentityAuthProvider { auth }),
|
||||
agent_identity_telemetry: Some(agent_identity_telemetry),
|
||||
runtime: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn agent_identity_telemetry(auth: &AgentIdentityAuth) -> AgentIdentityTelemetry {
|
||||
AgentIdentityTelemetry {
|
||||
agent_id: auth.record().agent_runtime_id.clone(),
|
||||
task_id: auth.run_task_id().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct AgentIdentityAuthProvider {
|
||||
auth: AgentIdentityAuth,
|
||||
}
|
||||
|
||||
impl AuthProvider for AgentIdentityAuthProvider {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
let record = self.auth.record();
|
||||
let header_value = authorization_header_for_agent_task(
|
||||
AgentIdentityKey {
|
||||
agent_runtime_id: &record.agent_runtime_id,
|
||||
private_key_pkcs8_base64: &record.agent_private_key,
|
||||
},
|
||||
self.auth.run_task_id(),
|
||||
)
|
||||
.map_err(std::io::Error::other);
|
||||
|
||||
if let Ok(header_value) = header_value
|
||||
&& let Ok(header) = HeaderValue::from_str(&header_value)
|
||||
{
|
||||
let _ = headers.insert(http::header::AUTHORIZATION, header);
|
||||
}
|
||||
|
||||
if let Ok(header) = HeaderValue::from_str(self.auth.account_id()) {
|
||||
let _ = headers.insert(CHATGPT_ACCOUNT_ID_HEADER, header);
|
||||
}
|
||||
|
||||
if self.auth.is_fedramp_account() {
|
||||
let _ = headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct HeaderAuthProvider {
|
||||
auth: AuthHeaders,
|
||||
}
|
||||
|
||||
impl AuthProvider for HeaderAuthProvider {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
headers.extend(self.auth.headers().clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct AuthManagerAuthProvider {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
// Startup auth is only the account-scoped identity anchor. Request
|
||||
// headers always come from the current AuthManager snapshot below.
|
||||
expected_auth: CodexAuth,
|
||||
}
|
||||
|
||||
impl AuthManagerAuthProvider {
|
||||
fn is_expected_auth(&self, auth: &CodexAuth) -> bool {
|
||||
auth.uses_codex_backend()
|
||||
&& auth.get_account_id() == self.expected_auth.get_account_id()
|
||||
&& auth.get_chatgpt_user_id() == self.expected_auth.get_chatgpt_user_id()
|
||||
&& auth.is_workspace_account() == self.expected_auth.is_workspace_account()
|
||||
}
|
||||
|
||||
fn current_auth(&self) -> Option<CodexAuth> {
|
||||
self.auth_manager
|
||||
.auth_cached()
|
||||
.filter(|auth| self.is_expected_auth(auth))
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthProvider for AuthManagerAuthProvider {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
let auth = self.current_auth().ok_or_else(|| {
|
||||
AuthError::Transient("managed authentication is unavailable".to_string())
|
||||
})?;
|
||||
auth_provider_from_auth(&auth).add_auth_headers(headers)
|
||||
}
|
||||
|
||||
fn apply_auth_headers(&self, mut headers: HeaderMap) -> AuthHeadersFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let auth = self
|
||||
.auth_manager
|
||||
.auth()
|
||||
.await
|
||||
.filter(|auth| self.is_expected_auth(auth))
|
||||
.ok_or_else(|| {
|
||||
AuthError::Transient("managed authentication is unavailable".to_string())
|
||||
})?;
|
||||
headers.extend(auth_provider_from_auth(&auth).to_auth_headers()?);
|
||||
Ok(headers)
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_after_unauthorized(
|
||||
&self,
|
||||
rejected_headers: HeaderMap,
|
||||
) -> codex_api::AuthRefreshFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let Some(auth) = self.current_auth() else {
|
||||
return false;
|
||||
};
|
||||
let Ok(headers) = auth_provider_from_auth(&auth).to_auth_headers() else {
|
||||
return false;
|
||||
};
|
||||
if headers.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if headers
|
||||
.iter()
|
||||
.any(|(name, value)| rejected_headers.get(name) != Some(value))
|
||||
&& self.auth_manager.refresh_failure_for_auth(&auth).is_none()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if !self.auth_manager.unauthorized_recovery().has_next() {
|
||||
return false;
|
||||
}
|
||||
let result = self.auth_manager.refresh_token_if_unchanged(&auth).await;
|
||||
let Some(refreshed_auth) = self.current_auth() else {
|
||||
return false;
|
||||
};
|
||||
if self
|
||||
.auth_manager
|
||||
.refresh_failure_for_auth(&refreshed_auth)
|
||||
.is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Ok(refreshed_headers) = auth_provider_from_auth(&refreshed_auth).to_auth_headers()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
!refreshed_headers.is_empty()
|
||||
&& refreshed_headers != headers
|
||||
&& !matches!(result, Err(codex_login::RefreshTokenError::Policy(_)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Some providers are meant to send no auth headers. Examples include local OSS
|
||||
// providers and custom test providers with `requires_openai_auth = false`.
|
||||
#[derive(Clone, Debug)]
|
||||
struct UnauthenticatedAuthProvider;
|
||||
|
||||
impl AuthProvider for UnauthenticatedAuthProvider {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unauthenticated_auth_provider() -> SharedAuthProvider {
|
||||
Arc::new(UnauthenticatedAuthProvider)
|
||||
}
|
||||
|
||||
/// Returns the provider-scoped auth manager when this provider uses command-backed auth.
|
||||
///
|
||||
/// Providers without custom auth continue using the caller-supplied base manager, when present.
|
||||
pub(crate) fn auth_manager_for_provider(
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
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),
|
||||
})
|
||||
}
|
||||
}
|
||||
None => auth_manager,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_provider_auth(
|
||||
auth: Option<&CodexAuth>,
|
||||
provider: &ModelProviderInfo,
|
||||
) -> codex_protocol::error::Result<SharedAuthProvider> {
|
||||
if let Some(auth) = bearer_auth_for_provider(provider)? {
|
||||
return Ok(Arc::new(auth));
|
||||
}
|
||||
|
||||
if !provider.requires_openai_auth && provider.auth.is_none() {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_provider_auth_for_scope(
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
auth: Option<&CodexAuth>,
|
||||
provider: &ModelProviderInfo,
|
||||
scope: ProviderAuthScope,
|
||||
) -> codex_protocol::error::Result<ResolvedProviderAuth> {
|
||||
let ProviderAuthScope {
|
||||
agent_identity_policy,
|
||||
session_source,
|
||||
agent_identity_session_fallback,
|
||||
} = scope;
|
||||
if let Some(CodexAuth::AgentIdentity(agent_identity_auth)) = auth {
|
||||
return Ok(ResolvedProviderAuth::for_agent_identity(
|
||||
agent_identity_auth.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
if !should_bootstrap_chatgpt_agent_identity(agent_identity_policy, auth)
|
||||
|| agent_identity_session_fallback.is_engaged()
|
||||
{
|
||||
return resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new);
|
||||
}
|
||||
|
||||
let Some(auth_manager) = auth_manager else {
|
||||
return resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new);
|
||||
};
|
||||
|
||||
match auth_manager
|
||||
.agent_identity_auth(agent_identity_policy, session_source)
|
||||
.await
|
||||
{
|
||||
Ok(Some(agent_identity_auth)) => Ok(ResolvedProviderAuth::for_agent_identity(
|
||||
agent_identity_auth,
|
||||
)),
|
||||
Ok(None) => resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new),
|
||||
Err(err) => {
|
||||
if let Some(AgentIdentityAuthError::BootstrapUnavailable {
|
||||
operation,
|
||||
attempts,
|
||||
message,
|
||||
}) = err
|
||||
.get_ref()
|
||||
.and_then(|source| source.downcast_ref::<AgentIdentityAuthError>())
|
||||
{
|
||||
let newly_engaged = agent_identity_session_fallback.engage();
|
||||
tracing::warn!(
|
||||
operation,
|
||||
attempts = *attempts,
|
||||
error = %message,
|
||||
newly_engaged,
|
||||
"agent identity bootstrap unavailable; using ChatGPT bearer auth for this session"
|
||||
);
|
||||
resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new)
|
||||
} else {
|
||||
Err(err.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn should_bootstrap_chatgpt_agent_identity(
|
||||
agent_identity_policy: AgentIdentityAuthPolicy,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> bool {
|
||||
agent_identity_policy == AgentIdentityAuthPolicy::ChatGptAuth
|
||||
&& matches!(auth, Some(CodexAuth::Chatgpt(_)))
|
||||
}
|
||||
|
||||
pub(crate) fn bearer_auth_for_provider(
|
||||
provider: &ModelProviderInfo,
|
||||
) -> codex_protocol::error::Result<Option<BearerAuthProvider>> {
|
||||
if let Some(api_key) = provider.api_key()? {
|
||||
return Ok(Some(BearerAuthProvider::new(api_key)));
|
||||
}
|
||||
|
||||
if let Some(token) = provider.experimental_bearer_token.clone() {
|
||||
return Ok(Some(BearerAuthProvider::new(token.into_inner())));
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
/// Select the shared runtime without changing the identity of captured request data.
|
||||
pub async fn auth_provider_for_request(
|
||||
auth: &CodexAuth,
|
||||
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<ResolvedProviderAuth, RuntimeAuthError> {
|
||||
observe_auth_selection(runtime.map(|(_, mode)| *mode), "request", async {
|
||||
match runtime {
|
||||
Some((manager, mode)) => {
|
||||
let manager = Arc::clone(manager);
|
||||
let auth = auth.clone();
|
||||
let selection = crate::runtime_auth::resource_selection(headers)?;
|
||||
let selected = crate::runtime_auth::finish_runtime_selection(async move {
|
||||
manager.auth_for(&auth, &selection).await
|
||||
})
|
||||
.await?;
|
||||
Ok(ResolvedProviderAuth::for_runtime(selected, *mode))
|
||||
}
|
||||
None => {
|
||||
let mut resolved = ResolvedProviderAuth::new(auth_provider_from_auth(auth));
|
||||
resolved.credential = Some(auth.clone());
|
||||
Ok(resolved)
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Record bounded auth-mode and outcome labels without changing the selection result.
|
||||
pub(crate) async fn observe_auth_selection<T, E>(
|
||||
mode: Option<RuntimeAuthMode>,
|
||||
operation: &'static str,
|
||||
selection: impl Future<Output = Result<T, E>>,
|
||||
) -> Result<T, E> {
|
||||
let started = std::time::Instant::now();
|
||||
let result = selection.await;
|
||||
let mode = match mode {
|
||||
None => "ordinary",
|
||||
Some(RuntimeAuthMode::DualHeader) => "dual_header",
|
||||
Some(RuntimeAuthMode::AssertionOnly) => "assertion_only",
|
||||
};
|
||||
let _ = codex_otel::record_global_operation(
|
||||
"codex.auth.selection",
|
||||
"codex.auth.selection.duration",
|
||||
started.elapsed(),
|
||||
&[
|
||||
("mode", mode),
|
||||
("operation", operation),
|
||||
("outcome", if result.is_ok() { "success" } else { "error" }),
|
||||
],
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
/// Builds request-header auth for a first-party Codex credential.
|
||||
pub fn auth_provider_from_auth(auth: &CodexAuth) -> SharedAuthProvider {
|
||||
match auth {
|
||||
CodexAuth::AgentIdentity(auth) => {
|
||||
Arc::new(AgentIdentityAuthProvider { auth: auth.clone() })
|
||||
}
|
||||
CodexAuth::Headers(auth) => Arc::new(HeaderAuthProvider { auth: auth.clone() }),
|
||||
CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_) => {
|
||||
unreachable!("{BEDROCK_API_KEY_UNSUPPORTED_MESSAGE}")
|
||||
}
|
||||
CodexAuth::ApiKey(_)
|
||||
| CodexAuth::Chatgpt(_)
|
||||
| CodexAuth::ChatgptAuthTokens(_)
|
||||
| CodexAuth::PersonalAccessToken(_) => Arc::new(BearerAuthProvider {
|
||||
token: auth.get_token().ok(),
|
||||
account_id: auth.get_account_id(),
|
||||
is_fedramp_account: auth.is_fedramp_account(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds request-header auth that reads the current managed auth snapshot on
|
||||
/// every request while remaining scoped to the expected auth identity.
|
||||
///
|
||||
/// Callers with account-scoped state should pass the same snapshot that keyed
|
||||
/// that state so a later account switch cannot reuse it.
|
||||
pub fn auth_provider_from_auth_manager(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
expected_auth: &CodexAuth,
|
||||
) -> SharedAuthProvider {
|
||||
Arc::new(AuthManagerAuthProvider {
|
||||
auth_manager,
|
||||
expected_auth: expected_auth.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "auth_refresh_tests.rs"]
|
||||
mod auth_refresh_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "auth_tests.rs"]
|
||||
mod tests;
|
||||
263
codex-rs/model-provider/src/auth_refresh_tests.rs
Normal file
263
codex-rs/model-provider/src/auth_refresh_tests.rs
Normal file
@@ -0,0 +1,263 @@
|
||||
//! Verifies that concurrent proactive and unauthorized requests share one OAuth refresh.
|
||||
|
||||
use super::auth_provider_from_auth_manager;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::RefreshTokenError;
|
||||
use codex_login::auth::RefreshTokenFailedError;
|
||||
use codex_login::auth::RefreshTokenFailedReason;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::task::Poll;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::Barrier;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::body_partial_json;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_and_late_rejections_share_one_refresh() {
|
||||
check_concurrent_refresh(RefreshTrigger::Unauthorized).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_proactive_requests_share_one_refresh() {
|
||||
check_concurrent_refresh(RefreshTrigger::Proactive).await;
|
||||
}
|
||||
|
||||
struct RotatingExternalAuth {
|
||||
refreshes: AtomicUsize,
|
||||
barrier: Barrier,
|
||||
}
|
||||
|
||||
impl ExternalAuth for RotatingExternalAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
let token = if self.refreshes.load(Ordering::SeqCst) == 0 {
|
||||
"Bearer initial"
|
||||
} else {
|
||||
"Bearer replacement"
|
||||
};
|
||||
Ok(CodexAuth::Headers(AuthHeaders::new(HeaderMap::from_iter(
|
||||
[(http::header::AUTHORIZATION, HeaderValue::from_static(token))],
|
||||
))))
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_context: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
if self.refreshes.fetch_add(1, Ordering::SeqCst) != 0 {
|
||||
return Err(std::io::Error::other("redundant refresh rejected"));
|
||||
}
|
||||
self.barrier.wait().await;
|
||||
self.resolve().await
|
||||
})
|
||||
}
|
||||
|
||||
fn classify_error(&self, error: std::io::Error) -> RefreshTokenError {
|
||||
RefreshTokenError::Permanent(RefreshTokenFailedError::new(
|
||||
RefreshTokenFailedReason::Other,
|
||||
error.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_external_rejections_share_one_refresh() {
|
||||
let external = Arc::new(RotatingExternalAuth {
|
||||
refreshes: AtomicUsize::new(0),
|
||||
barrier: Barrier::new(2),
|
||||
});
|
||||
let initial = external.resolve().await.unwrap();
|
||||
let manager = AuthManager::from_auth_for_testing(initial.clone());
|
||||
manager.set_external_auth(external.clone()).await.unwrap();
|
||||
let provider = auth_provider_from_auth_manager(manager, &initial);
|
||||
let rejected = provider.to_auth_headers().unwrap();
|
||||
let mut first = provider.refresh_after_unauthorized(rejected.clone());
|
||||
let mut second = provider.refresh_after_unauthorized(rejected.clone());
|
||||
std::future::poll_fn(|cx| {
|
||||
assert!(first.as_mut().poll(cx).is_pending());
|
||||
assert!(second.as_mut().poll(cx).is_pending());
|
||||
Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
external.barrier.wait().await;
|
||||
assert_eq!(tokio::join!(first, second), (true, true));
|
||||
assert!(provider.refresh_after_unauthorized(rejected).await);
|
||||
assert_eq!(external.refreshes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
provider.apply_auth_headers(HeaderMap::new()).await.unwrap()[http::header::AUTHORIZATION],
|
||||
"Bearer replacement"
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RefreshTrigger {
|
||||
Unauthorized,
|
||||
Proactive,
|
||||
}
|
||||
|
||||
async fn check_concurrent_refresh(trigger: RefreshTrigger) {
|
||||
let server = MockServer::start().await;
|
||||
let home = TempDir::new().unwrap();
|
||||
let auth = json!({
|
||||
"tokens": {
|
||||
"id_token": "e30.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoib3JpZ2luYWwtdXNlciIsImNoYXRncHRfYWNjb3VudF9pZCI6Im9yaWdpbmFsLWFjY291bnQifX0.sig",
|
||||
"access_token": "initial-token",
|
||||
"refresh_token": "initial-refresh-token",
|
||||
"account_id": "original-account",
|
||||
"oauth_provenance": {
|
||||
"issuer": server.uri(),
|
||||
"client_id": "concurrent-refresh-test"
|
||||
}
|
||||
},
|
||||
"last_refresh": match trigger {
|
||||
RefreshTrigger::Unauthorized => "2099-01-01T00:00:00Z",
|
||||
RefreshTrigger::Proactive => "2000-01-01T00:00:00Z",
|
||||
}
|
||||
});
|
||||
std::fs::write(
|
||||
home.path().join("auth.json"),
|
||||
serde_json::to_vec(&auth).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let manager = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let provider =
|
||||
auth_provider_from_auth_manager(manager.clone(), &manager.auth_cached().unwrap());
|
||||
let rejected_headers = provider.to_auth_headers().unwrap();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.and(body_partial_json(
|
||||
json!({"refresh_token": "initial-refresh-token"}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"access_token": "replacement-token",
|
||||
"refresh_token": "replacement-refresh-token"
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
// A redundant refresh could permanently fail even though the replacement works.
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.and(body_partial_json(
|
||||
json!({"refresh_token": "replacement-refresh-token"}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
|
||||
"error": "invalid_grant",
|
||||
})))
|
||||
.with_priority(10)
|
||||
.expect(0)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let refresh = || async {
|
||||
match trigger {
|
||||
RefreshTrigger::Unauthorized => {
|
||||
provider
|
||||
.refresh_after_unauthorized(rejected_headers.clone())
|
||||
.await
|
||||
}
|
||||
RefreshTrigger::Proactive => {
|
||||
let headers = provider.apply_auth_headers(HeaderMap::new()).await.unwrap();
|
||||
assert_eq!(
|
||||
headers[http::header::AUTHORIZATION],
|
||||
"Bearer replacement-token"
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut first = Box::pin(refresh());
|
||||
let mut second = Box::pin(refresh());
|
||||
let mut third = Box::pin(refresh());
|
||||
// Queue both waiters before the runtime can service the first OAuth request.
|
||||
std::future::poll_fn(|cx| {
|
||||
assert!(first.as_mut().poll(cx).is_pending());
|
||||
assert!(second.as_mut().poll(cx).is_pending());
|
||||
assert!(third.as_mut().poll(cx).is_pending());
|
||||
Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
assert_eq!(tokio::join!(first, second, third), (true, true, true));
|
||||
// A delayed 401 for the old token also reuses the completed refresh.
|
||||
assert!(
|
||||
provider
|
||||
.refresh_after_unauthorized(rejected_headers.clone())
|
||||
.await
|
||||
);
|
||||
let updated_headers = provider.apply_auth_headers(HeaderMap::new()).await.unwrap();
|
||||
assert_eq!(
|
||||
updated_headers[http::header::AUTHORIZATION],
|
||||
"Bearer replacement-token"
|
||||
);
|
||||
|
||||
// A rejection of the new credential must still be able to refresh again.
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.and(body_partial_json(
|
||||
json!({"refresh_token": "replacement-refresh-token"}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"access_token": "next-token",
|
||||
"refresh_token": "next-refresh-token"
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
assert!(provider.refresh_after_unauthorized(updated_headers).await);
|
||||
assert_eq!(
|
||||
provider.apply_auth_headers(HeaderMap::new()).await.unwrap()[http::header::AUTHORIZATION],
|
||||
"Bearer next-token"
|
||||
);
|
||||
// A permanent failure must not prevent a later guarded reload of fresh credentials.
|
||||
let rejected = provider.to_auth_headers().unwrap();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.and(body_partial_json(
|
||||
json!({"refresh_token": "next-refresh-token"}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
assert!(!provider.refresh_after_unauthorized(rejected.clone()).await);
|
||||
let path = home.path().join("auth.json");
|
||||
let mut stored: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
stored["tokens"]["access_token"] = json!("reloaded-token");
|
||||
std::fs::write(path, serde_json::to_vec(&stored).unwrap()).unwrap();
|
||||
assert!(provider.refresh_after_unauthorized(rejected).await);
|
||||
assert_eq!(
|
||||
provider.to_auth_headers().unwrap()[http::header::AUTHORIZATION],
|
||||
"Bearer reloaded-token"
|
||||
);
|
||||
server.verify().await;
|
||||
}
|
||||
673
codex-rs/model-provider/src/auth_tests.rs
Normal file
673
codex-rs/model-provider/src/auth_tests.rs
Normal file
@@ -0,0 +1,673 @@
|
||||
//! Unit tests for the auth module.
|
||||
|
||||
use codex_agent_identity::generate_agent_key_material;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::auth::AgentIdentityAuthRecord;
|
||||
use codex_login::auth::BedrockApiKeyAuth;
|
||||
use codex_login::auth::login_with_chatgpt_auth_tokens;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_model_provider_info::create_oss_provider_with_base_url;
|
||||
use codex_protocol::account::PlanType;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use http::header::AUTHORIZATION;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::num::NonZeroU64;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
use super::*;
|
||||
|
||||
static NEXT_CODEX_HOME_ID: AtomicUsize = AtomicUsize::new(0);
|
||||
const TEST_CHATGPT_ID_TOKEN: &str = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaHR0cHM6Ly9hcGkub3BlbmFpLmNvbS9hdXRoIjp7ImNoYXRncHRfdXNlcl9pZCI6InVzZXItMTIzNDUiLCJ1c2VyX2lkIjoidXNlci0xMjM0NSIsImNoYXRncHRfcGxhbl90eXBlIjoicHJvIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoiYWNjb3VudC0xMjMifX0.c2ln";
|
||||
|
||||
async fn agent_identity_auth(chatgpt_account_is_fedramp: bool) -> AgentIdentityAuth {
|
||||
let key_material = generate_agent_key_material().expect("generate key material");
|
||||
AgentIdentityAuth::from_record(
|
||||
AgentIdentityAuthRecord {
|
||||
agent_runtime_id: "agent-runtime-1".to_string(),
|
||||
agent_private_key: key_material.private_key_pkcs8_base64,
|
||||
account_id: "account-1".to_string(),
|
||||
chatgpt_user_id: "user-1".to_string(),
|
||||
email: Some("agent@example.com".to_string()),
|
||||
plan_type: PlanType::Plus,
|
||||
chatgpt_account_is_fedramp,
|
||||
task_id: Some("task-run-1".to_string()),
|
||||
},
|
||||
"https://auth.openai.com/api/accounts",
|
||||
&codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await
|
||||
.expect("agent identity auth record should include task id")
|
||||
}
|
||||
|
||||
fn provider_auth_scope(
|
||||
policy: AgentIdentityAuthPolicy,
|
||||
fallback: AgentIdentitySessionFallback,
|
||||
) -> ProviderAuthScope {
|
||||
ProviderAuthScope {
|
||||
agent_identity_policy: policy,
|
||||
session_source: SessionSource::Cli,
|
||||
agent_identity_session_fallback: fallback,
|
||||
}
|
||||
}
|
||||
|
||||
fn test_codex_home() -> PathBuf {
|
||||
let id = NEXT_CODEX_HOME_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"codex-model-provider-agent-identity-{pid}-{id}",
|
||||
pid = std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp codex home");
|
||||
path
|
||||
}
|
||||
|
||||
fn write_chatgpt_auth_json(codex_home: &Path) {
|
||||
let auth_json = json!({
|
||||
"tokens": {
|
||||
"id_token": TEST_CHATGPT_ID_TOKEN,
|
||||
"access_token": "test-access-token",
|
||||
"refresh_token": "test-refresh-token",
|
||||
"account_id": "account-123"
|
||||
},
|
||||
"last_refresh": "2099-01-01T00:00:00Z"
|
||||
});
|
||||
std::fs::write(
|
||||
codex_home.join("auth.json"),
|
||||
serde_json::to_string_pretty(&auth_json).expect("serialize auth.json"),
|
||||
)
|
||||
.expect("write auth.json");
|
||||
}
|
||||
|
||||
async fn chatgpt_auth_manager(
|
||||
agent_identity_authapi_base_url: String,
|
||||
) -> (PathBuf, Arc<AuthManager>, CodexAuth) {
|
||||
let codex_home = test_codex_home();
|
||||
write_chatgpt_auth_json(&codex_home);
|
||||
let auth_manager = AuthManager::shared(
|
||||
codex_home.clone(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await;
|
||||
let auth = auth_manager.auth().await.expect("auth should load");
|
||||
let auth_manager = AuthManager::from_auth_for_testing_with_agent_identity_authapi_base_url(
|
||||
auth.clone(),
|
||||
agent_identity_authapi_base_url,
|
||||
);
|
||||
(codex_home, auth_manager, auth)
|
||||
}
|
||||
|
||||
async fn mount_transient_agent_registration(
|
||||
server: &MockServer,
|
||||
status: u16,
|
||||
registration_count: Arc<AtomicUsize>,
|
||||
) {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/agent/register"))
|
||||
.respond_with(move |_request: &wiremock::Request| {
|
||||
registration_count.fetch_add(1, Ordering::SeqCst);
|
||||
ResponseTemplate::new(status)
|
||||
})
|
||||
.mount(server)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unauthenticated_auth_provider_adds_no_headers() {
|
||||
let provider =
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
||||
let auth = resolve_provider_auth(/*auth*/ None, &provider).expect("auth should resolve");
|
||||
|
||||
assert!(auth.to_auth_headers().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_does_not_inherit_ambient_auth_headers() {
|
||||
let provider =
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
||||
let mut ambient_headers = HeaderMap::new();
|
||||
ambient_headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer ambient-token"),
|
||||
);
|
||||
ambient_headers.insert(
|
||||
"ChatGPT-Account-ID",
|
||||
HeaderValue::from_static("account-123"),
|
||||
);
|
||||
for ambient_auth in [
|
||||
CodexAuth::Headers(AuthHeaders::new(ambient_headers)),
|
||||
CodexAuth::from_api_key("sk-proj-fedramp-synthetic-test-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_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() {
|
||||
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";
|
||||
|
||||
for (ambient_key, provider_key, expected_fedramp) in [
|
||||
(project_key, None, true),
|
||||
(service_account_key, None, true),
|
||||
(legacy_key, None, false),
|
||||
(project_key, Some(legacy_key), false),
|
||||
(legacy_key, Some(project_key), true),
|
||||
(legacy_key, Some(service_account_key), true),
|
||||
] {
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
provider.experimental_bearer_token = provider_key.map(Into::into);
|
||||
let ambient_auth = CodexAuth::from_api_key(ambient_key);
|
||||
|
||||
let headers = resolve_provider_auth(Some(&ambient_auth), &provider)
|
||||
.expect("auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap();
|
||||
|
||||
let key = provider_key.unwrap_or(ambient_key);
|
||||
let mut 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);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_uses_command_resolved_auth() {
|
||||
let mut provider =
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses);
|
||||
provider.auth = Some(ModelProviderAuthInfo {
|
||||
command: "print-token".to_string(),
|
||||
args: Vec::new(),
|
||||
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"),
|
||||
});
|
||||
let command_auth = CodexAuth::from_api_key("command-token");
|
||||
|
||||
let headers = resolve_provider_auth(Some(&command_auth), &provider)
|
||||
.expect("auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
headers.get(AUTHORIZATION),
|
||||
Some(&HeaderValue::from_static("Bearer command-token"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_preserves_ambient_auth_headers() {
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let mut expected = HeaderMap::new();
|
||||
expected.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer ambient-token"),
|
||||
);
|
||||
expected.insert(
|
||||
"ChatGPT-Account-ID",
|
||||
HeaderValue::from_static("account-123"),
|
||||
);
|
||||
let ambient_auth = CodexAuth::Headers(AuthHeaders::new(expected.clone()));
|
||||
|
||||
let auth = resolve_provider_auth(Some(&ambient_auth), &provider).expect("auth should resolve");
|
||||
|
||||
assert_eq!(auth.to_auth_headers().unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_auth_adds_predefined_headers() {
|
||||
let mut expected = HeaderMap::new();
|
||||
expected.insert(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer external"),
|
||||
);
|
||||
expected.insert("x-external-auth", HeaderValue::from_static("enabled"));
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(expected.clone()));
|
||||
|
||||
let actual = auth_provider_from_auth(&auth).to_auth_headers().unwrap();
|
||||
|
||||
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_refreshes_but_not_account_switches() {
|
||||
let codex_home = test_codex_home();
|
||||
login_with_chatgpt_auth_tokens(
|
||||
&codex_home,
|
||||
"header.e30.first",
|
||||
"test-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.expect("save initial auth");
|
||||
let auth_manager = Arc::new(
|
||||
AuthManager::new(
|
||||
codex_home.clone(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
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 header.e30.first"))
|
||||
);
|
||||
|
||||
login_with_chatgpt_auth_tokens(
|
||||
&codex_home,
|
||||
"header.e30.reloaded",
|
||||
"test-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.expect("save reloaded auth");
|
||||
|
||||
// Ordinary requests retain the manager's cache until refresh or recovery runs.
|
||||
assert_eq!(
|
||||
provider
|
||||
.apply_auth_headers(HeaderMap::new())
|
||||
.await
|
||||
.expect("cached auth headers"),
|
||||
initial_headers
|
||||
);
|
||||
assert_eq!(
|
||||
tokio::join!(
|
||||
provider.refresh_after_unauthorized(initial_headers.clone()),
|
||||
provider.refresh_after_unauthorized(initial_headers),
|
||||
),
|
||||
(true, true)
|
||||
);
|
||||
|
||||
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 header.e30.reloaded"))
|
||||
);
|
||||
|
||||
login_with_chatgpt_auth_tokens(
|
||||
&codex_home,
|
||||
"header.e30.other-account",
|
||||
"other-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.expect("save switched-account auth");
|
||||
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,
|
||||
Permanent,
|
||||
Policy,
|
||||
}
|
||||
|
||||
struct FailingRefreshAuth {
|
||||
auth: tokio::sync::watch::Receiver<CodexAuth>,
|
||||
barrier: tokio::sync::Barrier,
|
||||
failure: RefreshFailure,
|
||||
}
|
||||
|
||||
impl codex_login::ExternalAuth for FailingRefreshAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.auth.borrow().clone()) })
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_context: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
self.barrier.wait().await;
|
||||
self.barrier.wait().await;
|
||||
Err(std::io::Error::other("refresh service unavailable"))
|
||||
})
|
||||
}
|
||||
|
||||
fn classify_error(&self, error: std::io::Error) -> codex_login::RefreshTokenError {
|
||||
match self.failure {
|
||||
RefreshFailure::Transient => codex_login::RefreshTokenError::Transient(error),
|
||||
RefreshFailure::Permanent => codex_login::auth::RefreshTokenFailedError::new(
|
||||
codex_login::auth::RefreshTokenFailedReason::Other,
|
||||
error.to_string(),
|
||||
)
|
||||
.into(),
|
||||
RefreshFailure::Policy => codex_login::RefreshTokenError::Policy(
|
||||
codex_http_client::NetworkPolicyDenied::Revoked,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_refresh_retries_only_with_newer_credentials() {
|
||||
for failure in [
|
||||
RefreshFailure::Transient,
|
||||
RefreshFailure::Permanent,
|
||||
RefreshFailure::Policy,
|
||||
] {
|
||||
for (token, account, changed) in [
|
||||
("Bearer old", "account", false),
|
||||
("Bearer new", "account", true),
|
||||
("Bearer new", "other-account", false),
|
||||
] {
|
||||
let initial = CodexAuth::Headers(AuthHeaders::new(HeaderMap::from_iter([
|
||||
(AUTHORIZATION, HeaderValue::from_static("Bearer old")),
|
||||
(
|
||||
http::HeaderName::from_static("chatgpt-account-id"),
|
||||
HeaderValue::from_static("account"),
|
||||
),
|
||||
])));
|
||||
let (updates, auth) = tokio::sync::watch::channel(initial.clone());
|
||||
let external = Arc::new(FailingRefreshAuth {
|
||||
auth,
|
||||
barrier: tokio::sync::Barrier::new(2),
|
||||
failure,
|
||||
});
|
||||
let manager = AuthManager::from_auth_for_testing(initial.clone());
|
||||
manager.set_external_auth(external.clone()).await.unwrap();
|
||||
let provider = auth_provider_from_auth_manager(manager.clone(), &initial);
|
||||
let rejected = provider.to_auth_headers().expect("initial auth headers");
|
||||
let recovery = provider.refresh_after_unauthorized(rejected);
|
||||
let concurrent_update = async {
|
||||
external.barrier.wait().await;
|
||||
updates.send_replace(CodexAuth::Headers(AuthHeaders::new(HeaderMap::from_iter(
|
||||
[
|
||||
(AUTHORIZATION, HeaderValue::from_static(token)),
|
||||
(
|
||||
http::HeaderName::from_static("chatgpt-account-id"),
|
||||
HeaderValue::from_static(account),
|
||||
),
|
||||
],
|
||||
))));
|
||||
manager.reload().await;
|
||||
external.barrier.wait().await;
|
||||
};
|
||||
let (retry, ()) = tokio::join!(recovery, concurrent_update);
|
||||
assert_eq!(retry, changed && !matches!(failure, RefreshFailure::Policy));
|
||||
if matches!(failure, RefreshFailure::Permanent) && token == "Bearer old" {
|
||||
// Even a late rejection must not reuse a credential known to have failed.
|
||||
assert!(!provider.refresh_after_unauthorized(HeaderMap::new()).await);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_party_run_scope_uses_agent_assertion_and_exposes_telemetry() {
|
||||
let auth =
|
||||
CodexAuth::AgentIdentity(agent_identity_auth(/*chatgpt_account_is_fedramp*/ false).await);
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
|
||||
let auth = resolve_provider_auth_for_scope(
|
||||
/*auth_manager*/ None,
|
||||
Some(&auth),
|
||||
&provider,
|
||||
provider_auth_scope(
|
||||
AgentIdentityAuthPolicy::JwtOnly,
|
||||
AgentIdentitySessionFallback::default(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("auth should resolve");
|
||||
|
||||
assert_eq!(
|
||||
auth.agent_identity_telemetry,
|
||||
Some(AgentIdentityTelemetry {
|
||||
agent_id: "agent-runtime-1".to_string(),
|
||||
task_id: "task-run-1".to_string(),
|
||||
})
|
||||
);
|
||||
let headers = auth.auth.to_auth_headers().unwrap();
|
||||
assert!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|value| value.starts_with("AgentAssertion "))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_identity_auth_provider_preserves_account_routing_headers() {
|
||||
let auth = agent_identity_auth(/*chatgpt_account_is_fedramp*/ true).await;
|
||||
let provider = auth_provider_from_auth(&CodexAuth::AgentIdentity(auth));
|
||||
|
||||
let headers = provider.to_auth_headers().unwrap();
|
||||
|
||||
assert!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(|value| value.starts_with("AgentAssertion "))
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("ChatGPT-Account-ID")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("account-1")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("X-OpenAI-Fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("true")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chatgpt_bootstrap_unavailable_uses_session_bearer_fallback() {
|
||||
let server = MockServer::start().await;
|
||||
let registration_count = Arc::new(AtomicUsize::new(0));
|
||||
mount_transient_agent_registration(
|
||||
&server,
|
||||
/*status*/ 503,
|
||||
Arc::clone(®istration_count),
|
||||
)
|
||||
.await;
|
||||
let (_codex_home, auth_manager, auth) = chatgpt_auth_manager(server.uri()).await;
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let fallback = AgentIdentitySessionFallback::default();
|
||||
|
||||
let provider_auth = resolve_provider_auth_for_scope(
|
||||
Some(auth_manager),
|
||||
Some(&auth),
|
||||
&provider,
|
||||
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, fallback.clone()),
|
||||
)
|
||||
.await
|
||||
.expect("fallback should resolve bearer auth");
|
||||
|
||||
let headers = provider_auth.auth.to_auth_headers().unwrap();
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("Bearer test-access-token")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("ChatGPT-Account-ID")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("account-123")
|
||||
);
|
||||
assert!(fallback.is_engaged());
|
||||
assert_eq!(registration_count.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chatgpt_session_fallback_skips_later_agent_identity_bootstrap() {
|
||||
let server = MockServer::start().await;
|
||||
let registration_count = Arc::new(AtomicUsize::new(0));
|
||||
mount_transient_agent_registration(
|
||||
&server,
|
||||
/*status*/ 503,
|
||||
Arc::clone(®istration_count),
|
||||
)
|
||||
.await;
|
||||
let (_codex_home, auth_manager, auth) = chatgpt_auth_manager(server.uri()).await;
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let fallback = AgentIdentitySessionFallback::default();
|
||||
|
||||
resolve_provider_auth_for_scope(
|
||||
Some(Arc::clone(&auth_manager)),
|
||||
Some(&auth),
|
||||
&provider,
|
||||
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, fallback.clone()),
|
||||
)
|
||||
.await
|
||||
.expect("first fallback should resolve bearer auth");
|
||||
resolve_provider_auth_for_scope(
|
||||
Some(auth_manager),
|
||||
Some(&auth),
|
||||
&provider,
|
||||
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, fallback),
|
||||
)
|
||||
.await
|
||||
.expect("second fallback should resolve bearer auth");
|
||||
|
||||
assert_eq!(registration_count.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chatgpt_sessions_share_bootstrap_failure_cooldown() {
|
||||
let server = MockServer::start().await;
|
||||
let registration_count = Arc::new(AtomicUsize::new(0));
|
||||
mount_transient_agent_registration(
|
||||
&server,
|
||||
/*status*/ 503,
|
||||
Arc::clone(®istration_count),
|
||||
)
|
||||
.await;
|
||||
let (_codex_home, auth_manager, auth) = chatgpt_auth_manager(server.uri()).await;
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let first_fallback = AgentIdentitySessionFallback::default();
|
||||
let second_fallback = AgentIdentitySessionFallback::default();
|
||||
|
||||
resolve_provider_auth_for_scope(
|
||||
Some(Arc::clone(&auth_manager)),
|
||||
Some(&auth),
|
||||
&provider,
|
||||
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, first_fallback.clone()),
|
||||
)
|
||||
.await
|
||||
.expect("first session fallback should resolve bearer auth");
|
||||
resolve_provider_auth_for_scope(
|
||||
Some(auth_manager),
|
||||
Some(&auth),
|
||||
&provider,
|
||||
provider_auth_scope(
|
||||
AgentIdentityAuthPolicy::ChatGptAuth,
|
||||
second_fallback.clone(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("second session fallback should resolve bearer auth");
|
||||
|
||||
assert!(first_fallback.is_engaged());
|
||||
assert!(second_fallback.is_engaged());
|
||||
assert_eq!(registration_count.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
55
codex-rs/model-provider/src/bearer_auth_provider.rs
Normal file
55
codex-rs/model-provider/src/bearer_auth_provider.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use codex_api::AuthProvider;
|
||||
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
|
||||
use codex_login::auth::is_fedramp_api_key;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
|
||||
/// Bearer-token auth provider for OpenAI-compatible model-provider requests.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct BearerAuthProvider {
|
||||
pub token: Option<String>,
|
||||
pub account_id: 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),
|
||||
account_id: None,
|
||||
is_fedramp_account,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_test(token: Option<&str>, account_id: Option<&str>) -> Self {
|
||||
Self {
|
||||
token: token.map(str::to_string),
|
||||
account_id: account_id.map(str::to_string),
|
||||
is_fedramp_account: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthProvider for BearerAuthProvider {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
|
||||
if let Some(token) = self.token.as_ref()
|
||||
&& let Ok(header) = HeaderValue::from_str(&format!("Bearer {token}"))
|
||||
{
|
||||
let _ = headers.insert(http::header::AUTHORIZATION, header);
|
||||
}
|
||||
if let Some(account_id) = self.account_id.as_ref()
|
||||
&& let Ok(header) = HeaderValue::from_str(account_id)
|
||||
{
|
||||
let _ = headers.insert(CHATGPT_ACCOUNT_ID_HEADER, header);
|
||||
}
|
||||
if self.is_fedramp_account {
|
||||
let _ = headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bearer_auth_provider_tests.rs"]
|
||||
mod tests;
|
||||
61
codex-rs/model-provider/src/bearer_auth_provider_tests.rs
Normal file
61
codex-rs/model-provider/src/bearer_auth_provider_tests.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
//! Unit tests for the bearer_auth_provider module.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn bearer_auth_provider_reports_when_auth_header_will_attach() {
|
||||
let auth = BearerAuthProvider {
|
||||
token: Some("access-token".to_string()),
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
codex_api::auth_header_telemetry(&auth).unwrap(),
|
||||
codex_api::AuthHeaderTelemetry {
|
||||
attached: true,
|
||||
name: Some("authorization"),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_auth_provider_adds_auth_headers() {
|
||||
let auth = BearerAuthProvider::for_test(Some("access-token"), Some("workspace-123"));
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
auth.add_auth_headers(&mut headers).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("Bearer access-token")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("ChatGPT-Account-ID")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("workspace-123")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_auth_provider_adds_fedramp_routing_header_for_fedramp_accounts() {
|
||||
let auth = BearerAuthProvider {
|
||||
token: Some("access-token".to_string()),
|
||||
account_id: Some("workspace-123".to_string()),
|
||||
is_fedramp_account: true,
|
||||
};
|
||||
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")
|
||||
);
|
||||
}
|
||||
60
codex-rs/model-provider/src/capabilities.rs
Normal file
60
codex-rs/model-provider/src/capabilities.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
//! Provider capability defaults and resolution of custom provider overrides.
|
||||
|
||||
use codex_api::is_azure_responses_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::RemoteCompactionSupport;
|
||||
|
||||
/// Optional provider-backed features that Codex may expose at runtime.
|
||||
///
|
||||
/// These capabilities are a provider-owned upper bound. Model and turn settings
|
||||
/// can further restrict the functionality exposed to the model.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ProviderCapabilities {
|
||||
/// Whether requests may include the Responses API `reasoning.summary` parameter.
|
||||
pub reasoning_summaries: bool,
|
||||
pub image_generation: bool,
|
||||
pub web_search: bool,
|
||||
pub external_web_access: bool,
|
||||
pub remote_compaction: RemoteCompactionSupport,
|
||||
}
|
||||
|
||||
impl Default for ProviderCapabilities {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
reasoning_summaries: true,
|
||||
image_generation: true,
|
||||
web_search: true,
|
||||
external_web_access: true,
|
||||
remote_compaction: RemoteCompactionSupport::Unsupported,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
{
|
||||
RemoteCompactionSupport::V2
|
||||
} else {
|
||||
RemoteCompactionSupport::Unsupported
|
||||
},
|
||||
..Self::default()
|
||||
};
|
||||
let overrides = info.capabilities.unwrap_or_default();
|
||||
Self {
|
||||
external_web_access: overrides
|
||||
.external_web_access
|
||||
.unwrap_or(defaults.external_web_access),
|
||||
remote_compaction: overrides
|
||||
.remote_compaction
|
||||
.unwrap_or(defaults.remote_compaction),
|
||||
..defaults
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "capabilities_tests.rs"]
|
||||
mod tests;
|
||||
35
codex-rs/model-provider/src/capabilities_tests.rs
Normal file
35
codex-rs/model-provider/src/capabilities_tests.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use super::*;
|
||||
use crate::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderCapabilities;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn capability_overrides_preserve_unspecified_provider_defaults() {
|
||||
for info in [
|
||||
ModelProviderInfo::default(),
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
ModelProviderInfo {
|
||||
name: "Azure".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
let defaults = create_model_provider(info.clone(), /*auth_manager*/ None).capabilities();
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo {
|
||||
capabilities: Some(ModelProviderCapabilities {
|
||||
external_web_access: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
..info
|
||||
},
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
provider.capabilities(),
|
||||
ProviderCapabilities {
|
||||
external_web_access: false,
|
||||
..defaults
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
39
codex-rs/model-provider/src/catalog_factory.rs
Normal file
39
codex-rs/model-provider/src/catalog_factory.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! Host catalog construction from the provider and credentials selected for a thread.
|
||||
|
||||
use crate::SharedModelProvider;
|
||||
use codex_models_manager::manager::ModelCatalogSettings;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
|
||||
/// Builds catalogs for the selected provider while retaining the host's cache policy.
|
||||
/// Provider-backed implementations must use the supplied provider, which carries the
|
||||
/// current credential owner and runtime mode. Hosts may also supply independent metadata.
|
||||
pub trait ModelCatalogFactory: Send + Sync {
|
||||
fn build(
|
||||
&self,
|
||||
provider: SharedModelProvider,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
api_key_model_discovery_default: bool,
|
||||
) -> SharedModelsManager;
|
||||
|
||||
/// Publish a live discovery setting to existing and future catalogs.
|
||||
/// Sources that do not perform API-key discovery may ignore it.
|
||||
fn set_api_key_model_discovery_enabled(&self, _enabled: bool) {}
|
||||
}
|
||||
|
||||
impl ModelCatalogFactory for ModelCatalogSettings {
|
||||
fn build(
|
||||
&self,
|
||||
provider: SharedModelProvider,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
api_key_model_discovery_default: bool,
|
||||
) -> SharedModelsManager {
|
||||
let mut settings = self.clone();
|
||||
settings.api_key_model_discovery_default = api_key_model_discovery_default;
|
||||
provider.models_manager_with_settings(config_model_catalog, settings)
|
||||
}
|
||||
|
||||
fn set_api_key_model_discovery_enabled(&self, enabled: bool) {
|
||||
ModelCatalogSettings::set_api_key_model_discovery_enabled(self, enabled);
|
||||
}
|
||||
}
|
||||
40
codex-rs/model-provider/src/chatgpt_base_url.rs
Normal file
40
codex-rs/model-provider/src/chatgpt_base_url.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! 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())
|
||||
}
|
||||
}
|
||||
121
codex-rs/model-provider/src/client_auth.rs
Normal file
121
codex-rs/model-provider/src/client_auth.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! Authentication for clients that reuse a connection across requests.
|
||||
|
||||
use crate::ResolvedProviderAuth;
|
||||
use codex_api::AuthError;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_runtime_agent_instance::RuntimeAuthBinding;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use http::HeaderMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Keeps a reusable client's credential source fixed while allowing token refresh.
|
||||
/// Each request resolves fresh auth using the same source as the client transport.
|
||||
#[derive(Clone)]
|
||||
pub struct ClientAuth {
|
||||
source: ClientAuthSource,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum ClientAuthSource {
|
||||
Provider(SharedAuthProvider),
|
||||
Runtime {
|
||||
manager: Arc<RuntimeAuthBinding>,
|
||||
mode: RuntimeAuthMode,
|
||||
source_generation: u64,
|
||||
},
|
||||
}
|
||||
|
||||
impl ClientAuth {
|
||||
pub fn new(provider: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
source: ClientAuthSource::Provider(provider),
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the auth source and matching transport for a reusable client's request headers.
|
||||
/// The caller selects runtime auth only for a supported OpenAI destination.
|
||||
pub async fn for_auth(
|
||||
auth: &CodexAuth,
|
||||
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
factory: HttpClientFactory,
|
||||
headers: &HeaderMap,
|
||||
) -> anyhow::Result<(Self, HttpClientFactory)> {
|
||||
let resolved = crate::auth_provider_for_request(auth, runtime, headers).await?;
|
||||
let factory = resolved.bind_http_client_factory(factory)?;
|
||||
let source = match (runtime, resolved.runtime) {
|
||||
(Some((_, mode)), Some(selected)) => ClientAuthSource::Runtime {
|
||||
manager: Arc::clone(selected.binding()),
|
||||
mode: *mode,
|
||||
source_generation: selected.change_state().source_generation,
|
||||
},
|
||||
_ => ClientAuthSource::Provider(resolved.auth),
|
||||
};
|
||||
Ok((Self { source }, factory))
|
||||
}
|
||||
|
||||
/// Replace ordinary authentication; reject changes to a runtime-bound client.
|
||||
pub fn set_provider(&mut self, provider: SharedAuthProvider) -> Result<(), AuthError> {
|
||||
match &mut self.source {
|
||||
ClientAuthSource::Provider(current) => {
|
||||
*current = provider;
|
||||
Ok(())
|
||||
}
|
||||
ClientAuthSource::Runtime { .. } => Err(AuthError::Build(
|
||||
"cannot replace credentials on a runtime-bound client".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve one request, preserving the source that authenticated the client.
|
||||
pub async fn resolve(&self, headers: &HeaderMap) -> Result<ResolvedProviderAuth, AuthError> {
|
||||
let mode = match &self.source {
|
||||
ClientAuthSource::Provider(_) => None,
|
||||
ClientAuthSource::Runtime { mode, .. } => Some(*mode),
|
||||
};
|
||||
crate::auth::observe_auth_selection(mode, "client_request", async {
|
||||
match &self.source {
|
||||
ClientAuthSource::Provider(provider) => {
|
||||
Ok(ResolvedProviderAuth::new(Arc::clone(provider)))
|
||||
}
|
||||
ClientAuthSource::Runtime {
|
||||
manager,
|
||||
mode,
|
||||
source_generation,
|
||||
} => {
|
||||
let selected =
|
||||
crate::select_runtime_auth_for_source(manager, *source_generation, headers)
|
||||
.await?;
|
||||
Ok(ResolvedProviderAuth::for_runtime(selected, *mode))
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Allow OpenAI requests and the original origin, never an unrelated provider.
|
||||
pub fn validate_destination(&self, base_url: &str, url: &str) -> CodexResult<()> {
|
||||
if matches!(&self.source, ClientAuthSource::Provider(_)) {
|
||||
return Ok(());
|
||||
}
|
||||
crate::validate_runtime_destination(Some(url))?;
|
||||
if codex_runtime_agent_instance::is_openai_api_url(url) {
|
||||
return Ok(());
|
||||
}
|
||||
let origin = |value| {
|
||||
url::Url::parse(value)
|
||||
.map(|url| url.origin())
|
||||
.map_err(std::io::Error::other)
|
||||
};
|
||||
if origin(url)? != origin(base_url)? {
|
||||
return Err(std::io::Error::other(
|
||||
"runtime-authenticated clients cannot send requests to another provider",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
113
codex-rs/model-provider/src/combined_auth.rs
Normal file
113
codex-rs/model-provider/src/combined_auth.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
//! Composes primary provider credentials with independently managed gateway OAuth credentials.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::GatewayAuthManager;
|
||||
use crate::auth::ResolvedProviderAuth;
|
||||
use codex_api::AuthError;
|
||||
use codex_api::AuthHeaderTelemetry;
|
||||
use codex_api::AuthHeadersFuture;
|
||||
use codex_api::AuthProvider;
|
||||
use codex_api::AuthProviderFuture;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_model_provider_info::GatewayOAuthDelivery;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderName;
|
||||
use http::HeaderValue;
|
||||
|
||||
pub(crate) async fn compose_auth(
|
||||
provider: &ModelProviderInfo,
|
||||
manager: Option<&std::result::Result<Arc<GatewayAuthManager>, String>>,
|
||||
mut resolved: ResolvedProviderAuth,
|
||||
) -> Result<ResolvedProviderAuth> {
|
||||
let Some(config) = provider.gateway_oauth.as_ref() else {
|
||||
return Ok(resolved);
|
||||
};
|
||||
provider.validate().map_err(CodexErr::InvalidRequest)?;
|
||||
let manager = manager.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest("gateway_oauth requires auth runtime configuration".into())
|
||||
})?;
|
||||
let manager = manager
|
||||
.as_ref()
|
||||
.map_err(|error| CodexErr::InvalidRequest(error.clone()))?;
|
||||
let token = manager.resolve_access_token().await?;
|
||||
let (name, value) = gateway_header(config.delivery(), &token)?;
|
||||
resolved.auth = Arc::new(CombinedAuth {
|
||||
primary: resolved.auth,
|
||||
name,
|
||||
value,
|
||||
});
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn gateway_header(
|
||||
delivery: &GatewayOAuthDelivery,
|
||||
token: &str,
|
||||
) -> Result<(HeaderName, HeaderValue)> {
|
||||
if token.is_empty() {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"gateway access token is empty".into(),
|
||||
));
|
||||
}
|
||||
let (name, value) = match delivery {
|
||||
GatewayOAuthDelivery::Header { name, scheme } => (
|
||||
HeaderName::from_bytes(name.as_bytes())
|
||||
.map_err(|_| CodexErr::InvalidRequest("invalid gateway header".into()))?,
|
||||
format!("{scheme} {token}"),
|
||||
),
|
||||
GatewayOAuthDelivery::Cookie { name } => (http::header::COOKIE, format!("{name}={token}")),
|
||||
};
|
||||
let mut value = HeaderValue::from_str(&value)
|
||||
.map_err(|_| CodexErr::InvalidRequest("invalid gateway OAuth token header".into()))?;
|
||||
value.set_sensitive(true);
|
||||
Ok((name, value))
|
||||
}
|
||||
|
||||
struct CombinedAuth {
|
||||
primary: SharedAuthProvider,
|
||||
name: HeaderName,
|
||||
value: HeaderValue,
|
||||
}
|
||||
|
||||
impl CombinedAuth {
|
||||
fn insert_gateway_header(&self, headers: &mut HeaderMap) -> std::result::Result<(), AuthError> {
|
||||
if headers.contains_key(&self.name) {
|
||||
return Err(AuthError::Build(format!(
|
||||
"The request already sets the {} header. Choose a different header or cookie in gateway_oauth.delivery for the gateway token.",
|
||||
self.name
|
||||
)));
|
||||
}
|
||||
headers.insert(self.name.clone(), self.value.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthProvider for CombinedAuth {
|
||||
fn auth_header_telemetry(&self) -> std::result::Result<AuthHeaderTelemetry, AuthError> {
|
||||
self.primary.auth_header_telemetry()
|
||||
}
|
||||
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> std::result::Result<(), AuthError> {
|
||||
self.primary.add_auth_headers(headers)?;
|
||||
self.insert_gateway_header(headers)
|
||||
}
|
||||
|
||||
fn apply_auth_headers(&self, headers: HeaderMap) -> AuthHeadersFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let mut headers = self.primary.apply_auth_headers(headers).await?;
|
||||
self.insert_gateway_header(&mut headers)?;
|
||||
Ok(headers)
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_auth(&self, request: codex_http_client::Request) -> AuthProviderFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let mut request = self.primary.apply_auth(request).await?;
|
||||
self.insert_gateway_header(&mut request.headers)?;
|
||||
Ok(request)
|
||||
})
|
||||
}
|
||||
}
|
||||
98
codex-rs/model-provider/src/gateway_auth.rs
Normal file
98
codex-rs/model-provider/src/gateway_auth.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! Resolves credentials for a gateway, using its configured exporter or OAuth session.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::ProviderUnauthorizedRecovery;
|
||||
use crate::gateway_export::GatewayExport;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::GatewayAuthError;
|
||||
use codex_login::OAuthSessionManager;
|
||||
use codex_model_provider_info::GatewayOAuthConfig;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::error::Result;
|
||||
|
||||
/// Resolves gateway request credentials and exposes the optional interactive OAuth session.
|
||||
#[derive(Debug)]
|
||||
pub struct GatewayAuthManager(GatewayCredentialSource);
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GatewayCredentialSource {
|
||||
Export(Arc<GatewayExport>),
|
||||
OAuth(Arc<OAuthSessionManager>),
|
||||
}
|
||||
|
||||
impl GatewayAuthManager {
|
||||
pub(crate) fn new(
|
||||
provider: &ModelProviderInfo,
|
||||
config: &GatewayOAuthConfig,
|
||||
owner: &Arc<AuthManager>,
|
||||
) -> std::result::Result<Self, String> {
|
||||
let state = crate::shared_state::process_shared_state();
|
||||
let source = match config {
|
||||
GatewayOAuthConfig::Export {
|
||||
credential_export, ..
|
||||
} => GatewayCredentialSource::Export(state.gateway_export(
|
||||
provider,
|
||||
credential_export,
|
||||
owner,
|
||||
)),
|
||||
GatewayOAuthConfig::OAuth(settings) => GatewayCredentialSource::OAuth(
|
||||
state
|
||||
.gateway_oauth_session(settings, &owner.runtime_config())
|
||||
.map_err(|_| "failed to create provider OAuth HTTP client".to_string())?,
|
||||
),
|
||||
};
|
||||
Ok(Self(source))
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare_retry(&self) -> ProviderUnauthorizedRecovery {
|
||||
match &self.0 {
|
||||
GatewayCredentialSource::Export(export) => {
|
||||
export.invalidate().await;
|
||||
ProviderUnauthorizedRecovery::Recovered
|
||||
}
|
||||
GatewayCredentialSource::OAuth(_) => ProviderUnauthorizedRecovery::NotConfigured,
|
||||
}
|
||||
}
|
||||
|
||||
/// The session used for explicit sign-in and OAuth status, when configured.
|
||||
pub fn oauth_session(&self) -> Option<Arc<OAuthSessionManager>> {
|
||||
match &self.0 {
|
||||
GatewayCredentialSource::OAuth(session) => Some(Arc::clone(session)),
|
||||
GatewayCredentialSource::Export(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn resolve_access_token(&self) -> Result<Arc<str>> {
|
||||
match &self.0 {
|
||||
GatewayCredentialSource::Export(export) => export.token().await,
|
||||
GatewayCredentialSource::OAuth(session) => session
|
||||
.resolve_access_token()
|
||||
.await
|
||||
.map(Arc::from)
|
||||
.map_err(gateway_auth_error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gateway_auth_error(error: std::io::Error) -> CodexErr {
|
||||
if let Some(login_error) = error
|
||||
.get_ref()
|
||||
.and_then(|source| source.downcast_ref::<GatewayAuthError>())
|
||||
{
|
||||
return match login_error {
|
||||
GatewayAuthError::LoginRequired => {
|
||||
CodexErrorDetails::GatewayLoginRequired(login_error.to_string()).into()
|
||||
}
|
||||
GatewayAuthError::LoginInProgress => CodexErr::InvalidRequest(login_error.to_string()),
|
||||
};
|
||||
}
|
||||
// Issuer errors may echo arbitrary credentials from configured URLs. Keep the
|
||||
// diagnostic safe and bounded, preserving retries for transient failures.
|
||||
CodexErr::Io(std::io::Error::new(
|
||||
error.kind(),
|
||||
"Gateway OAuth authentication failed; check the gateway configuration and credential store.",
|
||||
))
|
||||
}
|
||||
68
codex-rs/model-provider/src/gateway_export.rs
Normal file
68
codex-rs/model-provider/src/gateway_export.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
//! Resolves and caches the configured gateway command's credential for this provider.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_http_client::NetworkPolicy;
|
||||
use codex_model_provider_info::CredentialExportConfig;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub(crate) struct GatewayExport {
|
||||
command: CredentialExportConfig,
|
||||
policy: NetworkPolicy,
|
||||
cached: Mutex<Option<Arc<str>>>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for GatewayExport {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("GatewayExport").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl GatewayExport {
|
||||
pub(crate) fn new(command: CredentialExportConfig, policy: NetworkPolicy) -> Self {
|
||||
Self {
|
||||
command,
|
||||
policy,
|
||||
cached: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn invalidate(&self) {
|
||||
*self.cached.lock().await = None;
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "concurrent cache misses must share a single credential export"
|
||||
)]
|
||||
pub(crate) async fn token(&self) -> Result<Arc<str>> {
|
||||
let mut cached = self.cached.lock().await;
|
||||
if let Some(token) = cached.as_ref() {
|
||||
return Ok(Arc::clone(token));
|
||||
}
|
||||
let policy = self.policy.clone().for_current_account();
|
||||
let permit = policy
|
||||
.acquire_for_unsupported_sdk()
|
||||
.map_err(|error| CodexErr::Fatal(error.to_string()))?;
|
||||
let output = permit
|
||||
.run(codex_login::run_credential_export(&self.command, "Gateway"))
|
||||
.await
|
||||
.map_err(|error| CodexErr::Fatal(error.to_string()))?
|
||||
.map_err(|error| CodexErr::InvalidRequest(error.to_string()))?;
|
||||
let token = std::str::from_utf8(&output)
|
||||
.ok()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty() && value.bytes().all(|b| b.is_ascii_graphic()))
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(
|
||||
"Gateway credential export must print one access token".into(),
|
||||
)
|
||||
})?;
|
||||
let token = Arc::<str>::from(token);
|
||||
*cached = Some(Arc::clone(&token));
|
||||
Ok(token)
|
||||
}
|
||||
}
|
||||
337
codex-rs/model-provider/src/gcp/gcp_tests.rs
Normal file
337
codex-rs/model-provider/src/gcp/gcp_tests.rs
Normal file
@@ -0,0 +1,337 @@
|
||||
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)
|
||||
);
|
||||
}
|
||||
252
codex-rs/model-provider/src/gcp/mod.rs
Normal file
252
codex-rs/model-provider/src/gcp/mod.rs
Normal file
@@ -0,0 +1,252 @@
|
||||
//! 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(/*auth_mode*/ None)
|
||||
}
|
||||
|
||||
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,
|
||||
image_generation: 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;
|
||||
73
codex-rs/model-provider/src/lib.rs
Normal file
73
codex-rs/model-provider/src/lib.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
mod amazon_bedrock;
|
||||
mod auth;
|
||||
mod bearer_auth_provider;
|
||||
mod capabilities;
|
||||
mod catalog_factory;
|
||||
mod chatgpt_base_url;
|
||||
mod client_auth;
|
||||
mod combined_auth;
|
||||
mod gateway_auth;
|
||||
mod gateway_export;
|
||||
mod gcp;
|
||||
mod models_endpoint;
|
||||
mod models_identity;
|
||||
mod provider;
|
||||
mod request_preparation;
|
||||
mod request_setup;
|
||||
mod runtime_auth;
|
||||
mod shared_state;
|
||||
pub mod test_support;
|
||||
mod workspace_routing;
|
||||
pub use workspace_routing::ACCOUNT_ROUTING_HEADER;
|
||||
pub use workspace_routing::ResolvedResponsesProvider;
|
||||
pub use workspace_routing::ResponsesConnectionKey;
|
||||
pub use workspace_routing::WorkspaceRoutingContext;
|
||||
|
||||
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::AgentIdentitySessionFallback;
|
||||
pub use auth::ProviderAuthContext;
|
||||
pub use auth::ProviderAuthScope;
|
||||
pub use auth::ResolvedProviderAuth;
|
||||
pub use auth::auth_provider_for_request;
|
||||
pub use auth::auth_provider_from_auth;
|
||||
pub use auth::auth_provider_from_auth_manager;
|
||||
pub use auth::unauthenticated_auth_provider;
|
||||
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 chatgpt_base_url::ChatgptBaseUrl;
|
||||
pub use chatgpt_base_url::DEFAULT_CHATGPT_BASE_URL;
|
||||
pub use client_auth::ClientAuth;
|
||||
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::CHATGPT_CODEX_BASE_URL;
|
||||
pub use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
pub use codex_model_provider_info::RemoteCompactionSupport;
|
||||
pub use codex_protocol::account::ProviderAccount;
|
||||
pub use gateway_auth::GatewayAuthManager;
|
||||
pub use provider::ModelProvider;
|
||||
pub use provider::ModelProviderFuture;
|
||||
pub use provider::ProviderAccountError;
|
||||
pub use provider::ProviderAccountResult;
|
||||
pub use provider::ProviderAccountState;
|
||||
pub use provider::ProviderAuthRecoveryMessages;
|
||||
pub use provider::ProviderUnauthorizedRecovery;
|
||||
pub use provider::SharedModelProvider;
|
||||
pub use provider::create_model_provider;
|
||||
pub use provider::provider_uses_first_party_auth_path;
|
||||
pub use provider::resolve_api_provider;
|
||||
|
||||
pub use request_preparation::prepare_provider_request;
|
||||
pub use request_setup::ResolvedProviderRequest;
|
||||
pub use request_setup::request_auth_owner;
|
||||
pub use request_setup::resolve_request;
|
||||
pub use runtime_auth::runtime_auth_for_url;
|
||||
pub use runtime_auth::select_runtime_auth_for;
|
||||
pub(crate) use runtime_auth::select_runtime_auth_for_source;
|
||||
pub use runtime_auth::select_runtime_provider;
|
||||
pub use runtime_auth::validate_runtime_destination;
|
||||
pub use runtime_auth::validate_runtime_environment;
|
||||
pub use runtime_auth::validate_runtime_selectors;
|
||||
491
codex-rs/model-provider/src/models_endpoint.rs
Normal file
491
codex-rs/model-provider/src/models_endpoint.rs
Normal file
@@ -0,0 +1,491 @@
|
||||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::GatewayAuthManager;
|
||||
use codex_api::AgentIdentityTelemetry;
|
||||
use codex_api::ModelsClient;
|
||||
use codex_api::RequestTelemetry;
|
||||
use codex_api::ReqwestTransport;
|
||||
use codex_api::TransportError;
|
||||
use codex_api::auth_header_telemetry;
|
||||
use codex_api::map_api_error;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_feedback::FeedbackRequestTags;
|
||||
use codex_feedback::emit_feedback_request_tags_with_auth_env;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthEnvTelemetry;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::collect_auth_env_telemetry;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use codex_login::default_client::create_client_for_route_async;
|
||||
use codex_model_provider_info::CHATGPT_CODEX_BASE_URL;
|
||||
use codex_model_provider_info::GatewayOAuthConfig;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::ModelCatalogOriginator;
|
||||
use codex_models_manager::manager::ModelsEndpointClient;
|
||||
use codex_models_manager::manager::ModelsEndpointFuture;
|
||||
use codex_models_manager::manager::ModelsEndpointResponse;
|
||||
use codex_otel::TelemetryAuthMode;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CoreResult;
|
||||
use codex_response_debug_context::extract_response_debug_context;
|
||||
use codex_response_debug_context::telemetry_transport_error_message;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use http::HeaderMap;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::auth::agent_identity_telemetry;
|
||||
use crate::auth::uses_fedramp_api_key;
|
||||
use crate::combined_auth::compose_auth;
|
||||
use crate::provider::resolve_api_provider;
|
||||
use crate::request_setup::resolve_request_auth;
|
||||
|
||||
const MODELS_REFRESH_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MODELS_ENDPOINT: &str = "/models";
|
||||
const FEDRAMP_CODEX_BASE_URL: &str = "https://gov.chatgpt.com/backend-api/codex";
|
||||
|
||||
/// Provider-owned OpenAI-compatible `/models` endpoint.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
gateway_auth_manager: Option<Result<Arc<GatewayAuthManager>, String>>,
|
||||
transport_builder: Arc<dyn ModelsTransportBuilder>,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
}
|
||||
|
||||
impl OpenAiModelsEndpoint {
|
||||
pub(crate) fn new(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
gateway_auth_manager: Option<Result<Arc<GatewayAuthManager>, String>>,
|
||||
) -> Self {
|
||||
let redirect_policy = if provider_info.model_catalog_url.is_some()
|
||||
|| provider_info
|
||||
.gateway_oauth
|
||||
.as_ref()
|
||||
.is_some_and(GatewayOAuthConfig::uses_credential_export)
|
||||
{
|
||||
ClientRedirectPolicy::Reject
|
||||
} else {
|
||||
ClientRedirectPolicy::Default
|
||||
};
|
||||
Self {
|
||||
runtime_auth: None,
|
||||
provider_info,
|
||||
auth_manager,
|
||||
gateway_auth_manager,
|
||||
transport_builder: Arc::new(RouteAwareModelsTransportBuilder { redirect_policy }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Use the same runtime owner as the harness's model sessions.
|
||||
pub(crate) fn with_runtime_auth(
|
||||
mut self,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
) -> Self {
|
||||
self.runtime_auth = runtime_auth;
|
||||
self
|
||||
}
|
||||
|
||||
async fn auth(&self) -> Option<CodexAuth> {
|
||||
let auth_manager = self.auth_manager.clone()?;
|
||||
// Catalog startup has its own deadline. Let rotating credentials finish
|
||||
// saving even when that caller stops waiting.
|
||||
match tokio::spawn(async move { auth_manager.auth().await }).await {
|
||||
Ok(auth) => auth,
|
||||
Err(error) => {
|
||||
tracing::warn!(?error, "model catalog authentication task failed");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn uses_codex_backend(&self) -> bool {
|
||||
self.auth()
|
||||
.await
|
||||
.as_ref()
|
||||
.is_some_and(CodexAuth::uses_codex_backend)
|
||||
}
|
||||
|
||||
async fn list_models(
|
||||
&self,
|
||||
client_version: &str,
|
||||
http_client_factory: HttpClientFactory,
|
||||
) -> CoreResult<ModelsEndpointResponse> {
|
||||
timeout(
|
||||
MODELS_REFRESH_TIMEOUT,
|
||||
self.fetch_models(client_version, http_client_factory),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| CodexErr::RequestTimeout)?
|
||||
}
|
||||
|
||||
async fn fetch_models(
|
||||
&self,
|
||||
client_version: &str,
|
||||
http_client_factory: HttpClientFactory,
|
||||
) -> CoreResult<ModelsEndpointResponse> {
|
||||
let resolved = resolve_request_auth(
|
||||
self.provider_info.clone(),
|
||||
self.auth_manager.clone(),
|
||||
self.runtime_auth.clone(),
|
||||
/*scope*/ None,
|
||||
self.provider_info
|
||||
.model_catalog_url
|
||||
.as_deref()
|
||||
.map(String::as_str)
|
||||
.or(self.provider_info.base_url.as_deref())
|
||||
.map(str::to_owned),
|
||||
)
|
||||
.await?;
|
||||
let auth = resolved.credential.clone();
|
||||
let metric_auth_mode = if self.has_provider_api_key()
|
||||
|| auth.as_ref().is_some_and(CodexAuth::is_api_key_auth)
|
||||
{
|
||||
"api_key"
|
||||
} else if auth.is_some() {
|
||||
"chatgpt"
|
||||
} else {
|
||||
"none"
|
||||
};
|
||||
let _timer = codex_otel::start_global_timer(
|
||||
"codex.remote_models.fetch_update.duration_ms",
|
||||
&[("auth_mode", metric_auth_mode)],
|
||||
);
|
||||
let identity = crate::models_identity::identity(&self.provider_info, auth.as_ref())?;
|
||||
let auth_mode = auth.as_ref().map(CodexAuth::auth_mode);
|
||||
let mut api_provider = resolve_api_provider(&self.provider_info, auth.as_ref())?;
|
||||
if (auth.as_ref().is_some_and(CodexAuth::is_api_key_auth) || self.has_provider_api_key())
|
||||
&& self.supports_api_key_models()
|
||||
&& self.provider_info.base_url.is_none()
|
||||
&& self.provider_info.model_catalog_url.is_none()
|
||||
{
|
||||
// Codex metadata is served by the Codex backend, not the public /v1/models API.
|
||||
api_provider.base_url = if uses_fedramp_api_key(auth.as_ref(), &self.provider_info)? {
|
||||
FEDRAMP_CODEX_BASE_URL
|
||||
} else {
|
||||
CHATGPT_CODEX_BASE_URL
|
||||
}
|
||||
.to_string();
|
||||
}
|
||||
let http_client_factory = resolved
|
||||
.bind_http_client_factory(http_client_factory)
|
||||
.map_err(|error| map_api_error(error.into()))?;
|
||||
resolved.validate_headers(&api_provider.headers)?;
|
||||
let resolved = compose_auth(
|
||||
&self.provider_info,
|
||||
self.gateway_auth_manager.as_ref(),
|
||||
resolved,
|
||||
)
|
||||
.await?;
|
||||
let api_auth = resolved.auth;
|
||||
let request_url = match self.provider_info.model_catalog_url.as_deref() {
|
||||
Some(catalog_url) => ModelsClient::<ReqwestTransport>::catalog_request_url(
|
||||
&api_provider,
|
||||
catalog_url,
|
||||
client_version,
|
||||
)
|
||||
.map_err(map_api_error)?,
|
||||
None => ModelsClient::<ReqwestTransport>::request_url(&api_provider, client_version),
|
||||
};
|
||||
let auth_telemetry = auth_header_telemetry(api_auth.as_ref())
|
||||
.map_err(|error| map_api_error(error.into()))?;
|
||||
let agent_identity_telemetry = if let Some(CodexAuth::AgentIdentity(auth)) = auth.as_ref() {
|
||||
Some(agent_identity_telemetry(auth))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let request_telemetry: Arc<dyn RequestTelemetry> = Arc::new(ModelsRequestTelemetry {
|
||||
include_response_debug: self.provider_info.model_catalog_url.is_none(),
|
||||
auth_mode: auth_mode.map(|mode| TelemetryAuthMode::from(mode).to_string()),
|
||||
auth_header_attached: auth_telemetry.attached,
|
||||
auth_header_name: auth_telemetry.name,
|
||||
agent_identity_telemetry,
|
||||
auth_env: self.auth_env(),
|
||||
});
|
||||
let (models, etag) = {
|
||||
let transport = self
|
||||
.transport_builder
|
||||
.build(http_client_factory, request_url.clone())
|
||||
.await?;
|
||||
let client = ModelsClient::new(transport, api_provider, api_auth)
|
||||
.with_telemetry(Some(request_telemetry));
|
||||
client
|
||||
.list_models(
|
||||
request_url,
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(|mut error| {
|
||||
if self.provider_info.model_catalog_url.is_some()
|
||||
&& let codex_api::ApiError::Transport(TransportError::Http {
|
||||
url,
|
||||
headers,
|
||||
body,
|
||||
..
|
||||
}) = &mut error
|
||||
{
|
||||
// Provider diagnostics may echo URL credentials or other secrets.
|
||||
*url = None;
|
||||
*headers = None;
|
||||
*body = None;
|
||||
}
|
||||
map_api_error(error)
|
||||
})
|
||||
}?;
|
||||
if self.provider_info.model_catalog_url.is_some() {
|
||||
let mut slugs = HashSet::new();
|
||||
if models
|
||||
.iter()
|
||||
.any(|model| model.slug.trim().is_empty() || !slugs.insert(&model.slug))
|
||||
{
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"model catalog must contain unique, non-empty model slugs".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(ModelsEndpointResponse {
|
||||
models,
|
||||
etag,
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
fn auth_env(&self) -> AuthEnvTelemetry {
|
||||
let codex_api_key_env_enabled = self
|
||||
.auth_manager
|
||||
.as_ref()
|
||||
.is_some_and(|auth_manager| auth_manager.codex_api_key_env_enabled());
|
||||
collect_auth_env_telemetry(&self.provider_info, codex_api_key_env_enabled)
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelsEndpointClient for OpenAiModelsEndpoint {
|
||||
fn for_originator(
|
||||
&self,
|
||||
originator: ModelCatalogOriginator,
|
||||
) -> Option<Arc<dyn ModelsEndpointClient>> {
|
||||
let mut provider_info = self.provider_info.clone();
|
||||
let headers = provider_info.http_headers.get_or_insert_default();
|
||||
headers.retain(|name, _| !name.eq_ignore_ascii_case("originator"));
|
||||
headers.insert("originator".to_string(), originator.as_str().into());
|
||||
if let Some(headers) = &mut provider_info.env_http_headers {
|
||||
headers.retain(|name, _| !name.eq_ignore_ascii_case("originator"));
|
||||
}
|
||||
Some(Arc::new(Self {
|
||||
provider_info,
|
||||
auth_manager: self.auth_manager.clone(),
|
||||
gateway_auth_manager: self.gateway_auth_manager.clone(),
|
||||
runtime_auth: self.runtime_auth.clone(),
|
||||
transport_builder: Arc::clone(&self.transport_builder),
|
||||
}))
|
||||
}
|
||||
|
||||
fn supports_api_key_models(&self) -> bool {
|
||||
self.provider_info.model_catalog_url.is_some()
|
||||
|| (self.provider_info.is_openai() && self.provider_info.base_url.is_none())
|
||||
}
|
||||
|
||||
fn has_provider_api_key(&self) -> bool {
|
||||
self.provider_info.env_key.is_some()
|
||||
|| self.provider_info.experimental_bearer_token.is_some()
|
||||
}
|
||||
|
||||
fn identity(&self) -> Option<String> {
|
||||
let auth = self
|
||||
.auth_manager
|
||||
.as_ref()
|
||||
.and_then(|manager| manager.auth_cached());
|
||||
crate::models_identity::identity(&self.provider_info, auth.as_ref()).ok()
|
||||
}
|
||||
|
||||
fn has_command_auth(&self) -> bool {
|
||||
self.provider_info.has_command_auth()
|
||||
}
|
||||
|
||||
fn uses_codex_backend(&self) -> ModelsEndpointFuture<'_, bool> {
|
||||
Box::pin(OpenAiModelsEndpoint::uses_codex_backend(self))
|
||||
}
|
||||
|
||||
fn list_models<'a>(
|
||||
&'a self,
|
||||
client_version: &'a str,
|
||||
http_client_factory: HttpClientFactory,
|
||||
) -> ModelsEndpointFuture<'a, CoreResult<ModelsEndpointResponse>> {
|
||||
Box::pin(OpenAiModelsEndpoint::list_models(
|
||||
self,
|
||||
client_version,
|
||||
http_client_factory,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
type ModelsTransportFuture<'a> =
|
||||
Pin<Box<dyn Future<Output = std::io::Result<ReqwestTransport>> + Send + 'a>>;
|
||||
|
||||
/// Builds the concrete transport selected for one models request.
|
||||
///
|
||||
/// Implementations must honor the supplied request-time client factory and exact request URL.
|
||||
trait ModelsTransportBuilder: fmt::Debug + Send + Sync {
|
||||
fn build(
|
||||
&self,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_url: String,
|
||||
) -> ModelsTransportFuture<'_>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RouteAwareModelsTransportBuilder {
|
||||
redirect_policy: ClientRedirectPolicy,
|
||||
}
|
||||
|
||||
impl ModelsTransportBuilder for RouteAwareModelsTransportBuilder {
|
||||
fn build(
|
||||
&self,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_url: String,
|
||||
) -> ModelsTransportFuture<'_> {
|
||||
let redirect_policy = self.redirect_policy;
|
||||
Box::pin(async move {
|
||||
let client = create_client_for_route_async(
|
||||
http_client_factory,
|
||||
request_url,
|
||||
ClientRouteClass::Api,
|
||||
redirect_policy,
|
||||
)
|
||||
.await?;
|
||||
let client = match redirect_policy {
|
||||
ClientRedirectPolicy::Default => client,
|
||||
ClientRedirectPolicy::Reject => client.without_request_logging(),
|
||||
};
|
||||
Ok(ReqwestTransport::from_http_client(client))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ModelsRequestTelemetry {
|
||||
include_response_debug: bool,
|
||||
auth_mode: Option<String>,
|
||||
auth_header_attached: bool,
|
||||
auth_header_name: Option<&'static str>,
|
||||
agent_identity_telemetry: Option<AgentIdentityTelemetry>,
|
||||
auth_env: AuthEnvTelemetry,
|
||||
}
|
||||
|
||||
impl RequestTelemetry for ModelsRequestTelemetry {
|
||||
fn on_request(
|
||||
&self,
|
||||
attempt: u64,
|
||||
status: Option<http::StatusCode>,
|
||||
error: Option<&TransportError>,
|
||||
duration: Duration,
|
||||
) {
|
||||
let success = status.is_some_and(|code| code.is_success()) && error.is_none();
|
||||
let error_message = error.map(telemetry_transport_error_message);
|
||||
let response_debug = error
|
||||
.filter(|_| self.include_response_debug)
|
||||
.map(extract_response_debug_context)
|
||||
.unwrap_or_default();
|
||||
let status = status.map(|status| status.as_u16());
|
||||
tracing::event!(
|
||||
target: "codex_otel.log_only",
|
||||
tracing::Level::INFO,
|
||||
event.name = "codex.api_request",
|
||||
duration_ms = %duration.as_millis(),
|
||||
http.response.status_code = status,
|
||||
success = success,
|
||||
error.message = error_message.as_deref(),
|
||||
attempt = attempt,
|
||||
endpoint = MODELS_ENDPOINT,
|
||||
auth.header_attached = self.auth_header_attached,
|
||||
auth.header_name = self.auth_header_name,
|
||||
auth.env_openai_api_key_present = self.auth_env.openai_api_key_env_present,
|
||||
auth.env_codex_api_key_present = self.auth_env.codex_api_key_env_present,
|
||||
auth.env_codex_api_key_enabled = self.auth_env.codex_api_key_env_enabled,
|
||||
auth.env_provider_key_name = self.auth_env.provider_env_key_name.as_deref(),
|
||||
auth.env_provider_key_present = self.auth_env.provider_env_key_present,
|
||||
auth.env_refresh_token_url_override_present = self.auth_env.refresh_token_url_override_present,
|
||||
auth.request_id = response_debug.request_id.as_deref(),
|
||||
auth.cf_ray = response_debug.cf_ray.as_deref(),
|
||||
auth.error = response_debug.auth_error.as_deref(),
|
||||
auth.error_code = response_debug.auth_error_code.as_deref(),
|
||||
auth.mode = self.auth_mode.as_deref(),
|
||||
auth.agent_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.agent_id.as_str()),
|
||||
auth.task_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.task_id.as_str()),
|
||||
);
|
||||
tracing::event!(
|
||||
target: "codex_otel.trace_safe",
|
||||
tracing::Level::INFO,
|
||||
event.name = "codex.api_request",
|
||||
duration_ms = %duration.as_millis(),
|
||||
http.response.status_code = status,
|
||||
success = success,
|
||||
error.message = error_message.as_deref(),
|
||||
attempt = attempt,
|
||||
endpoint = MODELS_ENDPOINT,
|
||||
auth.header_attached = self.auth_header_attached,
|
||||
auth.header_name = self.auth_header_name,
|
||||
auth.env_openai_api_key_present = self.auth_env.openai_api_key_env_present,
|
||||
auth.env_codex_api_key_present = self.auth_env.codex_api_key_env_present,
|
||||
auth.env_codex_api_key_enabled = self.auth_env.codex_api_key_env_enabled,
|
||||
auth.env_provider_key_name = self.auth_env.provider_env_key_name.as_deref(),
|
||||
auth.env_provider_key_present = self.auth_env.provider_env_key_present,
|
||||
auth.env_refresh_token_url_override_present = self.auth_env.refresh_token_url_override_present,
|
||||
auth.request_id = response_debug.request_id.as_deref(),
|
||||
auth.cf_ray = response_debug.cf_ray.as_deref(),
|
||||
auth.error = response_debug.auth_error.as_deref(),
|
||||
auth.error_code = response_debug.auth_error_code.as_deref(),
|
||||
auth.mode = self.auth_mode.as_deref(),
|
||||
auth.agent_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.agent_id.as_str()),
|
||||
auth.task_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.task_id.as_str()),
|
||||
);
|
||||
emit_feedback_request_tags_with_auth_env(
|
||||
&FeedbackRequestTags {
|
||||
endpoint: MODELS_ENDPOINT,
|
||||
auth_header_attached: self.auth_header_attached,
|
||||
auth_header_name: self.auth_header_name,
|
||||
auth_mode: self.auth_mode.as_deref(),
|
||||
auth_retry_after_unauthorized: None,
|
||||
auth_recovery_mode: None,
|
||||
auth_recovery_phase: None,
|
||||
auth_connection_reused: None,
|
||||
auth_request_id: response_debug.request_id.as_deref(),
|
||||
auth_cf_ray: response_debug.cf_ray.as_deref(),
|
||||
auth_error: response_debug.auth_error.as_deref(),
|
||||
auth_error_code: response_debug.auth_error_code.as_deref(),
|
||||
auth_recovery_followup_success: None,
|
||||
auth_recovery_followup_status: None,
|
||||
},
|
||||
&self.auth_env,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_endpoint_timeout_tests.rs"]
|
||||
mod timeout_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_originator_tests.rs"]
|
||||
mod originator_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_endpoint_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_endpoint_runtime_auth_tests.rs"]
|
||||
mod runtime_auth_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_endpoint_refresh_tests.rs"]
|
||||
mod refresh_tests;
|
||||
289
codex-rs/model-provider/src/models_endpoint_refresh_tests.rs
Normal file
289
codex-rs/model-provider/src/models_endpoint_refresh_tests.rs
Normal file
@@ -0,0 +1,289 @@
|
||||
//! A catalog deadline must not interrupt rotating OAuth credentials before persistence.
|
||||
|
||||
use super::*;
|
||||
use base64::Engine;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthRouteConfig;
|
||||
use codex_models_manager::manager::ModelsManager;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::body_partial_json;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Caller {
|
||||
Catalog,
|
||||
Startup,
|
||||
CapturedCredential,
|
||||
SourceGeneration,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_timeout_preserves_refreshed_tokens_with_and_without_runtime_auth() {
|
||||
check_timeout_preserves_refreshed_tokens(Caller::Catalog).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_startup_timeout_preserves_refreshed_tokens() {
|
||||
check_timeout_preserves_refreshed_tokens(Caller::Startup).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_runtime_client_selection_persists_the_rotated_token() {
|
||||
check_timeout_preserves_refreshed_tokens(Caller::CapturedCredential).await;
|
||||
check_timeout_preserves_refreshed_tokens(Caller::SourceGeneration).await;
|
||||
}
|
||||
|
||||
async fn check_timeout_preserves_refreshed_tokens(caller: Caller) {
|
||||
for mode in [
|
||||
None,
|
||||
Some(RuntimeAuthMode::DualHeader),
|
||||
Some(RuntimeAuthMode::AssertionOnly),
|
||||
] {
|
||||
if matches!(
|
||||
caller,
|
||||
Caller::CapturedCredential | Caller::SourceGeneration
|
||||
) && mode != Some(RuntimeAuthMode::DualHeader)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let token = |expires| {
|
||||
let payload = json!({
|
||||
"iss": server.uri(), "session_id": "session-a", "exp": expires,
|
||||
"https://api.openai.com/auth": {
|
||||
"chatgpt_user_id": "user-a", "chatgpt_account_id": "workspace-a",
|
||||
"chatgpt_plan_type": "plus",
|
||||
},
|
||||
});
|
||||
format!(
|
||||
"e30.{}.signature",
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload.to_string())
|
||||
)
|
||||
};
|
||||
let old_token = token(0);
|
||||
let new_token = token(chrono::Utc::now().timestamp() + 3600);
|
||||
let stored = serde_json::from_value(json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {
|
||||
"id_token": old_token, "access_token": old_token,
|
||||
"refresh_token": "refresh-before", "account_id": "workspace-a",
|
||||
"oauth_provenance": {"issuer": server.uri(), "client_id": "test-client"},
|
||||
},
|
||||
"last_refresh": "2020-01-01T00:00:00Z",
|
||||
}))
|
||||
.unwrap();
|
||||
codex_login::save_auth(
|
||||
home.path(),
|
||||
&stored,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
)
|
||||
.unwrap();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.and(body_partial_json(
|
||||
json!({"refresh_token": "refresh-before"}),
|
||||
))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_delay(MODELS_REFRESH_TIMEOUT + Duration::from_secs(1))
|
||||
.set_body_json(json!({
|
||||
"id_token": new_token, "access_token": new_token,
|
||||
"refresh_token": "refresh-after",
|
||||
})),
|
||||
)
|
||||
.up_to_n_times(1)
|
||||
.with_priority(1)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
// Reusing the consumed refresh token must fail, as it would at the issuer.
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
|
||||
"error": {"code": "refresh_token_reused"},
|
||||
})))
|
||||
.with_priority(2)
|
||||
.expect(0)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.and(body_partial_json(
|
||||
json!({"actor_auth": {"credential": new_token}}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a",
|
||||
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
|
||||
})))
|
||||
.expect(u64::from(mode.is_some()))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let credentials = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthRouteConfig::from_http_client_factory(factory.clone()),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let runtime_auth = mode.map(|mode| {
|
||||
(
|
||||
Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/register", server.uri()).parse().unwrap(),
|
||||
)),
|
||||
mode,
|
||||
)
|
||||
});
|
||||
let mut info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
info.env_http_headers = None;
|
||||
let endpoint = Arc::new(
|
||||
OpenAiModelsEndpoint::new(
|
||||
info,
|
||||
Some(Arc::clone(&credentials)),
|
||||
/*gateway_auth_manager*/ None,
|
||||
)
|
||||
.with_runtime_auth(runtime_auth.clone()),
|
||||
);
|
||||
match caller {
|
||||
Caller::CapturedCredential => {
|
||||
let auth = credentials.auth_cached().unwrap();
|
||||
assert!(
|
||||
timeout(
|
||||
MODELS_REFRESH_TIMEOUT,
|
||||
crate::auth_provider_for_request(
|
||||
&auth,
|
||||
runtime_auth.as_ref(),
|
||||
&http::HeaderMap::new()
|
||||
)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
Caller::SourceGeneration => {
|
||||
let generation = credentials
|
||||
.auth_change_state_receiver()
|
||||
.borrow()
|
||||
.source_generation;
|
||||
let runtime = runtime_auth
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.0
|
||||
.bind(Arc::clone(&credentials));
|
||||
assert!(
|
||||
timeout(
|
||||
MODELS_REFRESH_TIMEOUT,
|
||||
crate::select_runtime_auth_for_source(
|
||||
&runtime,
|
||||
generation,
|
||||
&http::HeaderMap::new()
|
||||
)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
Caller::Startup => {
|
||||
let manager = OpenAiModelsManager::new_without_cache(
|
||||
endpoint.clone(),
|
||||
Some(Arc::clone(&credentials)),
|
||||
);
|
||||
manager.refresh_after_auth_change(factory.clone()).await;
|
||||
}
|
||||
Caller::Catalog => {
|
||||
let error = endpoint
|
||||
.list_models("test", factory.clone())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
codex_protocol::error::CodexErrorDetails::RequestTimeout
|
||||
));
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/oauth/token")
|
||||
.count(),
|
||||
1,
|
||||
);
|
||||
|
||||
// Wait through the existing refresh lock; this must reuse the completed refresh.
|
||||
let current = credentials.auth().await.unwrap();
|
||||
assert_eq!(current.get_token().unwrap(), new_token);
|
||||
let saved = codex_login::load_auth_dot_json(
|
||||
home.path(),
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.tokens
|
||||
.unwrap();
|
||||
assert_eq!(saved.access_token, new_token);
|
||||
assert_eq!(saved.refresh_token, "refresh-after");
|
||||
|
||||
endpoint.list_models("test", factory).await.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let models = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path() == "/models")
|
||||
.unwrap();
|
||||
if mode == Some(RuntimeAuthMode::AssertionOnly) {
|
||||
assert!(
|
||||
models.headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("AgentAssertion ")
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
models.headers["authorization"],
|
||||
format!("Bearer {new_token}")
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
models.headers.contains_key("x-openai-agent-assertion"),
|
||||
mode == Some(RuntimeAuthMode::DualHeader)
|
||||
);
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
use super::*;
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_auth_rejects_selectors_that_do_not_match_the_registered_actor() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for selector in ["chatgpt-account-id", "openai-organization"] {
|
||||
let server = MockServer::start().await;
|
||||
let (auth, actor, expected) = if selector == "chatgpt-account-id" {
|
||||
let claims = json!({"session_id": "session-a", "https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"}});
|
||||
let token = format!(
|
||||
"e30.{}.signature",
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())
|
||||
);
|
||||
(
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
&token,
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap(),
|
||||
json!({"kind":"chatgpt", "user_id":"user-a", "account_id":"workspace-a"}),
|
||||
"workspace-a",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
CodexAuth::from_api_key("key-a"),
|
||||
json!({"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":"project-a"}),
|
||||
"org-a",
|
||||
)
|
||||
};
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a", "actor": actor,
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let credentials = AuthManager::from_auth_for_testing(auth);
|
||||
let context = crate::ProviderAuthContext {
|
||||
runtime_auth: Some((runtime_manager(&server, Arc::clone(&credentials)), mode)),
|
||||
credentials,
|
||||
};
|
||||
let mut info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
info.env_http_headers = None;
|
||||
info.http_headers = Some(std::collections::HashMap::from([(
|
||||
selector.into(),
|
||||
expected.into(),
|
||||
)]));
|
||||
let provider = context.model_provider(info.clone());
|
||||
let auth = provider.api_auth().await.unwrap();
|
||||
assert!(
|
||||
auth.to_auth_headers()
|
||||
.unwrap()
|
||||
.contains_key("authorization")
|
||||
);
|
||||
|
||||
info.http_headers = Some(std::collections::HashMap::from([(
|
||||
selector.into(),
|
||||
"different".into(),
|
||||
)]));
|
||||
let provider = context.model_provider(info);
|
||||
let error = provider
|
||||
.api_auth()
|
||||
.await
|
||||
.err()
|
||||
.expect("mismatched selector must be rejected");
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_)
|
||||
));
|
||||
assert!(error.to_string().contains(selector));
|
||||
assert!(!server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_requests_keep_the_selected_project_while_reusing_one_runtime() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-a",
|
||||
"agent_host_id": "host-a",
|
||||
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":"project-a"},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[]})))
|
||||
.expect(4)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
|
||||
let runtime = runtime_manager(&server, Arc::clone(&credentials));
|
||||
let context = crate::ProviderAuthContext {
|
||||
runtime_auth: Some((Arc::clone(&runtime), mode)),
|
||||
credentials: Arc::clone(&credentials),
|
||||
};
|
||||
let projects = [
|
||||
Some("project-a"),
|
||||
Some("project-b"),
|
||||
None,
|
||||
Some("project-a"),
|
||||
];
|
||||
for project in projects {
|
||||
let mut info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
info.env_http_headers = None;
|
||||
let mut headers =
|
||||
std::collections::HashMap::from([("openai-organization".into(), "org-a".into())]);
|
||||
if let Some(project) = project {
|
||||
headers.insert("openai-project".into(), project.into());
|
||||
}
|
||||
info.http_headers = Some(headers);
|
||||
let provider = context.model_provider(info.clone());
|
||||
let request = crate::resolve_request(
|
||||
provider.as_ref(),
|
||||
/*scope*/ None,
|
||||
/*routing*/ None,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(request.runtime_id.as_deref(), Some("runtime-a"));
|
||||
assert_eq!(
|
||||
request
|
||||
.api_provider
|
||||
.headers
|
||||
.get("openai-project")
|
||||
.map(|value| value.to_str().unwrap()),
|
||||
project,
|
||||
);
|
||||
assert!(
|
||||
request
|
||||
.api_auth
|
||||
.to_auth_headers()
|
||||
.unwrap()
|
||||
.contains_key("authorization")
|
||||
);
|
||||
|
||||
info.base_url = Some(server.uri());
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
info,
|
||||
Some(Arc::clone(&credentials)),
|
||||
/*gateway_auth_manager*/ None,
|
||||
)
|
||||
.with_runtime_auth(Some((Arc::clone(&runtime), mode)));
|
||||
endpoint
|
||||
.list_models(
|
||||
"test",
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let models: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/models")
|
||||
.collect();
|
||||
assert_eq!(models.len(), projects.len());
|
||||
for (request, project) in models.into_iter().zip(projects) {
|
||||
assert_eq!(
|
||||
request
|
||||
.headers
|
||||
.get("openai-project")
|
||||
.map(|value| value.to_str().unwrap()),
|
||||
project
|
||||
);
|
||||
assert_eq!(request.headers["openai-organization"], "org-a");
|
||||
match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(request.headers["authorization"], "Bearer key-a");
|
||||
assert!(request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(
|
||||
request.headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("AgentAssertion ")
|
||||
);
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
}
|
||||
}
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_registration_environment_matches_inference_and_catalog() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for (registration_base, destination, matching_destination) in [
|
||||
(
|
||||
"https://chatgpt.com",
|
||||
Some("https://api.openai-staging.com/v1"),
|
||||
"https://eu.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"https://chatgpt-staging.com",
|
||||
Some("https://api.openai.com/v1"),
|
||||
"https://api.openai-staging.com/v1",
|
||||
),
|
||||
(
|
||||
"https://chatgpt-staging.com",
|
||||
None,
|
||||
"https://chatgpt-staging.com/backend-api/codex",
|
||||
),
|
||||
] {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
// Keep external network access disabled even if destination validation regresses.
|
||||
let controller = codex_http_client::NetworkPolicyController::default();
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(controller.policy());
|
||||
let credentials = AuthManager::from_api_key(
|
||||
"ambient-key",
|
||||
codex_login::AuthRuntimeConfig {
|
||||
codex_home: home.path().to_path_buf(),
|
||||
auth_route_config: codex_login::AuthRouteConfig::from_http_client_factory(
|
||||
factory.clone(),
|
||||
),
|
||||
},
|
||||
);
|
||||
let runtime = Arc::new(RuntimeAuthManager::for_chatgpt(
|
||||
Arc::clone(&credentials),
|
||||
"00000000-0000-0000-0000-000000000000".into(),
|
||||
registration_base.into(),
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
));
|
||||
crate::validate_runtime_environment(&runtime, Some(matching_destination)).unwrap();
|
||||
let info = ModelProviderInfo {
|
||||
experimental_bearer_token: Some("provider-key".into()),
|
||||
env_http_headers: None,
|
||||
..ModelProviderInfo::create_openai_provider(destination.map(str::to_owned))
|
||||
};
|
||||
let provider = crate::provider::create_model_provider_with_runtime(
|
||||
info.clone(),
|
||||
Some(Arc::clone(&credentials)),
|
||||
Some((Arc::clone(&runtime), mode)),
|
||||
);
|
||||
let error = provider.request_auth(/*scope*/ None).await.err().unwrap();
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
codex_protocol::error::CodexErrorDetails::InvalidRequest(_)
|
||||
));
|
||||
|
||||
let mut catalog_info = info;
|
||||
if let Some(destination) = destination {
|
||||
catalog_info.base_url = Some(matching_destination.into());
|
||||
catalog_info.model_catalog_url = Some(format!("{destination}/models").into());
|
||||
}
|
||||
let catalog = OpenAiModelsEndpoint::new(
|
||||
catalog_info,
|
||||
Some(credentials),
|
||||
/*gateway_auth_manager*/ None,
|
||||
)
|
||||
.with_runtime_auth(Some((runtime, mode)));
|
||||
let error = catalog.list_models("0.0.0", factory).await.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
codex_protocol::error::CodexErrorDetails::InvalidRequest(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_openai_destinations_do_not_fall_back_to_bearer_auth() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
|
||||
let runtime = runtime_manager(&server, Arc::clone(&credentials));
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
for destination in [
|
||||
"https://unknown.api.openai.com/v1",
|
||||
"http://api.openai.com/v1",
|
||||
"https://api.openai.com:8443/v1",
|
||||
] {
|
||||
let info = ModelProviderInfo::create_openai_provider(Some(destination.into()));
|
||||
let provider = crate::provider::create_model_provider_with_runtime(
|
||||
info.clone(),
|
||||
Some(Arc::clone(&credentials)),
|
||||
Some((Arc::clone(&runtime), mode)),
|
||||
);
|
||||
let error = provider
|
||||
.request_auth(/*scope*/ None)
|
||||
.await
|
||||
.err()
|
||||
.expect("unsupported inference origin");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("does not support this OpenAI endpoint")
|
||||
);
|
||||
let mut catalog_info = info;
|
||||
catalog_info.base_url = Some("https://api.openai.com/v1".into());
|
||||
catalog_info.model_catalog_url = Some(format!("{destination}/models").into());
|
||||
let catalog = OpenAiModelsEndpoint::new(
|
||||
catalog_info,
|
||||
Some(Arc::clone(&credentials)),
|
||||
/*gateway_auth_manager*/ None,
|
||||
)
|
||||
.with_runtime_auth(Some((Arc::clone(&runtime), mode)));
|
||||
let error = catalog
|
||||
.list_models("0.0.0", factory.clone())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("does not support this OpenAI endpoint")
|
||||
);
|
||||
}
|
||||
// An explicitly configured other provider retains its existing bearer auth.
|
||||
let info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
let provider = crate::provider::create_model_provider_with_runtime(
|
||||
info,
|
||||
Some(credentials),
|
||||
Some((runtime, mode)),
|
||||
);
|
||||
let resolved = provider.request_auth(/*scope*/ None).await.unwrap();
|
||||
let headers = resolved
|
||||
.auth
|
||||
.apply_auth_headers(http::HeaderMap::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(headers["authorization"], "Bearer key-a");
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_timeout_keeps_registration_alive_for_the_next_request() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(6)).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-a",
|
||||
"agent_host_id": "host-a",
|
||||
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[]})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
|
||||
let runtime = runtime_manager(&server, Arc::clone(&credentials));
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
provider.env_http_headers = None;
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
provider,
|
||||
Some(credentials),
|
||||
/*gateway_auth_manager*/ None,
|
||||
)
|
||||
.with_runtime_auth(Some((runtime, RuntimeAuthMode::DualHeader)));
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let result = timeout(
|
||||
Duration::from_secs(10),
|
||||
endpoint.list_models("0.0.0", factory.clone()),
|
||||
)
|
||||
.await
|
||||
.expect("catalog timeout must precede the registration client's timeout");
|
||||
assert!(matches!(
|
||||
result.unwrap_err().details(),
|
||||
codex_protocol::error::CodexErrorDetails::RequestTimeout
|
||||
));
|
||||
endpoint.list_models("0.0.0", factory).await.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/register")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_catalog_follows_redirects_without_forwarding_credentials_to_another_origin() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for policy in [
|
||||
OutboundProxyPolicy::ReqwestDefault,
|
||||
OutboundProxyPolicy::RespectSystemProxy,
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let target = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-a",
|
||||
"agent_host_id": "host-a",
|
||||
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(307).insert_header("location", "/same-origin"))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/same-origin"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(302)
|
||||
.insert_header("location", format!("{}/models", target.uri())),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
|
||||
.expect(1)
|
||||
.mount(&target)
|
||||
.await;
|
||||
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
|
||||
let runtime = runtime_manager(&server, Arc::clone(&credentials));
|
||||
let mut info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
info.env_http_headers = None;
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
info,
|
||||
Some(credentials),
|
||||
/*gateway_auth_manager*/ None,
|
||||
)
|
||||
.with_runtime_auth(Some((runtime, mode)));
|
||||
endpoint
|
||||
.list_models("test", HttpClientFactory::new(policy))
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let initial = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path() == "/models")
|
||||
.unwrap();
|
||||
let same_origin = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path() == "/same-origin")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
same_origin.headers.get("authorization"),
|
||||
initial.headers.get("authorization")
|
||||
);
|
||||
assert_eq!(
|
||||
same_origin.headers.get("x-openai-agent-assertion"),
|
||||
initial.headers.get("x-openai-agent-assertion")
|
||||
);
|
||||
match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(initial.headers["authorization"], "Bearer key-a");
|
||||
assert!(initial.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(
|
||||
initial.headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("AgentAssertion ")
|
||||
);
|
||||
assert!(!initial.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
}
|
||||
let redirected = target.received_requests().await.unwrap();
|
||||
assert_eq!(redirected.len(), 1);
|
||||
assert!(!redirected[0].headers.contains_key("authorization"));
|
||||
assert!(
|
||||
!redirected[0]
|
||||
.headers
|
||||
.contains_key("x-openai-agent-assertion")
|
||||
);
|
||||
server.verify().await;
|
||||
target.verify().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime_manager(server: &MockServer, credentials: Arc<AuthManager>) -> Arc<RuntimeAuthManager> {
|
||||
Arc::new(RuntimeAuthManager::new(
|
||||
credentials,
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/register", server.uri()).parse().unwrap(),
|
||||
))
|
||||
}
|
||||
631
codex-rs/model-provider/src/models_endpoint_tests.rs
Normal file
631
codex-rs/model-provider/src/models_endpoint_tests.rs
Normal file
@@ -0,0 +1,631 @@
|
||||
//! Unit tests for the models_endpoint module.
|
||||
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::default_client::RESIDENCY_HEADER_NAME;
|
||||
use codex_login::default_client::ResidencyRequirement;
|
||||
use codex_login::default_client::create_client;
|
||||
use codex_login::default_client::set_default_client_residency_requirement;
|
||||
use codex_models_manager::manager::ModelsManager;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::model_info::model_info_from_slug;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::openai_models::ModelVisibility;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RecordingTransportBuilder {
|
||||
observed_request: Arc<Mutex<Option<(OutboundProxyPolicy, String)>>>,
|
||||
}
|
||||
|
||||
impl ModelsTransportBuilder for RecordingTransportBuilder {
|
||||
fn build(
|
||||
&self,
|
||||
http_client_factory: HttpClientFactory,
|
||||
request_url: String,
|
||||
) -> ModelsTransportFuture<'_> {
|
||||
let observed_request = Arc::clone(&self.observed_request);
|
||||
Box::pin(async move {
|
||||
*observed_request
|
||||
.lock()
|
||||
.expect("observed request lock should not be poisoned") =
|
||||
Some((http_client_factory.outbound_proxy_policy(), request_url));
|
||||
Ok(ReqwestTransport::from_http_client(create_client()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CaptureModelsUrl(Mutex<Option<String>>);
|
||||
|
||||
impl ModelsTransportBuilder for CaptureModelsUrl {
|
||||
fn build(
|
||||
&self,
|
||||
_http_client_factory: HttpClientFactory,
|
||||
request_url: String,
|
||||
) -> ModelsTransportFuture<'_> {
|
||||
*self.0.lock().unwrap() = Some(request_url);
|
||||
Box::pin(async { Err(std::io::Error::other("transport intentionally unavailable")) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_discovery_respects_provider_routing() {
|
||||
let client_version = codex_models_manager::client_version_to_whole();
|
||||
for (api_key, name, base_url, models_url, inference_url) in [
|
||||
(
|
||||
"test-api-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
Some("https://chatgpt.com/backend-api/codex/models"),
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"test-api-key",
|
||||
"OpenAI",
|
||||
Some("https://example.com/codex"),
|
||||
None,
|
||||
"https://example.com/codex",
|
||||
),
|
||||
(
|
||||
"test-api-key",
|
||||
"Azure",
|
||||
Some("https://example.openai.azure.com/openai/v1"),
|
||||
None,
|
||||
"https://example.openai.azure.com/openai/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
Some("https://gov.chatgpt.com/backend-api/codex/models"),
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
Some("https://gov.chatgpt.com/backend-api/codex/models"),
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
Some("https://example.com/codex"),
|
||||
None,
|
||||
"https://example.com/codex",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
"Azure",
|
||||
None,
|
||||
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))
|
||||
},
|
||||
auth_manager: Some(auth.clone()),
|
||||
gateway_auth_manager: None,
|
||||
runtime_auth: None,
|
||||
transport_builder: capture.clone(),
|
||||
});
|
||||
let provider = crate::provider::create_model_provider(
|
||||
endpoint.provider_info.clone(),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
let manager = OpenAiModelsManager::new_without_cache(endpoint, Some(auth));
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
*capture.0.lock().unwrap(),
|
||||
models_url.map(|url| format!("{url}?client_version={client_version}"))
|
||||
);
|
||||
assert_eq!(
|
||||
provider.api_provider().await.unwrap().base_url,
|
||||
inference_url
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_api_key_without_endpoint_overrides_uses_codex_backend() {
|
||||
for (api_key, auth, models_base_url, inference_url) in [
|
||||
(
|
||||
"provider-key",
|
||||
None,
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"provider-key",
|
||||
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
),
|
||||
(
|
||||
"provider-key",
|
||||
Some(CodexAuth::from_api_key("sk-proj-fedramp-ambient-key")),
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-provider-key",
|
||||
None,
|
||||
"https://gov.chatgpt.com/backend-api/codex",
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-provider-key",
|
||||
Some(CodexAuth::from_api_key("legacy-ambient-key")),
|
||||
"https://gov.chatgpt.com/backend-api/codex",
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-provider-key",
|
||||
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
"https://gov.chatgpt.com/backend-api/codex",
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
] {
|
||||
let capture = Arc::new(CaptureModelsUrl(Mutex::new(/*t*/ None)));
|
||||
let auth_manager = auth.map(AuthManager::from_auth_for_testing);
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo {
|
||||
experimental_bearer_token: Some(api_key.into()),
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
},
|
||||
auth_manager: auth_manager.clone(),
|
||||
gateway_auth_manager: None,
|
||||
runtime_auth: None,
|
||||
transport_builder: capture.clone(),
|
||||
});
|
||||
let provider = crate::provider::create_model_provider(
|
||||
endpoint.provider_info.clone(),
|
||||
auth_manager.clone(),
|
||||
);
|
||||
let manager = OpenAiModelsManager::new_without_cache(endpoint, auth_manager);
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
*capture.0.lock().unwrap(),
|
||||
Some(format!(
|
||||
"{models_base_url}/models?client_version={}",
|
||||
codex_models_manager::client_version_to_whole(),
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
provider.api_provider().await.unwrap().base_url,
|
||||
inference_url
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn provider_info_with_command_auth() -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
auth: Some(ModelProviderAuthInfo {
|
||||
command: "print-token".to_string(),
|
||||
args: Vec::new(),
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("timeout should be non-zero"),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: std::env::current_dir()
|
||||
.expect("current dir should be available")
|
||||
.try_into()
|
||||
.expect("current dir should be absolute"),
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_auth_provider_reports_command_auth_without_cached_auth() {
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
provider_info_with_command_auth(),
|
||||
/*auth_manager*/ None,
|
||||
/*gateway_auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert!(endpoint.has_command_auth());
|
||||
let auth = CodexAuth::from_api_key("sk-proj-fedramp-command-key");
|
||||
assert_eq!(
|
||||
resolve_api_provider(&endpoint.provider_info, Some(&auth))
|
||||
.unwrap()
|
||||
.base_url,
|
||||
"https://api.openai.com/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_without_command_auth_reports_no_command_auth() {
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
/*auth_manager*/ None,
|
||||
/*gateway_auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert!(!endpoint.has_command_auth());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_request_uses_request_time_proxy_policy_and_exact_url() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.and(query_param("client_version", "0.0.0"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(ModelsResponse { models: Vec::new() }),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let observed_request = Arc::new(Mutex::new(None));
|
||||
let endpoint = OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo::create_openai_provider(Some(server.uri())),
|
||||
auth_manager: None,
|
||||
gateway_auth_manager: None,
|
||||
runtime_auth: None,
|
||||
transport_builder: Arc::new(RecordingTransportBuilder {
|
||||
observed_request: Arc::clone(&observed_request),
|
||||
}),
|
||||
};
|
||||
|
||||
endpoint
|
||||
.list_models(
|
||||
"0.0.0",
|
||||
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
|
||||
)
|
||||
.await
|
||||
.expect("models request should succeed");
|
||||
|
||||
assert_eq!(
|
||||
*observed_request
|
||||
.lock()
|
||||
.expect("observed request lock should not be poisoned"),
|
||||
Some((
|
||||
OutboundProxyPolicy::RespectSystemProxy,
|
||||
format!("{}/models?client_version=0.0.0", server.uri()),
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_discovery_enforces_managed_residency_over_provider_headers() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.and(header(RESIDENCY_HEADER_NAME, "us"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(ModelsResponse { models: Vec::new() }),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let mut provider_info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
|
||||
provider_info.http_headers = Some(std::collections::HashMap::from([(
|
||||
RESIDENCY_HEADER_NAME.to_string(),
|
||||
"eu".into(),
|
||||
)]));
|
||||
let endpoint = OpenAiModelsEndpoint {
|
||||
provider_info,
|
||||
auth_manager: None,
|
||||
gateway_auth_manager: None,
|
||||
runtime_auth: None,
|
||||
transport_builder: Arc::new(RecordingTransportBuilder {
|
||||
observed_request: Arc::new(Mutex::new(None)),
|
||||
}),
|
||||
};
|
||||
|
||||
set_default_client_residency_requirement(Some(ResidencyRequirement::Us));
|
||||
endpoint
|
||||
.list_models(
|
||||
"0.0.0",
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await
|
||||
.expect("managed residency model discovery should succeed");
|
||||
set_default_client_residency_requirement(/*enforce_residency*/ None);
|
||||
|
||||
assert_eq!(
|
||||
endpoint
|
||||
.provider_info
|
||||
.http_headers
|
||||
.as_ref()
|
||||
.and_then(|headers| headers.get(RESIDENCY_HEADER_NAME)),
|
||||
Some(&"eu".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RotatingAuth(std::sync::atomic::AtomicUsize);
|
||||
|
||||
impl codex_login::ExternalAuth for RotatingAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async move {
|
||||
let generation = self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
Ok(CodexAuth::from_api_key(&format!("token-{generation}")))
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_context: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn command_auth_refresh_fetches_a_catalog_for_the_current_credentials() {
|
||||
use codex_models_manager::manager::ModelsManager;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("initial"));
|
||||
auth.set_external_auth(Arc::new(RotatingAuth(std::sync::atomic::AtomicUsize::new(
|
||||
0,
|
||||
))))
|
||||
.await
|
||||
.unwrap();
|
||||
let model = model_info_from_slug("command-auth-model");
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(ModelsResponse {
|
||||
models: vec![model.clone()],
|
||||
}))
|
||||
.expect(/*r*/ 3)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut provider = provider_info_with_command_auth();
|
||||
provider.base_url = Some(server.uri());
|
||||
// Keep this test independent of the residency override exercised in parallel.
|
||||
provider.http_headers = Some(std::collections::HashMap::from([(
|
||||
RESIDENCY_HEADER_NAME.to_string(),
|
||||
"us".into(),
|
||||
)]));
|
||||
let manager = OpenAiModelsManager::new_without_cache(
|
||||
Arc::new(OpenAiModelsEndpoint::new(
|
||||
provider,
|
||||
Some(auth.clone()),
|
||||
/*gateway_auth_manager*/ None,
|
||||
)),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
let catalog = manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::OnlineIfUncached,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.find(|candidate| candidate.slug == model.slug),
|
||||
Some(&model)
|
||||
);
|
||||
// The cached identity still matches here; resolving command auth must
|
||||
// detect the next token before deciding whether a refresh is needed.
|
||||
manager
|
||||
.refresh_after_auth_change(HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault))
|
||||
.await;
|
||||
assert_eq!(manager.get_remote_models().await, catalog.models);
|
||||
auth.auth().await;
|
||||
let bundled = codex_models_manager::bundled_models_response().unwrap();
|
||||
assert_eq!(manager.get_remote_models().await, bundled.models);
|
||||
assert_eq!(manager.try_get_remote_models().unwrap(), bundled.models);
|
||||
assert_eq!(
|
||||
manager
|
||||
.get_model_info(&model.slug, &Default::default())
|
||||
.await,
|
||||
codex_models_manager::CatalogModel {
|
||||
model: model_info_from_slug(&model.slug).into(),
|
||||
origin: codex_models_manager::ModelOrigin::Synthetic,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Offline,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await,
|
||||
bundled
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::OnlineIfUncached,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await,
|
||||
catalog
|
||||
);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.map(|request| request.headers["authorization"].to_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["Bearer token-2", "Bearer token-5", "Bearer token-9"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_catalog_reuses_auth_headers_and_query_parameters() {
|
||||
for auth in [
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
CodexAuth::from_api_key("test-key"),
|
||||
CodexAuth::from_api_key("sk-proj-fedramp-synthetic-test-key"),
|
||||
CodexAuth::from_api_key("sk-svcacct-fedramp-synthetic-test-key"),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let mut model = model_info_from_slug("provider-model");
|
||||
model.visibility = ModelVisibility::List;
|
||||
model.supported_in_api = true;
|
||||
|
||||
let expected = ModelsResponse {
|
||||
models: vec![model],
|
||||
};
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.and(header(
|
||||
"authorization",
|
||||
format!("Bearer {}", auth.get_token().unwrap()),
|
||||
))
|
||||
.and(header("x-provider-header", "preserved"))
|
||||
.and(query_param("deployment", "one"))
|
||||
.and(query_param("api-version", "2026-09"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(&expected))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let auth_manager = AuthManager::from_auth_for_testing(auth);
|
||||
// The parallel residency test must not change this catalog's cache identity.
|
||||
let provider = ModelProviderInfo {
|
||||
model_catalog_url: Some(format!("{}/codex/models?deployment=one", server.uri()).into()),
|
||||
query_params: Some(std::collections::HashMap::from([(
|
||||
"api-version".to_string(),
|
||||
"2026-09".into(),
|
||||
)])),
|
||||
http_headers: Some(std::collections::HashMap::from([
|
||||
("x-provider-header".to_string(), "preserved".into()),
|
||||
(
|
||||
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
|
||||
"us".into(),
|
||||
),
|
||||
])),
|
||||
..ModelProviderInfo::create_openai_provider(Some(format!("{}/v1", server.uri())))
|
||||
};
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
|
||||
provider,
|
||||
Some(auth_manager.clone()),
|
||||
/*gateway_auth_manager*/ None,
|
||||
));
|
||||
let manager = OpenAiModelsManager::new(
|
||||
home.path().to_path_buf(),
|
||||
endpoint,
|
||||
Some(auth_manager.clone()),
|
||||
)
|
||||
.with_provider_catalog();
|
||||
// SIWC does not require the API-key rollout flag.
|
||||
manager.set_api_key_model_discovery_enabled(
|
||||
auth_manager.auth_mode() == Some(codex_protocol::auth::AuthMode::ApiKey),
|
||||
);
|
||||
for _ in 0..2 {
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::OnlineIfUncached,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
)
|
||||
.await,
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_catalog_requires_unique_nonempty_slugs() {
|
||||
for slugs in [vec![" \t"], vec!["private-model", "private-model"]] {
|
||||
let server = MockServer::start().await;
|
||||
let catalog = ModelsResponse {
|
||||
models: slugs.into_iter().map(model_info_from_slug).collect(),
|
||||
};
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(catalog))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
ModelProviderInfo {
|
||||
model_catalog_url: Some(format!("{}/codex/models", server.uri()).into()),
|
||||
..ModelProviderInfo::default()
|
||||
},
|
||||
/*auth_manager*/ None,
|
||||
/*gateway_auth_manager*/ None,
|
||||
);
|
||||
let error = endpoint
|
||||
.list_models(
|
||||
"1.2.3",
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await
|
||||
.expect_err("ambiguous model identity must be rejected");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"model catalog must contain unique, non-empty model slugs"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_catalog_rejects_redirects_without_forwarding_provider_credentials() {
|
||||
let server = MockServer::start().await;
|
||||
let destination = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/codex/models"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(/*s*/ 302)
|
||||
.insert_header("location", format!("{}/codex/models", destination.uri()))
|
||||
.set_body_string("catalog-secret"),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
ModelProviderInfo {
|
||||
base_url: Some(server.uri()),
|
||||
model_catalog_url: Some(
|
||||
format!("{}/codex/models?token=catalog-secret", server.uri()).into(),
|
||||
),
|
||||
experimental_bearer_token: Some("provider-key".into()),
|
||||
..ModelProviderInfo::default()
|
||||
},
|
||||
/*auth_manager*/ None,
|
||||
/*gateway_auth_manager*/ None,
|
||||
);
|
||||
let error = endpoint
|
||||
.list_models(
|
||||
"1.2.3",
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await
|
||||
.expect_err("redirect should be rejected");
|
||||
assert!(!error.to_string().contains("catalog-secret"));
|
||||
assert!(!format!("{error:?}").contains("catalog-secret"));
|
||||
assert_eq!(destination.received_requests().await.unwrap().len(), 0);
|
||||
}
|
||||
67
codex-rs/model-provider/src/models_endpoint_timeout_tests.rs
Normal file
67
codex-rs/model-provider/src/models_endpoint_timeout_tests.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
use super::*;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_deadline_returns_request_timeout() {
|
||||
let server = MockServer::start().await;
|
||||
let mock = Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(serde_json::json!({ "models": [] }))
|
||||
.set_delay(Duration::from_secs(/*secs*/ 60)),
|
||||
)
|
||||
.expect(1)
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let endpoint = OpenAiModelsEndpoint::new(
|
||||
ModelProviderInfo::create_openai_provider(Some(server.uri())),
|
||||
/*auth_manager*/ None,
|
||||
/*gateway_auth_manager*/ None,
|
||||
);
|
||||
|
||||
tokio::time::pause();
|
||||
let request = tokio::time::timeout(
|
||||
MODELS_REFRESH_TIMEOUT * 2,
|
||||
endpoint.list_models(
|
||||
"0.0.0",
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
),
|
||||
);
|
||||
tokio::pin!(request);
|
||||
let received = mock.wait_until_satisfied();
|
||||
tokio::pin!(received);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(/*secs*/ 30);
|
||||
// Keep the paused runtime runnable until the request reaches the server.
|
||||
// Otherwise auto-advance can expire the catalog deadline during dispatch.
|
||||
loop {
|
||||
assert!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"server did not receive the catalog request"
|
||||
);
|
||||
tokio::select! {
|
||||
() = &mut received => break,
|
||||
result = &mut request => {
|
||||
panic!("catalog request finished before reaching the server: {result:?}");
|
||||
}
|
||||
() = tokio::task::yield_now() => {}
|
||||
}
|
||||
}
|
||||
tokio::time::advance(MODELS_REFRESH_TIMEOUT + Duration::from_millis(/*millis*/ 1)).await;
|
||||
let error = request
|
||||
.await
|
||||
.expect("catalog deadline should expire")
|
||||
.expect_err("delayed catalog request should time out");
|
||||
tokio::time::resume();
|
||||
|
||||
assert!(
|
||||
matches!(error.details(), CodexErrorDetails::RequestTimeout),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
112
codex-rs/model-provider/src/models_identity.rs
Normal file
112
codex-rs/model-provider/src/models_identity.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
//! Model catalog cache identity follows provider routing, effective auth, and gateway OAuth config.
|
||||
//! Only a digest is persisted; access tokens for ChatGPT are excluded so token
|
||||
//! rotation does not discard a catalog for the same account, user, and plan.
|
||||
//! Header auth with an account ID uses that identity instead of opaque auth headers.
|
||||
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::Result as CoreResult;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::auth::resolve_provider_auth;
|
||||
use crate::provider::resolve_api_provider;
|
||||
|
||||
pub(crate) fn identity(
|
||||
provider_info: &ModelProviderInfo,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> CoreResult<String> {
|
||||
// Provider bearer overrides replace the login credential and its account metadata.
|
||||
let auth =
|
||||
if provider_info.env_key.is_some() || provider_info.experimental_bearer_token.is_some() {
|
||||
None
|
||||
} else {
|
||||
auth
|
||||
};
|
||||
let mut api_provider = resolve_api_provider(provider_info, auth)?;
|
||||
let mut digest = Sha256::new();
|
||||
// Length-prefix every field to avoid ambiguity between adjacent values.
|
||||
let mut field = |value: &[u8]| {
|
||||
digest.update((value.len() as u64).to_le_bytes());
|
||||
digest.update(value);
|
||||
};
|
||||
field(b"models-cache-v1");
|
||||
field(api_provider.name.as_bytes());
|
||||
field(api_provider.base_url.as_bytes());
|
||||
// Preserve existing cache identities when no explicit catalog is configured.
|
||||
// The API provider resolves base_url defaults; model_catalog_url stays on ModelProviderInfo.
|
||||
if let Some(catalog_url) = &provider_info.model_catalog_url {
|
||||
field(b"model_catalog_url");
|
||||
field(catalog_url.as_bytes());
|
||||
}
|
||||
let mut query: Vec<_> = api_provider.query_params.iter().flatten().collect();
|
||||
query.sort();
|
||||
field(&(query.len() as u64).to_le_bytes());
|
||||
for (name, value) in query {
|
||||
field(name.as_bytes());
|
||||
field(value.as_bytes());
|
||||
}
|
||||
field(&[u8::from(provider_info.requires_openai_auth)]);
|
||||
field(&[u8::from(provider_info.has_command_auth())]);
|
||||
field(format!("{:?}", auth.map(CodexAuth::api_auth_mode)).as_bytes());
|
||||
if let Some(auth) = auth {
|
||||
field(format!("{:?}", auth.get_account_id()).as_bytes());
|
||||
field(format!("{:?}", auth.get_chatgpt_user_id()).as_bytes());
|
||||
field(format!("{:?}", auth.get_account_email()).as_bytes());
|
||||
field(format!("{:?}", auth.account_plan_type()).as_bytes());
|
||||
field(
|
||||
format!(
|
||||
"{:?}",
|
||||
auth.get_token_data()
|
||||
.ok()
|
||||
.and_then(|tokens| tokens.id_token.get_chatgpt_plan_type_raw())
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
field(&[u8::from(auth.is_fedramp_account())]);
|
||||
}
|
||||
let has_stable_account = auth.is_some_and(|auth| {
|
||||
auth.get_account_id().is_some()
|
||||
&& if matches!(auth, CodexAuth::Headers(_)) {
|
||||
!provider_info.has_command_auth()
|
||||
} else {
|
||||
matches!(
|
||||
auth,
|
||||
CodexAuth::Chatgpt(_)
|
||||
| CodexAuth::ChatgptAuthTokens(_)
|
||||
| CodexAuth::AgentIdentity(_)
|
||||
) && (auth.get_chatgpt_user_id().is_some() || auth.get_account_email().is_some())
|
||||
}
|
||||
});
|
||||
let explicit_bearer =
|
||||
provider_info.api_key()?.is_some() || provider_info.experimental_bearer_token.is_some();
|
||||
// Command auth also returns opaque API keys. A changed key may belong to a
|
||||
// different account, so reuse requires stable owner metadata. Explicit provider
|
||||
// keys take precedence over the header auth's account identity.
|
||||
if !has_stable_account || explicit_bearer {
|
||||
let headers = resolve_provider_auth(auth, provider_info)?
|
||||
.to_auth_headers()
|
||||
.map_err(|error| codex_api::map_api_error(error.into()))?;
|
||||
api_provider.headers.extend(headers);
|
||||
}
|
||||
let mut headers: Vec<_> = api_provider.headers.iter().collect();
|
||||
headers.sort_by(|(a, av), (b, bv)| {
|
||||
a.as_str()
|
||||
.cmp(b.as_str())
|
||||
.then(av.as_bytes().cmp(bv.as_bytes()))
|
||||
});
|
||||
field(&(headers.len() as u64).to_le_bytes());
|
||||
for (name, value) in headers {
|
||||
field(name.as_str().as_bytes());
|
||||
field(value.as_bytes());
|
||||
}
|
||||
// Preserve existing identities for providers without gateway OAuth.
|
||||
if let Some(gateway_oauth) = &provider_info.gateway_oauth {
|
||||
field(&serde_json::to_vec(gateway_oauth)?);
|
||||
}
|
||||
Ok(format!("{:x}", digest.finalize()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_identity_tests.rs"]
|
||||
mod tests;
|
||||
142
codex-rs/model-provider/src/models_identity_tests.rs
Normal file
142
codex-rs/model-provider/src/models_identity_tests.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
//! Provider and authentication dimensions that partition model catalogs.
|
||||
|
||||
use super::*;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn chatgpt_auth(email: &str, user: &str, account: &str, plan: &str, signature: &str) -> CodexAuth {
|
||||
let claims = serde_json::json!({
|
||||
"email": email,
|
||||
"https://api.openai.com/auth": {"chatgpt_user_id": user}
|
||||
});
|
||||
let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
&format!("e30.{payload}.{signature}"),
|
||||
account,
|
||||
Some(plan),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_identity_tracks_account_email_user_plan_and_auth_mode_but_not_token_refresh() {
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
// 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(),
|
||||
"us".into(),
|
||||
)]));
|
||||
let initial = chatgpt_auth("one@example.com", "user", "account", "team", "first");
|
||||
let key = identity(&provider, Some(&initial)).unwrap();
|
||||
let refreshed = chatgpt_auth("one@example.com", "user", "account", "team", "second");
|
||||
assert_eq!(identity(&provider, Some(&refreshed)).unwrap(), key);
|
||||
for auth in [
|
||||
chatgpt_auth("two@example.com", "user", "account", "team", "first"),
|
||||
chatgpt_auth("one@example.com", "other", "account", "team", "first"),
|
||||
chatgpt_auth("one@example.com", "user", "other", "team", "first"),
|
||||
chatgpt_auth("one@example.com", "user", "account", "plus", "first"),
|
||||
CodexAuth::from_api_key("api-key"),
|
||||
] {
|
||||
assert_ne!(identity(&provider, Some(&auth)).unwrap(), key);
|
||||
}
|
||||
assert_ne!(identity(&provider, /*auth*/ None).unwrap(), key);
|
||||
}
|
||||
|
||||
#[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 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);
|
||||
let mut other_provider = provider.clone();
|
||||
other_provider.base_url = Some("https://two.example/v1".into());
|
||||
assert_ne!(identity(&other_provider, Some(&auth)).unwrap(), key);
|
||||
other_provider = provider.clone();
|
||||
other_provider.experimental_bearer_token = Some("provider-key".into());
|
||||
assert_ne!(identity(&other_provider, Some(&auth)).unwrap(), key);
|
||||
other_provider = provider;
|
||||
other_provider.http_headers = Some(std::collections::HashMap::from([(
|
||||
"openai-project".into(),
|
||||
"another-project".into(),
|
||||
)]));
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_identity_distinguishes_auth_requirements_and_unknown_plans() {
|
||||
let mut provider =
|
||||
ModelProviderInfo::create_openai_provider(Some("https://example.com/v1".into()));
|
||||
let first = chatgpt_auth(
|
||||
"one@example.com",
|
||||
"user",
|
||||
"account",
|
||||
"future-plan-one",
|
||||
"first",
|
||||
);
|
||||
let second = chatgpt_auth(
|
||||
"one@example.com",
|
||||
"user",
|
||||
"account",
|
||||
"future-plan-two",
|
||||
"first",
|
||||
);
|
||||
let key = identity(&provider, Some(&first)).unwrap();
|
||||
assert_ne!(key, identity(&provider, Some(&second)).unwrap());
|
||||
provider.requires_openai_auth = false;
|
||||
assert_ne!(key, identity(&provider, Some(&first)).unwrap());
|
||||
}
|
||||
|
||||
#[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 bundled = identity(&provider, Some(&auth)).unwrap();
|
||||
provider.model_catalog_url = Some("https://gateway.example/catalog-one".into());
|
||||
let first = identity(&provider, Some(&auth)).unwrap();
|
||||
provider.model_catalog_url = Some("https://gateway.example/catalog-two".into());
|
||||
let second = identity(&provider, Some(&auth)).unwrap();
|
||||
assert_ne!(bundled, first);
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[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()));
|
||||
// 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(),
|
||||
"us".into(),
|
||||
)]));
|
||||
provider.requires_openai_auth = false;
|
||||
provider.experimental_bearer_token = Some("provider-key".into());
|
||||
let identity_without_login = identity(&provider, /*auth*/ None).unwrap();
|
||||
let selected_key = CodexAuth::from_api_key("provider-key");
|
||||
let unused_login = chatgpt_auth("user@example.com", "user", "workspace", "team", "token");
|
||||
for auth in [&selected_key, &unused_login] {
|
||||
assert_eq!(
|
||||
identity(&provider, Some(auth)).unwrap(),
|
||||
identity_without_login
|
||||
);
|
||||
}
|
||||
provider.experimental_bearer_token = Some("different-provider-key".into());
|
||||
assert_ne!(
|
||||
identity(&provider, /*auth*/ None).unwrap(),
|
||||
identity_without_login
|
||||
);
|
||||
}
|
||||
189
codex-rs/model-provider/src/models_originator_tests.rs
Normal file
189
codex-rs/model-provider/src/models_originator_tests.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
//! End-to-end catalog partitioning through provider headers, manager state, and file storage.
|
||||
|
||||
use super::*;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_models_manager::manager::ModelsManager;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::model_info::model_info_from_slug;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
/// Runtime discovery updates reach existing and newly created scopes, including cached catalogs.
|
||||
#[tokio::test]
|
||||
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()));
|
||||
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(),
|
||||
"us".into(),
|
||||
)]));
|
||||
let mut model = model_info_from_slug("gpt-5.5");
|
||||
model.visibility = codex_protocol::openai_models::ModelVisibility::List;
|
||||
|
||||
let catalog = ModelsResponse {
|
||||
models: vec![model],
|
||||
};
|
||||
for originator in ["codex_work_cca", "chatgpt_cca"] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.and(header("originator", originator))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(&catalog))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-key"));
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
|
||||
provider,
|
||||
Some(Arc::clone(&auth)),
|
||||
/*gateway_auth_manager*/ None,
|
||||
));
|
||||
let manager = OpenAiModelsManager::new(home.path().to_path_buf(), endpoint, Some(auth));
|
||||
let work = manager.for_originator("codex_work_cca").unwrap();
|
||||
let bundled = codex_models_manager::bundled_models_response().unwrap();
|
||||
let client = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
assert_eq!(
|
||||
work.raw_model_catalog(RefreshStrategy::Online, client.clone())
|
||||
.await,
|
||||
bundled
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let chat = manager.for_originator("chatgpt_cca").unwrap();
|
||||
for child in [&work, &chat] {
|
||||
assert_eq!(
|
||||
child
|
||||
.raw_model_catalog(RefreshStrategy::OnlineIfUncached, client.clone())
|
||||
.await,
|
||||
catalog
|
||||
);
|
||||
}
|
||||
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ false);
|
||||
for child in [&work, &chat] {
|
||||
assert_eq!(
|
||||
child
|
||||
.raw_model_catalog(RefreshStrategy::Online, client.clone())
|
||||
.await,
|
||||
bundled
|
||||
);
|
||||
assert_eq!(child.try_get_remote_models().unwrap(), bundled.models);
|
||||
}
|
||||
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
for child in [&work, &chat] {
|
||||
assert_eq!(
|
||||
child
|
||||
.raw_model_catalog(RefreshStrategy::OnlineIfUncached, client.clone())
|
||||
.await,
|
||||
catalog
|
||||
);
|
||||
}
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
/// Work, Chat, and legacy callers retain their own catalogs across concurrent access and restarts.
|
||||
#[tokio::test]
|
||||
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()));
|
||||
// The managed-residency test toggles the process-wide US policy. Keep this
|
||||
// provider's cache identity stable whether that policy is enabled or disabled.
|
||||
provider.http_headers = Some(std::collections::HashMap::from([
|
||||
("Originator".to_string(), "provider-default".into()),
|
||||
(
|
||||
codex_model_provider_info::RESIDENCY_HEADER_NAME.to_string(),
|
||||
"us".into(),
|
||||
),
|
||||
]));
|
||||
let mut catalogs = Vec::new();
|
||||
for originator in [
|
||||
"provider-default",
|
||||
"codex_work_cca",
|
||||
"codex_work_web",
|
||||
"codex_work_desktop",
|
||||
"codex_work_mobile",
|
||||
"chatgpt_cca",
|
||||
] {
|
||||
let mut model = model_info_from_slug("gpt-5.5");
|
||||
model.visibility = codex_protocol::openai_models::ModelVisibility::List;
|
||||
|
||||
model.description = Some(originator.to_string());
|
||||
let catalog = ModelsResponse {
|
||||
models: vec![model],
|
||||
};
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.and(header("originator", originator))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(&catalog))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
catalogs.push(catalog);
|
||||
}
|
||||
let client = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
for _ in 0..2 {
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
|
||||
provider.clone(),
|
||||
Some(Arc::clone(&auth)),
|
||||
/*gateway_auth_manager*/ None,
|
||||
));
|
||||
let manager = OpenAiModelsManager::new(home.path().to_path_buf(), endpoint, Some(auth));
|
||||
let work = manager.for_originator("codex_work_cca").unwrap();
|
||||
let chat = manager.for_originator("chatgpt_cca").unwrap();
|
||||
assert!(Arc::ptr_eq(
|
||||
&work,
|
||||
&manager.for_originator("codex_work_cca").unwrap()
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
&chat,
|
||||
&manager.for_originator("chatgpt_cca").unwrap()
|
||||
));
|
||||
let (default_catalog, work_catalog, chat_catalog) = tokio::join!(
|
||||
manager.raw_model_catalog(RefreshStrategy::OnlineIfUncached, client.clone()),
|
||||
work.raw_model_catalog(RefreshStrategy::OnlineIfUncached, client.clone()),
|
||||
chat.raw_model_catalog(RefreshStrategy::OnlineIfUncached, client.clone()),
|
||||
);
|
||||
let mut actual = vec![default_catalog, work_catalog];
|
||||
for originator in ["codex_work_web", "codex_work_desktop", "codex_work_mobile"] {
|
||||
actual.push(
|
||||
manager
|
||||
.for_originator(originator)
|
||||
.unwrap()
|
||||
.raw_model_catalog(RefreshStrategy::OnlineIfUncached, client.clone())
|
||||
.await,
|
||||
);
|
||||
}
|
||||
actual.push(chat_catalog);
|
||||
assert_eq!(actual, catalogs);
|
||||
for originator in [
|
||||
"",
|
||||
"unknown",
|
||||
"codex_cli_rs",
|
||||
"codex_vscode",
|
||||
"chatgpt_cca_local_dev",
|
||||
] {
|
||||
assert!(manager.for_originator(originator).is_none());
|
||||
}
|
||||
}
|
||||
assert!(home.path().join("models_cache.json").exists());
|
||||
assert!(
|
||||
home.path()
|
||||
.join("models_cache.codex_work_cca.json")
|
||||
.exists()
|
||||
);
|
||||
assert!(home.path().join("models_cache.chatgpt_cca.json").exists());
|
||||
}
|
||||
775
codex-rs/model-provider/src/provider.rs
Normal file
775
codex-rs/model-provider/src/provider.rs
Normal file
@@ -0,0 +1,775 @@
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::GatewayAuthManager;
|
||||
use codex_api::ApiError;
|
||||
use codex_api::Provider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_api::TransportError;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::cache::ModelsCache;
|
||||
use codex_models_manager::manager::ModelCatalogSettings;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_models_manager::manager::StaticModelsManager;
|
||||
use codex_protocol::account::ProviderAccount;
|
||||
use codex_protocol::auth::RefreshTokenFailedError;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
|
||||
use crate::ProviderCapabilities;
|
||||
use crate::ResolvedResponsesProvider;
|
||||
use crate::amazon_bedrock::AmazonBedrockModelProvider;
|
||||
use crate::auth::ProviderAuthScope;
|
||||
use crate::auth::ResolvedProviderAuth;
|
||||
use crate::auth::auth_manager_for_provider;
|
||||
use crate::auth::resolve_provider_auth;
|
||||
use crate::auth::resolve_provider_auth_for_scope;
|
||||
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;
|
||||
use crate::workspace_routing::WorkspaceRoutingContext;
|
||||
|
||||
/// Current app-visible account state for a model provider.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderAccountState {
|
||||
pub account: Option<ProviderAccount>,
|
||||
pub requires_openai_auth: bool,
|
||||
}
|
||||
|
||||
/// Outcome of a provider-owned attempt to recover from an authentication failure.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProviderUnauthorizedRecovery {
|
||||
/// The provider has no provider-specific authentication recovery configured.
|
||||
NotConfigured,
|
||||
/// The provider recovered its authentication state and the request can be retried.
|
||||
Recovered,
|
||||
}
|
||||
|
||||
/// User-facing lifecycle messages for provider-owned authentication recovery.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ProviderAuthRecoveryMessages {
|
||||
pub started: &'static str,
|
||||
pub succeeded: &'static str,
|
||||
}
|
||||
|
||||
/// Error returned when a provider cannot construct its app-visible account state.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProviderAccountError {
|
||||
MissingChatgptAccountDetails,
|
||||
UnsupportedBedrockApiKeyAuth,
|
||||
}
|
||||
|
||||
impl fmt::Display for ProviderAccountError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingChatgptAccountDetails => {
|
||||
write!(f, "plan type is required for chatgpt authentication")
|
||||
}
|
||||
Self::UnsupportedBedrockApiKeyAuth => {
|
||||
write!(
|
||||
f,
|
||||
"Bedrock API key auth is only supported by the Amazon Bedrock model provider"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ProviderAccountError {}
|
||||
|
||||
pub type ProviderAccountResult = std::result::Result<ProviderAccountState, ProviderAccountError>;
|
||||
|
||||
/// Default model used for automatic approval review when a provider does not
|
||||
/// require a backend-specific model ID.
|
||||
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";
|
||||
|
||||
/// Default model used for memory consolidation when a provider does not require
|
||||
/// a backend-specific model ID.
|
||||
pub const DEFAULT_MEMORY_CONSOLIDATION_PREFERRED_MODEL: &str = "gpt-6.1-terra";
|
||||
|
||||
/// Runtime provider abstraction used by model execution.
|
||||
///
|
||||
/// Implementations own provider-specific behavior for a model backend. The
|
||||
/// `ModelProviderInfo` returned by `info` is the serialized/configured provider
|
||||
/// metadata used by the default OpenAI-compatible implementation.
|
||||
///
|
||||
/// OpenAI-compatible catalog caches use header auth's account ID instead of auth
|
||||
/// headers when available. Missing IDs and explicit provider API key, bearer, or
|
||||
/// command auth retain credential-sensitive keys. Provider settings remain in the key.
|
||||
/// Hosts using header auth must isolate model managers and cache storage by user and
|
||||
/// catalog-varying request context, such as country: an account ID may identify a
|
||||
/// workspace shared by multiple users. Request authentication, credential refresh,
|
||||
/// and permission checks are unchanged.
|
||||
pub trait ModelProvider: fmt::Debug + Send + Sync {
|
||||
/// Returns the configured provider metadata.
|
||||
fn info(&self) -> &ModelProviderInfo;
|
||||
|
||||
/// Returns whether the resolved Responses provider may receive internal tool metadata.
|
||||
fn include_internal_metadata(&self, provider: &Provider) -> bool {
|
||||
self.info().include_internal_metadata
|
||||
|| url::Url::parse(&provider.base_url).ok().is_some_and(|url| {
|
||||
url.scheme() == "https"
|
||||
&& url.host_str().is_some_and(|host| {
|
||||
host == "api.openai.com" || codex_http_client::is_allowed_chatgpt_host(host)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the provider-owned capability upper bounds.
|
||||
fn capabilities(&self) -> ProviderCapabilities {
|
||||
ProviderCapabilities::default()
|
||||
}
|
||||
|
||||
/// Returns the preferred model used for automatic approval review.
|
||||
///
|
||||
/// Providers that require backend-specific model IDs should override this.
|
||||
fn approval_review_preferred_model(&self) -> &'static str {
|
||||
DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL
|
||||
}
|
||||
|
||||
/// Returns the preferred model used for memory extraction.
|
||||
///
|
||||
/// Providers that require backend-specific model IDs should override this.
|
||||
fn memory_extraction_preferred_model(&self) -> &'static str {
|
||||
DEFAULT_MEMORY_EXTRACTION_PREFERRED_MODEL
|
||||
}
|
||||
|
||||
/// Returns the preferred model used for memory consolidation.
|
||||
///
|
||||
/// Providers that require backend-specific model IDs should override this.
|
||||
fn memory_consolidation_preferred_model(&self) -> &'static str {
|
||||
DEFAULT_MEMORY_CONSOLIDATION_PREFERRED_MODEL
|
||||
}
|
||||
|
||||
/// Returns whether requests made through this provider should include attestation.
|
||||
fn supports_attestation(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Returns the provider-scoped auth manager, when this provider uses one.
|
||||
///
|
||||
/// TODO(celia-oai): Make auth manager access internal to this crate so callers
|
||||
/// resolve provider-specific auth only through `ModelProvider`. We first need
|
||||
/// to think through whether Codex should have a unified provider-specific auth
|
||||
/// manager throughout the codebase; that is a larger refactor than this change.
|
||||
fn auth_manager(&self) -> Option<Arc<AuthManager>>;
|
||||
|
||||
/// Runtime authentication selected for this provider's inference destination.
|
||||
fn runtime_auth(&self) -> Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the gateway credential manager shared with inference and model discovery.
|
||||
/// Hosts use this handle for explicit login; configured setup failures remain errors.
|
||||
fn gateway_auth_manager(&self) -> std::io::Result<Option<Arc<GatewayAuthManager>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Returns whether this transport failure can be recovered by provider-scoped authentication.
|
||||
///
|
||||
/// The default preserves existing unauthorized-response handling. Providers with other
|
||||
/// authentication failure shapes may recognize additional response or request-signing errors.
|
||||
fn is_recoverable_auth_error(&self, error: &TransportError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
TransportError::Http { status, .. } if *status == http::StatusCode::UNAUTHORIZED
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns lifecycle messages when provider-owned authentication recovery is active.
|
||||
fn auth_recovery_messages(&self) -> Option<ProviderAuthRecoveryMessages> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Attempts provider-owned authentication recovery before using the auth manager.
|
||||
fn recover_from_unauthorized(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ProviderUnauthorizedRecovery>> {
|
||||
Box::pin(async { Ok(ProviderUnauthorizedRecovery::NotConfigured) })
|
||||
}
|
||||
|
||||
/// Returns the current provider-scoped auth value, if one is configured.
|
||||
fn auth(&self) -> ModelProviderFuture<'_, Option<CodexAuth>>;
|
||||
|
||||
/// Returns the current app-visible account state for this provider.
|
||||
fn account_state(&self) -> ProviderAccountResult;
|
||||
|
||||
/// Maps an API client error into the provider's user-facing error representation.
|
||||
fn map_api_error(&self, error: ApiError) -> CodexErr {
|
||||
codex_api::map_api_error(error)
|
||||
}
|
||||
|
||||
/// Returns provider configuration adapted for the API client.
|
||||
fn api_provider(&self) -> ModelProviderFuture<'_, codex_protocol::error::Result<Provider>> {
|
||||
Box::pin(async move {
|
||||
let auth = self.auth().await;
|
||||
self.api_provider_for_auth(auth.as_ref())
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves routing for Responses HTTP, compaction, and WebSocket handshakes.
|
||||
fn responses_api_provider<'a>(
|
||||
&'a self,
|
||||
routing_context: &'a WorkspaceRoutingContext,
|
||||
) -> ModelProviderFuture<'a, codex_protocol::error::Result<ResolvedResponsesProvider>> {
|
||||
Box::pin(async move {
|
||||
let provider = self.api_provider().await?;
|
||||
let auth = self.auth().await;
|
||||
self.route_responses_api_provider(provider, auth.as_ref(), routing_context)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies workspace routing using the credentials already selected for this request.
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "serialize discovery and the session's first successful routing transition"
|
||||
)]
|
||||
fn route_responses_api_provider<'a>(
|
||||
&'a self,
|
||||
mut provider: Provider,
|
||||
auth: Option<&'a CodexAuth>,
|
||||
routing_context: &'a WorkspaceRoutingContext,
|
||||
) -> ModelProviderFuture<'a, codex_protocol::error::Result<ResolvedResponsesProvider>> {
|
||||
Box::pin(async move {
|
||||
let mut redirect_policy = ClientRedirectPolicy::Default;
|
||||
if provider_uses_first_party_auth_path(self.info())
|
||||
&& self.info().supports_codex_backend_routes()
|
||||
&& let Some(auth) = auth.filter(|auth| auth.is_chatgpt_auth())
|
||||
&& let Some(auth_manager) = self.auth_manager()
|
||||
{
|
||||
let mut previously_routed = routing_context.previously_routed.lock().await;
|
||||
if let Some(routing) = auth_manager
|
||||
.workspace_routing(
|
||||
auth,
|
||||
WorkspaceRoutingRequest {
|
||||
provider_base_url: provider.base_url.clone(),
|
||||
chatgpt_base_url: routing_context.chatgpt_base_url.clone(),
|
||||
previously_routed: *previously_routed,
|
||||
session: routing_context.session.clone(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|error| match error.downcast::<RefreshTokenFailedError>() {
|
||||
Ok(rejection) => CodexErr::RefreshTokenFailed(rejection),
|
||||
Err(error) => error.into(),
|
||||
})?
|
||||
{
|
||||
crate::workspace_routing::apply_workspace_routing(&mut provider, routing)?;
|
||||
redirect_policy = ClientRedirectPolicy::Reject;
|
||||
*previously_routed = true;
|
||||
}
|
||||
}
|
||||
Ok(ResolvedResponsesProvider {
|
||||
provider,
|
||||
redirect_policy,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Adapt routing from the same frozen credential selected for the request.
|
||||
fn api_provider_for_auth(
|
||||
&self,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> codex_protocol::error::Result<Provider> {
|
||||
resolve_api_provider(self.info(), auth)
|
||||
}
|
||||
|
||||
/// Returns the provider base URL that will be used at request time.
|
||||
fn runtime_base_url(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<Option<String>>> {
|
||||
Box::pin(async { Ok(self.info().base_url.clone()) })
|
||||
}
|
||||
|
||||
/// Returns the auth provider used to attach request credentials.
|
||||
fn api_auth(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<SharedAuthProvider>> {
|
||||
Box::pin(async move {
|
||||
let auth = self.auth().await;
|
||||
resolve_provider_auth(auth.as_ref(), self.info())
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds provider-owned credentials, such as gateway OAuth, to already selected primary auth.
|
||||
fn compose_auth(
|
||||
&self,
|
||||
resolved: ResolvedProviderAuth,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
|
||||
Box::pin(async move { Ok(resolved) })
|
||||
}
|
||||
|
||||
/// Returns request credentials, optionally scoped to a Codex session task.
|
||||
fn api_auth_for_scope(
|
||||
&self,
|
||||
scope: ProviderAuthScope,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
|
||||
Box::pin(async move {
|
||||
if !provider_uses_first_party_auth_path(self.info()) {
|
||||
return self.api_auth().await.map(ResolvedProviderAuth::new);
|
||||
}
|
||||
let auth = self.auth().await;
|
||||
resolve_provider_auth_for_scope(self.auth_manager(), auth.as_ref(), self.info(), scope)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve auth together with metadata needed to route and admit this request.
|
||||
fn request_auth(
|
||||
&self,
|
||||
scope: Option<ProviderAuthScope>,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
|
||||
match scope {
|
||||
Some(scope) => self.api_auth_for_scope(scope),
|
||||
None => Box::pin(async { self.api_auth().await.map(ResolvedProviderAuth::new) }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the endpoint before headers for providers whose setup may refresh credentials.
|
||||
fn request_provider_and_auth(
|
||||
&self,
|
||||
scope: Option<ProviderAuthScope>,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<(Provider, ResolvedProviderAuth)>>
|
||||
{
|
||||
Box::pin(async move { Ok((self.api_provider().await?, self.request_auth(scope).await?)) })
|
||||
}
|
||||
|
||||
/// Creates the model manager implementation appropriate for this provider.
|
||||
fn models_manager(
|
||||
&self,
|
||||
codex_home: PathBuf,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager;
|
||||
|
||||
/// Build a thread catalog with the same cache and live discovery policy as its harness.
|
||||
fn models_manager_with_settings(
|
||||
&self,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
_settings: ModelCatalogSettings,
|
||||
) -> SharedModelsManager {
|
||||
self.models_manager_without_cache(config_model_catalog)
|
||||
}
|
||||
|
||||
/// Creates a model manager with caching disabled.
|
||||
///
|
||||
/// Providers that fetch model catalogs should override this method. The default uses an
|
||||
/// authoritative in-memory catalog so hosted callers cannot accidentally write to disk.
|
||||
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::Bundled
|
||||
};
|
||||
let model_catalog = config_model_catalog
|
||||
.or_else(|| codex_models_manager::bundled_models_response().ok())
|
||||
.unwrap_or_default();
|
||||
Arc::new(StaticModelsManager::new(
|
||||
self.auth_manager(),
|
||||
model_catalog,
|
||||
origin,
|
||||
))
|
||||
}
|
||||
|
||||
/// Creates a model manager that can use a caller-provided cache for remote catalogs.
|
||||
///
|
||||
/// Providers with remote catalogs should override this method. The default preserves the
|
||||
/// authoritative catalog returned by [`ModelProvider::models_manager_without_cache`] and does
|
||||
/// not consult `cache`. Implementations should likewise ignore the cache when
|
||||
/// `config_model_catalog` supplies an authoritative static catalog.
|
||||
fn models_manager_with_cache(
|
||||
&self,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
cache: Arc<dyn ModelsCache>,
|
||||
) -> SharedModelsManager {
|
||||
drop(cache);
|
||||
self.models_manager_without_cache(config_model_catalog)
|
||||
}
|
||||
}
|
||||
|
||||
pub type ModelProviderFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// Shared runtime model provider handle.
|
||||
pub type SharedModelProvider = Arc<dyn ModelProvider>;
|
||||
|
||||
/// Resolve credential-dependent defaults without changing configured endpoints.
|
||||
pub fn resolve_api_provider(
|
||||
info: &ModelProviderInfo,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> codex_protocol::error::Result<Provider> {
|
||||
let mut provider = info.to_api_provider(auth.map(CodexAuth::auth_mode))?;
|
||||
if info.base_url.is_none() && uses_fedramp_api_key(auth, info)? {
|
||||
provider.base_url = FEDRAMP_API_BASE_URL.to_string();
|
||||
}
|
||||
Ok(provider)
|
||||
}
|
||||
|
||||
pub fn provider_uses_first_party_auth_path(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.
|
||||
/// Harnesses with runtime identity use [`crate::ProviderAuthContext::model_provider`].
|
||||
pub fn create_model_provider(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
) -> SharedModelProvider {
|
||||
create_model_provider_with_runtime(provider_info, auth_manager, /*runtime_auth*/ None)
|
||||
}
|
||||
|
||||
pub(crate) fn create_model_provider_with_runtime(
|
||||
provider_info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
) -> 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,
|
||||
runtime_auth,
|
||||
))
|
||||
}
|
||||
|
||||
/// Runtime model provider that orchestrates primary and gateway credentials.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ConfiguredModelProvider {
|
||||
info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
// Construct eagerly; report setup failures when auth is requested because the factory is infallible.
|
||||
gateway_auth_manager: Option<Result<Arc<GatewayAuthManager>, String>>,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
catalog_runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
}
|
||||
|
||||
impl ConfiguredModelProvider {
|
||||
fn new(
|
||||
info: ModelProviderInfo,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
) -> Self {
|
||||
let gateway_auth_manager = info.gateway_oauth.as_ref().map(|config| {
|
||||
info.validate()?;
|
||||
let manager = auth_manager
|
||||
.as_ref()
|
||||
.ok_or_else(|| "gateway_oauth requires auth runtime configuration".to_string())?;
|
||||
GatewayAuthManager::new(&info, config, manager).map(Arc::new)
|
||||
});
|
||||
let auth_manager = auth_manager_for_provider(auth_manager, &info);
|
||||
let runtime_for_destination = |destination: Option<&str>| {
|
||||
runtime_auth.clone().filter(|_| {
|
||||
destination.is_none_or(|url| {
|
||||
codex_http_client::classify_openai_api_url(url)
|
||||
!= codex_http_client::OpenAiDestination::Other
|
||||
})
|
||||
})
|
||||
};
|
||||
let inference_runtime_auth = runtime_for_destination(info.base_url.as_deref());
|
||||
// Catalog overrides are absolute URLs and can have a different origin from inference.
|
||||
let catalog_runtime_auth = runtime_for_destination(
|
||||
info.model_catalog_url
|
||||
.as_deref()
|
||||
.map(String::as_str)
|
||||
.or(info.base_url.as_deref()),
|
||||
);
|
||||
Self {
|
||||
info,
|
||||
auth_manager,
|
||||
gateway_auth_manager,
|
||||
runtime_auth: inference_runtime_auth,
|
||||
catalog_runtime_auth,
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_auth(
|
||||
&self,
|
||||
scope: Option<ProviderAuthScope>,
|
||||
) -> codex_protocol::error::Result<ResolvedProviderAuth> {
|
||||
let resolved = resolve_request_auth(
|
||||
self.info.clone(),
|
||||
self.auth_manager.clone(),
|
||||
self.runtime_auth.clone(),
|
||||
scope,
|
||||
self.info.base_url.clone(),
|
||||
)
|
||||
.await?;
|
||||
self.compose_auth(resolved).await
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelProvider for ConfiguredModelProvider {
|
||||
fn is_recoverable_auth_error(&self, error: &TransportError) -> bool {
|
||||
let TransportError::Http { status, body, .. } = error else {
|
||||
return false;
|
||||
};
|
||||
*status == http::StatusCode::UNAUTHORIZED
|
||||
&& (self.runtime_auth.is_none()
|
||||
|| !codex_protocol::error::is_runtime_auth_denial(
|
||||
*status,
|
||||
body.as_deref().unwrap_or_default(),
|
||||
codex_response_debug_context::extract_response_debug_context(error)
|
||||
.auth_error_code
|
||||
.as_deref(),
|
||||
))
|
||||
}
|
||||
|
||||
fn info(&self) -> &ModelProviderInfo {
|
||||
&self.info
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> ProviderCapabilities {
|
||||
ProviderCapabilities::from_config(&self.info)
|
||||
}
|
||||
|
||||
fn approval_review_preferred_model(&self) -> &'static str {
|
||||
if self
|
||||
.auth_manager
|
||||
.as_ref()
|
||||
.and_then(|auth_manager| auth_manager.auth_cached())
|
||||
.is_some_and(|auth| auth.is_api_key_auth())
|
||||
{
|
||||
API_KEY_APPROVAL_REVIEW_PREFERRED_MODEL
|
||||
} else {
|
||||
DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_manager(&self) -> Option<Arc<AuthManager>> {
|
||||
self.auth_manager.clone()
|
||||
}
|
||||
|
||||
fn gateway_auth_manager(&self) -> std::io::Result<Option<Arc<GatewayAuthManager>>> {
|
||||
self.gateway_auth_manager
|
||||
.clone()
|
||||
.transpose()
|
||||
.map_err(std::io::Error::other)
|
||||
}
|
||||
|
||||
fn recover_from_unauthorized(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ProviderUnauthorizedRecovery>> {
|
||||
Box::pin(async {
|
||||
let Some(gateway) = self.gateway_auth_manager()? else {
|
||||
return Ok(ProviderUnauthorizedRecovery::NotConfigured);
|
||||
};
|
||||
Ok(gateway.prepare_retry().await)
|
||||
})
|
||||
}
|
||||
|
||||
fn supports_attestation(&self) -> bool {
|
||||
self.auth_manager
|
||||
.as_ref()
|
||||
.and_then(|auth_manager| auth_manager.auth_cached())
|
||||
.is_some_and(|auth| auth.is_chatgpt_auth())
|
||||
}
|
||||
|
||||
fn auth(&self) -> ModelProviderFuture<'_, Option<CodexAuth>> {
|
||||
Box::pin(async move {
|
||||
match self.auth_manager.as_ref() {
|
||||
Some(auth_manager) => auth_manager.auth().await,
|
||||
None => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_auth(&self) -> Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)> {
|
||||
self.runtime_auth.as_ref()
|
||||
}
|
||||
|
||||
fn request_auth(
|
||||
&self,
|
||||
scope: Option<ProviderAuthScope>,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
|
||||
Box::pin(self.resolve_auth(scope))
|
||||
}
|
||||
|
||||
fn request_provider_and_auth(
|
||||
&self,
|
||||
scope: Option<ProviderAuthScope>,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<(Provider, ResolvedProviderAuth)>>
|
||||
{
|
||||
Box::pin(async move {
|
||||
let resolved = self.resolve_auth(scope).await?;
|
||||
let provider = self.api_provider_for_auth(resolved.credential.as_ref())?;
|
||||
Ok((provider, resolved))
|
||||
})
|
||||
}
|
||||
|
||||
fn api_auth(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<SharedAuthProvider>> {
|
||||
Box::pin(async move {
|
||||
Ok(self.resolve_auth(/*scope*/ None).await?.auth)
|
||||
})
|
||||
}
|
||||
|
||||
fn compose_auth(
|
||||
&self,
|
||||
resolved: ResolvedProviderAuth,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
|
||||
Box::pin(compose_auth(
|
||||
&self.info,
|
||||
self.gateway_auth_manager.as_ref(),
|
||||
resolved,
|
||||
))
|
||||
}
|
||||
|
||||
fn api_auth_for_scope(
|
||||
&self,
|
||||
scope: ProviderAuthScope,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
|
||||
Box::pin(self.resolve_auth(Some(scope)))
|
||||
}
|
||||
|
||||
fn account_state(&self) -> ProviderAccountResult {
|
||||
let account = if self.info.requires_openai_auth {
|
||||
self.auth_manager
|
||||
.as_ref()
|
||||
.and_then(|auth_manager| {
|
||||
let auth = auth_manager.auth_cached()?;
|
||||
if auth_manager.refresh_failure_for_auth(&auth).is_some() {
|
||||
return None;
|
||||
}
|
||||
if matches!(auth, CodexAuth::Headers(_)) {
|
||||
return None;
|
||||
}
|
||||
Some(auth)
|
||||
})
|
||||
.map(|auth| match &auth {
|
||||
CodexAuth::ApiKey(_) => Ok(ProviderAccount::ApiKey),
|
||||
CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_) => {
|
||||
Err(ProviderAccountError::UnsupportedBedrockApiKeyAuth)
|
||||
}
|
||||
CodexAuth::Chatgpt(_)
|
||||
| CodexAuth::ChatgptAuthTokens(_)
|
||||
| CodexAuth::Headers(_)
|
||||
| CodexAuth::AgentIdentity(_)
|
||||
| CodexAuth::PersonalAccessToken(_) => {
|
||||
let email = auth.get_account_email();
|
||||
let plan_type = auth.account_plan_type();
|
||||
|
||||
plan_type
|
||||
.map(|plan_type| ProviderAccount::Chatgpt { email, plan_type })
|
||||
.ok_or(ProviderAccountError::MissingChatgptAccountDetails)
|
||||
}
|
||||
})
|
||||
.transpose()?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(ProviderAccountState {
|
||||
account,
|
||||
requires_openai_auth: self.info.requires_openai_auth,
|
||||
})
|
||||
}
|
||||
|
||||
fn models_manager(
|
||||
&self,
|
||||
codex_home: PathBuf,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager {
|
||||
self.models_manager_with_settings(
|
||||
config_model_catalog,
|
||||
ModelCatalogSettings::disk(codex_home),
|
||||
)
|
||||
}
|
||||
|
||||
fn models_manager_with_settings(
|
||||
&self,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
settings: ModelCatalogSettings,
|
||||
) -> SharedModelsManager {
|
||||
if let Some(model_catalog) = config_model_catalog {
|
||||
return Arc::new(StaticModelsManager::new(
|
||||
self.auth_manager.clone(),
|
||||
model_catalog,
|
||||
codex_models_manager::ModelOrigin::ExplicitConfig,
|
||||
));
|
||||
}
|
||||
let endpoint = Arc::new(
|
||||
OpenAiModelsEndpoint::new(
|
||||
self.info.clone(),
|
||||
self.auth_manager.clone(),
|
||||
self.gateway_auth_manager.clone(),
|
||||
)
|
||||
.with_runtime_auth(self.catalog_runtime_auth.clone()),
|
||||
);
|
||||
let auth_manager = self.auth_manager.clone();
|
||||
let manager = OpenAiModelsManager::with_settings(settings, endpoint, auth_manager);
|
||||
match &self.info.model_catalog_url {
|
||||
Some(_) => Arc::new(manager.with_provider_catalog()),
|
||||
None => Arc::new(manager),
|
||||
}
|
||||
}
|
||||
|
||||
fn models_manager_without_cache(
|
||||
&self,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager {
|
||||
self.models_manager_with_settings(config_model_catalog, ModelCatalogSettings::default())
|
||||
}
|
||||
|
||||
fn models_manager_with_cache(
|
||||
&self,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
cache: Arc<dyn ModelsCache>,
|
||||
) -> SharedModelsManager {
|
||||
self.models_manager_with_settings(
|
||||
config_model_catalog,
|
||||
ModelCatalogSettings::with_cache(cache),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod test_support {
|
||||
use super::*;
|
||||
|
||||
/// Use an injected runtime with a local transport fixture. Production callers use the
|
||||
/// destination-aware `ProviderAuthContext::model_provider` factory.
|
||||
pub fn runtime_model_provider(
|
||||
info: ModelProviderInfo,
|
||||
credentials: Arc<AuthManager>,
|
||||
runtime: (Arc<RuntimeAuthManager>, RuntimeAuthMode),
|
||||
) -> SharedModelProvider {
|
||||
let mut provider =
|
||||
ConfiguredModelProvider::new(info, Some(credentials), Some(runtime.clone()));
|
||||
provider.runtime_auth = Some(runtime);
|
||||
Arc::new(provider)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "provider_tests.rs"]
|
||||
mod tests;
|
||||
944
codex-rs/model-provider/src/provider_tests.rs
Normal file
944
codex-rs/model-provider/src/provider_tests.rs
Normal file
@@ -0,0 +1,944 @@
|
||||
//! 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::AgentIdentityAuthPolicy;
|
||||
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::account::PlanType;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_redacted_string::RedactedString;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header_regex;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
use super::*;
|
||||
use crate::RemoteCompactionSupport;
|
||||
use crate::auth::AgentIdentitySessionFallback;
|
||||
use crate::shared_state::process_shared_state;
|
||||
|
||||
fn provider_info_with_command_auth() -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
auth: Some(ModelProviderAuthInfo {
|
||||
command: "print-token".to_string(),
|
||||
args: Vec::new(),
|
||||
timeout_ms: NonZeroU64::new(5_000).expect("timeout should be non-zero"),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: std::env::current_dir()
|
||||
.expect("current dir should be available")
|
||||
.try_into()
|
||||
.expect("current dir should be absolute"),
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
}
|
||||
}
|
||||
|
||||
fn test_codex_home() -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("codex-model-provider-test-{}", std::process::id()))
|
||||
}
|
||||
|
||||
fn provider_for(base_url: String) -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
name: "mock".into(),
|
||||
base_url: Some(base_url),
|
||||
model_catalog_url: None,
|
||||
env_key: None,
|
||||
env_key_instructions: None,
|
||||
experimental_bearer_token: None,
|
||||
auth: None,
|
||||
gateway_oauth: None,
|
||||
aws: None,
|
||||
wire_api: WireApi::Responses,
|
||||
query_params: None,
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
request_max_retries: Some(0),
|
||||
stream_max_retries: Some(0),
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
supports_websockets: false,
|
||||
supports_standalone_web_search: false,
|
||||
capabilities: None,
|
||||
project_id: None,
|
||||
location: None,
|
||||
credential_file: None,
|
||||
include_internal_metadata: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_model(slug: &str) -> ModelInfo {
|
||||
serde_json::from_value(json!({
|
||||
"slug": slug,
|
||||
"display_name": slug,
|
||||
"description": null,
|
||||
"default_reasoning_level": "medium",
|
||||
"supported_reasoning_levels": [],
|
||||
"shell_type": "shell_command",
|
||||
"visibility": "list",
|
||||
"supported_in_api": true,
|
||||
"priority": 0,
|
||||
"upgrade": null,
|
||||
"support_verbosity": false,
|
||||
"default_verbosity": null,
|
||||
"apply_patch_tool_type": null,
|
||||
"truncation_policy": {"mode": "bytes", "limit": 10_000},
|
||||
"supports_image_detail_original": false,
|
||||
"context_window": 272_000,
|
||||
"max_context_window": 272_000,
|
||||
"experimental_supported_tools": [],
|
||||
}))
|
||||
.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 scoped_auth_ignores_scope_for_non_openai_provider() {
|
||||
let provider = create_model_provider(
|
||||
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
let auth = provider
|
||||
.api_auth_for_scope(ProviderAuthScope {
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Cli,
|
||||
agent_identity_session_fallback: AgentIdentitySessionFallback::default(),
|
||||
})
|
||||
.await
|
||||
.expect("auth should resolve");
|
||||
|
||||
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(),
|
||||
base_url: Some("https://example.com/openai".to_string()),
|
||||
..ModelProviderInfo::default()
|
||||
},
|
||||
RemoteCompactionSupport::V2,
|
||||
),
|
||||
(
|
||||
ModelProviderInfo {
|
||||
name: "Custom".to_string(),
|
||||
base_url: Some("https://example.openai.azure.com/openai/v1".to_string()),
|
||||
..ModelProviderInfo::default()
|
||||
},
|
||||
RemoteCompactionSupport::V2,
|
||||
),
|
||||
(
|
||||
provider_for("https://example.test/v1".to_string()),
|
||||
RemoteCompactionSupport::Unsupported,
|
||||
),
|
||||
];
|
||||
|
||||
for (provider_info, expected) in cases {
|
||||
let provider = create_model_provider(provider_info, /*auth_manager*/ None);
|
||||
assert_eq!(provider.capabilities().remote_compaction, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_provider_uses_default_approval_review_preferred_model() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.approval_review_preferred_model(),
|
||||
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),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
);
|
||||
|
||||
assert_eq!(provider.approval_review_preferred_model(), "gpt-5.6-luna");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_provider_uses_default_approval_review_model_with_chatgpt_auth() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
)),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.approval_review_preferred_model(),
|
||||
DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL
|
||||
);
|
||||
}
|
||||
|
||||
struct RotatingAuth(AtomicUsize);
|
||||
|
||||
impl codex_login::ExternalAuth for RotatingAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async move {
|
||||
let key = if self.0.fetch_add(1, Ordering::SeqCst).is_multiple_of(2) {
|
||||
"sk-proj-fedramp-synthetic-test-key"
|
||||
} else {
|
||||
"commercial-key"
|
||||
};
|
||||
Ok(CodexAuth::from_api_key(key))
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_context: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_provider_resolves_default_and_explicit_endpoints() {
|
||||
let provider = create_model_provider(
|
||||
provider_for("https://example.test/v1".to_string()),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.expect("runtime base URL should resolve"),
|
||||
Some("https://example.test/v1".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.request_provider_and_auth(/*scope*/ None)
|
||||
.await
|
||||
.unwrap()
|
||||
.0
|
||||
.base_url,
|
||||
"https://example.test/v1"
|
||||
);
|
||||
|
||||
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),
|
||||
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",
|
||||
),
|
||||
("commercial-key", "https://api.openai.com/v1"),
|
||||
] {
|
||||
codex_login::login_with_api_key(
|
||||
home.path(),
|
||||
api_key,
|
||||
codex_login::AuthCredentialsStoreMode::File,
|
||||
codex_login::AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.unwrap();
|
||||
auth.reload().await;
|
||||
let (api_provider, resolved) = provider
|
||||
.request_provider_and_auth(/*scope*/ None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(api_provider.base_url, expected_base_url);
|
||||
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),
|
||||
] {
|
||||
let reads_before = rotating_auth.0.load(Ordering::SeqCst);
|
||||
let (api_provider, resolved) = provider
|
||||
.request_provider_and_auth(/*scope*/ None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rotating_auth.0.load(Ordering::SeqCst), reads_before + 1);
|
||||
let headers = resolved.auth.to_auth_headers().unwrap();
|
||||
let expected_authorization = format!("Bearer {api_key}");
|
||||
assert_eq!(
|
||||
(
|
||||
api_provider.base_url.as_str(),
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
headers
|
||||
.get("X-OpenAI-Fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
),
|
||||
(
|
||||
expected_base_url,
|
||||
Some(expected_authorization.as_str()),
|
||||
expected_fedramp_header,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_model_provider_builds_command_auth_manager_without_base_manager() {
|
||||
let provider = create_model_provider(
|
||||
provider_info_with_command_auth(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
let auth_manager = provider
|
||||
.auth_manager()
|
||||
.expect("command auth provider should have an auth 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),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: None,
|
||||
requires_openai_auth: true,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_returns_api_key_account_state() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"openai-api-key",
|
||||
))),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::ApiKey),
|
||||
requires_openai_auth: true,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_returns_chatgpt_account_state_without_email() {
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
Some(AuthManager::from_auth_for_testing(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
)),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: Some(ProviderAccount::Chatgpt {
|
||||
email: None,
|
||||
plan_type: PlanType::Unknown,
|
||||
}),
|
||||
requires_openai_auth: true,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[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(
|
||||
ModelProviderInfo {
|
||||
name: "Custom".to_string(),
|
||||
base_url: Some("http://localhost:1234/v1".to_string()),
|
||||
wire_api: WireApi::Responses,
|
||||
requires_openai_auth: false,
|
||||
..Default::default()
|
||||
},
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
provider.account_state(),
|
||||
Ok(ProviderAccountState {
|
||||
account: None,
|
||||
requires_openai_auth: false,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[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;
|
||||
let remote_models = vec![remote_model("provider-model")];
|
||||
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.and(header_regex("Authorization", "Bearer provider-token"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "application/json")
|
||||
.set_body_json(ModelsResponse {
|
||||
models: remote_models.clone(),
|
||||
}),
|
||||
)
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let mut provider_info = provider_for(server.uri());
|
||||
provider_info.experimental_bearer_token = Some("provider-token".into());
|
||||
provider_info.model_catalog_url = Some(format!("{}/models", server.uri()).into());
|
||||
provider_info.http_headers = Some(std::collections::HashMap::from([(
|
||||
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
|
||||
"us".into(),
|
||||
)]));
|
||||
for auth in [
|
||||
None,
|
||||
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
] {
|
||||
// Disabled discovery must ignore the catalog cached by the enabled run.
|
||||
for enabled in [true, false] {
|
||||
let provider = create_model_provider(
|
||||
provider_info.clone(),
|
||||
auth.clone().map(AuthManager::from_auth_for_testing),
|
||||
);
|
||||
let manager =
|
||||
provider.models_manager(test_codex_home(), /*config_model_catalog*/ None);
|
||||
manager.set_api_key_model_discovery_enabled(enabled);
|
||||
let refresh_strategy = if enabled {
|
||||
RefreshStrategy::Online
|
||||
} else {
|
||||
RefreshStrategy::Offline
|
||||
};
|
||||
let catalog = manager
|
||||
.raw_model_catalog(
|
||||
refresh_strategy,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.any(|model| model.slug == "provider-model"),
|
||||
enabled
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
56
codex-rs/model-provider/src/request_preparation.rs
Normal file
56
codex-rs/model-provider/src/request_preparation.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
//! Keeps request preparation bound to the credential revision it started with.
|
||||
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
|
||||
use codex_login::AuthChangeState;
|
||||
use codex_login::RequestAuthChange;
|
||||
use codex_protocol::error::Result;
|
||||
|
||||
use crate::ModelProvider;
|
||||
|
||||
/// Prepare a request without dispatching it. When the request uses managed auth,
|
||||
/// repeat preparation after a credential refresh and fail if the owner changes.
|
||||
pub async fn prepare_provider_request<T, Fut>(
|
||||
provider: &dyn ModelProvider,
|
||||
check_auth: bool,
|
||||
mut prepare: impl FnMut(Option<AuthChangeState>) -> Fut,
|
||||
) -> Result<T>
|
||||
where
|
||||
Fut: Future<Output = Result<T>>,
|
||||
{
|
||||
let auth_state = || {
|
||||
provider
|
||||
.auth_manager()
|
||||
.map(|manager| *manager.auth_change_state_receiver().borrow())
|
||||
};
|
||||
let mut before = auth_state();
|
||||
loop {
|
||||
let prepared = prepare(before).await?;
|
||||
if !check_auth {
|
||||
return Ok(prepared);
|
||||
}
|
||||
// A managed provider can begin or cease exposing its auth manager during setup.
|
||||
let after = auth_state();
|
||||
let change = match (before, after) {
|
||||
(Some(before), Some(after)) => {
|
||||
after.compare_for_request(before.owner_generation, before)
|
||||
}
|
||||
(None, None) => RequestAuthChange::Unchanged,
|
||||
_ => RequestAuthChange::OwnerChanged,
|
||||
};
|
||||
match change {
|
||||
RequestAuthChange::Unchanged => return Ok(prepared),
|
||||
RequestAuthChange::CredentialsChanged => before = after,
|
||||
RequestAuthChange::OwnerChanged => {
|
||||
return Err(
|
||||
io::Error::other("account changed while preparing model request").into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "request_preparation_tests.rs"]
|
||||
mod tests;
|
||||
66
codex-rs/model-provider/src/request_preparation_tests.rs
Normal file
66
codex-rs/model-provider/src/request_preparation_tests.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use super::prepare_provider_request;
|
||||
use crate::create_model_provider;
|
||||
use crate::provider_uses_first_party_auth_path;
|
||||
use base64::Engine;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_provider_token_survives_a_workspace_switch_during_setup() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let claims = json!({"https://api.openai.com/auth": {"chatgpt_user_id": "user-a"}});
|
||||
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
|
||||
let token = format!("header.{payload}.signature");
|
||||
let initial = CodexAuth::from_external_chatgpt_tokens(
|
||||
&token,
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
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);
|
||||
info.experimental_bearer_token = Some("provider-token".into());
|
||||
let provider = create_model_provider(info, Some(manager.clone()));
|
||||
|
||||
let mut attempts = 0;
|
||||
let resolved = prepare_provider_request(
|
||||
provider.as_ref(),
|
||||
provider_uses_first_party_auth_path(provider.info()),
|
||||
|_| {
|
||||
attempts += 1;
|
||||
async {
|
||||
let (_, resolved) = provider.request_provider_and_auth(/*scope*/ None).await?;
|
||||
codex_login::auth::login_with_chatgpt_auth_tokens(
|
||||
home.path(),
|
||||
&token,
|
||||
"workspace-b",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
manager.reload().await;
|
||||
Ok(resolved)
|
||||
}
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
manager.auth_cached().unwrap().get_account_id().as_deref(),
|
||||
Some("workspace-b")
|
||||
);
|
||||
assert_eq!(attempts, 1);
|
||||
let mut headers = http::HeaderMap::new();
|
||||
resolved.auth.add_auth_headers(&mut headers).unwrap();
|
||||
assert_eq!(
|
||||
resolved.credential.as_ref().and_then(CodexAuth::api_key),
|
||||
Some("provider-token")
|
||||
);
|
||||
assert_eq!(
|
||||
headers[http::header::AUTHORIZATION],
|
||||
"Bearer provider-token"
|
||||
);
|
||||
}
|
||||
209
codex-rs/model-provider/src/request_setup.rs
Normal file
209
codex-rs/model-provider/src/request_setup.rs
Normal file
@@ -0,0 +1,209 @@
|
||||
//! Resolve credentials, routing, and transport policy as one request context.
|
||||
|
||||
use crate::ModelProvider;
|
||||
use crate::ProviderAuthScope;
|
||||
use crate::ResolvedProviderAuth;
|
||||
use crate::WorkspaceRoutingContext;
|
||||
use crate::auth::bearer_auth_for_provider;
|
||||
use crate::auth::resolve_provider_auth;
|
||||
use crate::auth::resolve_provider_auth_for_scope;
|
||||
use codex_api::AgentIdentityTelemetry;
|
||||
use codex_api::Provider;
|
||||
use codex_api::ReqwestTransport;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::AuthOwner;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use codex_login::default_client::create_client_for_route;
|
||||
use codex_model_provider_info::GatewayOAuthConfig;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_runtime_agent_instance::RuntimeAuth;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Select auth for inference and discovery, letting rotating credentials finish saving
|
||||
/// if the requesting operation is cancelled.
|
||||
pub(crate) async fn resolve_request_auth(
|
||||
info: ModelProviderInfo,
|
||||
manager: Option<Arc<AuthManager>>,
|
||||
runtime: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
scope: Option<ProviderAuthScope>,
|
||||
destination: Option<String>,
|
||||
) -> codex_protocol::error::Result<ResolvedProviderAuth> {
|
||||
tokio::spawn(async move {
|
||||
crate::auth::observe_auth_selection(
|
||||
runtime.as_ref().map(|(_, mode)| *mode),
|
||||
"model",
|
||||
async move {
|
||||
if let Some((runtime, mode)) = runtime {
|
||||
crate::validate_runtime_destination(destination.as_deref())?;
|
||||
crate::validate_runtime_environment(&runtime, destination.as_deref())?;
|
||||
let runtime =
|
||||
crate::select_runtime_provider(&info, manager.as_ref(), &runtime)?;
|
||||
let headers = info.build_header_map()?;
|
||||
let selected =
|
||||
crate::runtime_auth::select_runtime_auth(&runtime, &headers).await?;
|
||||
let resolved = ResolvedProviderAuth::for_runtime(selected, mode);
|
||||
resolved.validate_headers(&headers)?;
|
||||
tracing::debug!(runtime_auth_mode = ?mode, "selected runtime authentication");
|
||||
return Ok(resolved);
|
||||
}
|
||||
|
||||
if let Some(bearer) = bearer_auth_for_provider(&info)? {
|
||||
let credential = bearer.token.as_deref().map(CodexAuth::from_api_key);
|
||||
let mut resolved = ResolvedProviderAuth::new(Arc::new(bearer));
|
||||
resolved.credential = credential;
|
||||
return Ok(resolved);
|
||||
}
|
||||
|
||||
let credential = match &manager {
|
||||
Some(manager) => manager.auth().await,
|
||||
None => None,
|
||||
};
|
||||
let mut resolved = match scope {
|
||||
Some(scope) if crate::provider_uses_first_party_auth_path(&info) => {
|
||||
resolve_provider_auth_for_scope(manager, credential.as_ref(), &info, scope)
|
||||
.await?
|
||||
}
|
||||
_ => ResolvedProviderAuth::new(resolve_provider_auth(
|
||||
credential.as_ref(),
|
||||
&info,
|
||||
)?),
|
||||
};
|
||||
resolved.credential = credential;
|
||||
Ok(resolved)
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let credentials = provider.auth_manager();
|
||||
match provider.runtime_auth() {
|
||||
Some((runtime, _)) => {
|
||||
crate::select_runtime_provider(provider.info(), credentials.as_ref(), runtime)
|
||||
.ok()
|
||||
.map(|binding| binding.auth_owner())
|
||||
}
|
||||
None => credentials.map(|manager| manager.auth_owner()),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ResolvedProviderRequest {
|
||||
pub auth: Option<CodexAuth>,
|
||||
pub auth_owner: Option<AuthOwner>,
|
||||
pub auth_revision: Option<u64>,
|
||||
pub api_provider: Provider,
|
||||
pub redirect_policy: ClientRedirectPolicy,
|
||||
pub api_auth: SharedAuthProvider,
|
||||
pub agent_identity_telemetry: Option<AgentIdentityTelemetry>,
|
||||
pub runtime_id: Option<String>,
|
||||
pub http_client_factory: HttpClientFactory,
|
||||
}
|
||||
|
||||
impl ResolvedProviderRequest {
|
||||
pub fn http_transport(&self, endpoint: &str) -> Result<ReqwestTransport> {
|
||||
let redirect_policy = if self
|
||||
.api_provider
|
||||
.headers
|
||||
.contains_key(crate::ACCOUNT_ROUTING_HEADER)
|
||||
{
|
||||
ClientRedirectPolicy::Reject
|
||||
} else {
|
||||
self.redirect_policy
|
||||
};
|
||||
let request_url = self.api_provider.url_for_path(endpoint);
|
||||
let client = create_client_for_route(
|
||||
&self.http_client_factory,
|
||||
&request_url,
|
||||
ClientRouteClass::Api,
|
||||
redirect_policy,
|
||||
)
|
||||
.map_err(std::io::Error::from)?;
|
||||
Ok(ReqwestTransport::from_http_client(client))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve one attempt, including any workspace route, without mixing credential revisions.
|
||||
/// The supplied factory retains the caller's proxy/TLS settings; runtime requests bind its
|
||||
/// application policy to the same selected account used to sign the request.
|
||||
pub async fn resolve_request(
|
||||
provider: &dyn ModelProvider,
|
||||
scope: Option<ProviderAuthScope>,
|
||||
routing: Option<&WorkspaceRoutingContext>,
|
||||
http_client_factory: HttpClientFactory,
|
||||
) -> Result<ResolvedProviderRequest> {
|
||||
let check_auth = provider.runtime_auth().is_none()
|
||||
&& crate::provider_uses_first_party_auth_path(provider.info());
|
||||
crate::prepare_provider_request(provider, check_auth, |state| {
|
||||
let scope = scope.clone();
|
||||
let http_client_factory = http_client_factory.clone();
|
||||
let owner = state
|
||||
.and_then(|_| provider.auth_manager())
|
||||
.map(|manager| manager.auth_owner());
|
||||
async move {
|
||||
let (api_provider, resolved_auth) = provider.request_provider_and_auth(scope).await?;
|
||||
let auth = match &resolved_auth.credential {
|
||||
Some(auth) => Some(auth.clone()),
|
||||
None => provider.auth().await,
|
||||
};
|
||||
let (api_provider, redirect_policy) = match routing {
|
||||
Some(routing) => {
|
||||
let resolved = provider
|
||||
.route_responses_api_provider(api_provider, auth.as_ref(), routing)
|
||||
.await?;
|
||||
(resolved.provider, resolved.redirect_policy)
|
||||
}
|
||||
None => (api_provider, ClientRedirectPolicy::Default),
|
||||
};
|
||||
resolved_auth.validate_headers(&api_provider.headers)?;
|
||||
let runtime_state = resolved_auth
|
||||
.runtime
|
||||
.as_ref()
|
||||
.map(RuntimeAuth::change_state);
|
||||
let http_client_factory = resolved_auth
|
||||
.bind_http_client_factory(http_client_factory)
|
||||
.map_err(|error| provider.map_api_error(error.into()))?;
|
||||
let runtime_id = resolved_auth
|
||||
.runtime
|
||||
.as_ref()
|
||||
.map(|selected| selected.runtime().id().to_owned());
|
||||
Ok(ResolvedProviderRequest {
|
||||
auth,
|
||||
auth_owner: resolved_auth
|
||||
.runtime
|
||||
.as_ref()
|
||||
.map(|selected| selected.auth_owner().clone())
|
||||
.or(owner),
|
||||
auth_revision: runtime_state
|
||||
.map(|state| state.generation)
|
||||
.or(state.map(|state| state.generation)),
|
||||
api_provider,
|
||||
redirect_policy: if provider
|
||||
.info()
|
||||
.gateway_oauth
|
||||
.as_ref()
|
||||
.is_some_and(GatewayOAuthConfig::uses_credential_export)
|
||||
{
|
||||
ClientRedirectPolicy::Reject
|
||||
} else {
|
||||
redirect_policy
|
||||
},
|
||||
api_auth: resolved_auth.auth,
|
||||
agent_identity_telemetry: resolved_auth.agent_identity_telemetry,
|
||||
runtime_id,
|
||||
http_client_factory,
|
||||
})
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
221
codex-rs/model-provider/src/runtime_auth.rs
Normal file
221
codex-rs/model-provider/src/runtime_auth.rs
Normal file
@@ -0,0 +1,221 @@
|
||||
//! Keep model requests and catalog refreshes bound to the same registered actor.
|
||||
|
||||
use codex_api::AuthError;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
|
||||
use codex_http_client::OPENAI_ORGANIZATION_HEADER;
|
||||
use codex_http_client::OPENAI_PROJECT_HEADER;
|
||||
use codex_http_client::OpenAiDestination;
|
||||
use codex_http_client::classify_openai_api_url;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_runtime_agent_instance::ActorInfo;
|
||||
use codex_runtime_agent_instance::PlatformResourceSelection;
|
||||
use codex_runtime_agent_instance::RuntimeAuth;
|
||||
use codex_runtime_agent_instance::RuntimeAuthBinding;
|
||||
use codex_runtime_agent_instance::RuntimeAuthError;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use http::HeaderMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Select the runtime for the resource scope carried by the model request.
|
||||
pub(crate) async fn select_runtime_auth(
|
||||
manager: &Arc<RuntimeAuthBinding>,
|
||||
headers: &HeaderMap,
|
||||
) -> CodexResult<RuntimeAuth> {
|
||||
let selection = resource_selection(headers).map_err(map_runtime_auth_error)?;
|
||||
manager
|
||||
.auth_with_selection(&selection)
|
||||
.await
|
||||
.map_err(map_runtime_auth_error)
|
||||
}
|
||||
|
||||
/// Select the request's resource scope while preserving captured credential ownership.
|
||||
pub async fn select_runtime_auth_for(
|
||||
binding: &Arc<RuntimeAuthBinding>,
|
||||
auth: &CodexAuth,
|
||||
headers: &HeaderMap,
|
||||
) -> CodexResult<RuntimeAuth> {
|
||||
let selection = resource_selection(headers).map_err(map_runtime_auth_error)?;
|
||||
binding
|
||||
.auth_for(auth, &selection)
|
||||
.await
|
||||
.map_err(map_runtime_auth_error)
|
||||
}
|
||||
|
||||
fn map_runtime_auth_error(error: RuntimeAuthError) -> CodexErr {
|
||||
match error {
|
||||
RuntimeAuthError::RefreshTokenFailed(error) => CodexErr::RefreshTokenFailed(error),
|
||||
error => codex_api::map_api_error(AuthError::from(error).into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Select fresh request auth without allowing a reusable client's source to change.
|
||||
pub(crate) async fn select_runtime_auth_for_source(
|
||||
manager: &Arc<RuntimeAuthBinding>,
|
||||
source_generation: u64,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<RuntimeAuth, AuthError> {
|
||||
let manager = Arc::clone(manager);
|
||||
let selection = resource_selection(headers)?;
|
||||
finish_runtime_selection(
|
||||
async move { manager.auth_for_source(source_generation, &selection).await },
|
||||
)
|
||||
.await
|
||||
.map_err(AuthError::from)
|
||||
}
|
||||
|
||||
// Once token rotation begins, let it finish persisting even if the request is cancelled.
|
||||
pub(crate) async fn finish_runtime_selection(
|
||||
selection: impl Future<Output = Result<RuntimeAuth, RuntimeAuthError>> + Send + 'static,
|
||||
) -> Result<RuntimeAuth, RuntimeAuthError> {
|
||||
tokio::spawn(selection).await?
|
||||
}
|
||||
|
||||
pub(crate) fn resource_selection(
|
||||
headers: &HeaderMap,
|
||||
) -> Result<PlatformResourceSelection, RuntimeAuthError> {
|
||||
let selector = |name| {
|
||||
headers
|
||||
.get(name)
|
||||
.map(|value| {
|
||||
value
|
||||
.to_str()
|
||||
.map(str::to_owned)
|
||||
.map_err(|_| RuntimeAuthError::InvalidResourceSelection(name))
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
Ok(PlatformResourceSelection {
|
||||
organization_id: selector(OPENAI_ORGANIZATION_HEADER)?,
|
||||
project_id: selector(OPENAI_PROJECT_HEADER)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Use the credential selected by provider configuration, never an ambient actor's proof.
|
||||
pub fn select_runtime_provider(
|
||||
info: &ModelProviderInfo,
|
||||
credentials: Option<&Arc<AuthManager>>,
|
||||
runtime: &Arc<RuntimeAuthManager>,
|
||||
) -> CodexResult<Arc<RuntimeAuthBinding>> {
|
||||
let unsupported = || {
|
||||
CodexErr::UnsupportedOperation(
|
||||
"runtime auth requires the model provider's selected OpenAI credential".to_string(),
|
||||
)
|
||||
};
|
||||
if info.aws.is_some() {
|
||||
return Err(unsupported());
|
||||
}
|
||||
let credentials = credentials.ok_or_else(unsupported)?;
|
||||
if let Some(bearer) = crate::auth::bearer_auth_for_provider(info)? {
|
||||
let token = bearer.token.ok_or_else(unsupported)?;
|
||||
return Ok(runtime.bind_api_key(&token, &credentials.runtime_config()));
|
||||
}
|
||||
if !info.requires_openai_auth && info.auth.is_none() {
|
||||
return Err(unsupported());
|
||||
}
|
||||
Ok(runtime.bind(Arc::clone(credentials)))
|
||||
}
|
||||
|
||||
/// An unrecognized OpenAI origin must not silently fall back to legacy auth.
|
||||
pub fn validate_runtime_destination(destination: Option<&str>) -> CodexResult<()> {
|
||||
if destination.is_some_and(|url| classify_openai_api_url(url) == OpenAiDestination::Unsupported)
|
||||
{
|
||||
return Err(CodexErr::UnsupportedOperation(
|
||||
"runtime auth does not support this OpenAI endpoint".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Do not send a provider's credentials to registration in another OpenAI environment.
|
||||
pub fn validate_runtime_environment(
|
||||
runtime: &RuntimeAuthManager,
|
||||
destination: Option<&str>,
|
||||
) -> CodexResult<()> {
|
||||
let registration_url = runtime
|
||||
.registration_url()
|
||||
.map_err(|err| CodexErr::InvalidRequest(err.to_string()))?;
|
||||
let registration_is_staging = match registration_url
|
||||
.host_str()
|
||||
.map(|host| host.trim_end_matches('.'))
|
||||
{
|
||||
Some("auth.openai.com") => false,
|
||||
Some("auth.api.openai.org") => true,
|
||||
// Explicit registration targets also support local test servers.
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let destination_is_staging = match destination {
|
||||
Some(destination) => {
|
||||
let destination = url::Url::parse(destination)
|
||||
.map_err(|_| CodexErr::InvalidRequest("invalid runtime auth destination".into()))?;
|
||||
let host = destination
|
||||
.host_str()
|
||||
.unwrap_or_default()
|
||||
.trim_end_matches('.');
|
||||
matches!(
|
||||
host,
|
||||
"api.openai.org" | "api.openai-staging.com" | "chatgpt-staging.com"
|
||||
) || host.ends_with(".chatgpt-staging.com")
|
||||
}
|
||||
// Both implicit model-provider defaults use production.
|
||||
None => false,
|
||||
};
|
||||
if registration_is_staging != destination_is_staging {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"Requests must use the same production or staging environment as runtime registration"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Select runtime auth for supported OpenAI URLs; reject unsupported OpenAI URLs.
|
||||
pub fn runtime_auth_for_url<'a>(
|
||||
runtime: Option<&'a (Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
url: &str,
|
||||
) -> CodexResult<Option<&'a (Arc<RuntimeAuthManager>, RuntimeAuthMode)>> {
|
||||
if runtime.is_some() {
|
||||
validate_runtime_destination(Some(url))?;
|
||||
}
|
||||
let runtime = runtime.filter(|_| classify_openai_api_url(url) == OpenAiDestination::Supported);
|
||||
if let Some((manager, _)) = runtime {
|
||||
validate_runtime_environment(manager, Some(url))?;
|
||||
}
|
||||
Ok(runtime)
|
||||
}
|
||||
|
||||
/// Account and organization selectors must agree with the registered actor.
|
||||
/// API project access is authorized by the backend for each request.
|
||||
pub fn validate_runtime_selectors(headers: &HeaderMap, actor: &ActorInfo) -> CodexResult<()> {
|
||||
let validate = |name: &str, expected: Option<&str>| {
|
||||
if let Some(value) = headers.get(name)
|
||||
&& value.to_str().ok() != expected
|
||||
{
|
||||
return Err(CodexErr::UnsupportedOperation(format!(
|
||||
"configured {name} does not match the registered runtime"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
match actor {
|
||||
ActorInfo::Chatgpt { account_id, .. } => {
|
||||
validate(CHATGPT_ACCOUNT_ID_HEADER, Some(account_id))?;
|
||||
validate(OPENAI_ORGANIZATION_HEADER, None)?;
|
||||
validate(OPENAI_PROJECT_HEADER, None)
|
||||
}
|
||||
ActorInfo::Platform {
|
||||
organization_id, ..
|
||||
} => {
|
||||
validate(CHATGPT_ACCOUNT_ID_HEADER, None)?;
|
||||
validate(OPENAI_ORGANIZATION_HEADER, Some(organization_id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "runtime_auth_tests.rs"]
|
||||
mod tests;
|
||||
386
codex-rs/model-provider/src/runtime_auth_tests.rs
Normal file
386
codex-rs/model-provider/src/runtime_auth_tests.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
use super::*;
|
||||
use crate::ProviderAuthContext;
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::auth::BedrockApiKeyAuth;
|
||||
use codex_login::auth::RefreshTokenFailedReason;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::num::NonZeroU64;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
async fn context(
|
||||
server: &MockServer,
|
||||
credentials: Arc<AuthManager>,
|
||||
mode: RuntimeAuthMode,
|
||||
) -> ProviderAuthContext {
|
||||
Mock::given(method("POST"))
|
||||
.respond_with(|request: &wiremock::Request| ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": request.headers["idempotency-key"].to_str().unwrap(),
|
||||
"agent_host_id": "host-a",
|
||||
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null},
|
||||
})))
|
||||
.mount(server).await;
|
||||
let runtime = RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/agent/register", server.uri()).parse().unwrap(),
|
||||
);
|
||||
ProviderAuthContext {
|
||||
credentials,
|
||||
runtime_auth: Some((Arc::new(runtime), mode)),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_keys_and_commands_use_their_own_shared_runtime() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let credentials = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("ambient-key"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let context = context(&server, credentials, mode).await;
|
||||
let literal = ModelProviderInfo {
|
||||
experimental_bearer_token: Some("literal-key".into()),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
};
|
||||
#[cfg(unix)]
|
||||
let (command, args) = ("sh", vec!["-c".into(), "printf command-key".into()]);
|
||||
#[cfg(windows)]
|
||||
let (command, args) = (
|
||||
"cmd.exe",
|
||||
vec![
|
||||
"/D".into(),
|
||||
"/Q".into(),
|
||||
"/C".into(),
|
||||
"echo command-key".into(),
|
||||
],
|
||||
);
|
||||
let commanded = ModelProviderInfo {
|
||||
auth: Some(ModelProviderAuthInfo {
|
||||
command: command.into(),
|
||||
args,
|
||||
timeout_ms: NonZeroU64::new(5000).unwrap(),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: home.path().to_path_buf().try_into().unwrap(),
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
};
|
||||
for (info, key) in [(literal.clone(), "literal-key"), (commanded, "command-key")] {
|
||||
let mut runtime_id = None;
|
||||
for _ in 0..2 {
|
||||
let provider = context.model_provider(info.clone());
|
||||
let selected = provider.request_auth(/*scope*/ None).await.unwrap();
|
||||
let runtime = selected.runtime.as_ref().unwrap();
|
||||
assert_eq!(runtime.auth().api_key(), Some(key));
|
||||
match &runtime_id {
|
||||
Some(id) => assert_eq!(runtime.runtime().id(), id),
|
||||
None => runtime_id = Some(runtime.runtime().id().to_string()),
|
||||
}
|
||||
let headers = selected
|
||||
.auth
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(headers["authorization"], format!("Bearer {key}"));
|
||||
assert!(headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(
|
||||
headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("AgentAssertion ")
|
||||
);
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for (request, key) in requests.iter().zip(["literal-key", "command-key"]) {
|
||||
assert_eq!(
|
||||
request.body_json::<serde_json::Value>().unwrap()["actor_auth"]["credential"],
|
||||
key
|
||||
);
|
||||
}
|
||||
let custom = context.model_provider(ModelProviderInfo {
|
||||
base_url: Some("https://provider.example/v1".into()),
|
||||
..literal
|
||||
});
|
||||
let auth = custom.request_auth(/*scope*/ None).await.unwrap();
|
||||
assert!(auth.runtime.is_none());
|
||||
let headers = auth
|
||||
.auth
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(headers["authorization"], "Bearer literal-key");
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_provider_key_keeps_the_requested_project_scope() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("ambient-key"));
|
||||
let context = context(&server, credentials, mode).await;
|
||||
server.reset().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(wiremock::matchers::body_partial_json(json!({
|
||||
"actor_auth": {
|
||||
"type": "platform_api_key",
|
||||
"credential": "selected-key",
|
||||
"project_id": "proj-selected",
|
||||
},
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "rai-selected",
|
||||
"agent_host_id": "host-a",
|
||||
"actor": {
|
||||
"kind": "platform",
|
||||
"user_id": "user-a",
|
||||
"organization_id": "org-a",
|
||||
"project_id": "proj-selected",
|
||||
},
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let provider = context.model_provider(ModelProviderInfo {
|
||||
experimental_bearer_token: Some("selected-key".into()),
|
||||
http_headers: Some(std::collections::HashMap::from([(
|
||||
OPENAI_PROJECT_HEADER.into(),
|
||||
"proj-selected".into(),
|
||||
)])),
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
});
|
||||
let selected = provider.request_auth(/*scope*/ None).await.unwrap();
|
||||
let runtime = selected.runtime.as_ref().unwrap();
|
||||
assert_eq!(runtime.auth().api_key(), Some("selected-key"));
|
||||
assert!(matches!(
|
||||
runtime.runtime().actor().info(),
|
||||
ActorInfo::Platform { project_id: Some(project), .. } if project == "proj-selected"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bedrock_auth_stays_independent_when_openai_runtime_auth_is_enabled() {
|
||||
let server = MockServer::start().await;
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "bedrock-key".into(),
|
||||
region: "us-east-1".into(),
|
||||
}));
|
||||
let context = context(&server, credentials, RuntimeAuthMode::DualHeader).await;
|
||||
let bedrock = context.model_provider(ModelProviderInfo::create_amazon_bedrock_provider(
|
||||
/*aws*/ None,
|
||||
));
|
||||
let headers = bedrock
|
||||
.api_auth()
|
||||
.await
|
||||
.unwrap()
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(headers["authorization"], "Bearer bedrock-key");
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
|
||||
let openai = context.model_provider(ModelProviderInfo {
|
||||
experimental_bearer_token: Some("openai-key".into()),
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
});
|
||||
let headers = openai
|
||||
.api_auth()
|
||||
.await
|
||||
.unwrap()
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(headers["authorization"], "Bearer openai-key");
|
||||
assert!(headers.contains_key("x-openai-agent-assertion"));
|
||||
let headers = bedrock
|
||||
.api_auth()
|
||||
.await
|
||||
.unwrap()
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(headers["authorization"], "Bearer bedrock-key");
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(
|
||||
requests[0].body_json::<serde_json::Value>().unwrap()["actor_auth"]["credential"],
|
||||
"openai-key"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_denial_recovery_is_scoped_to_openai() {
|
||||
let server = MockServer::start().await;
|
||||
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("actor-key"));
|
||||
let context = context(&server, credentials, RuntimeAuthMode::AssertionOnly).await;
|
||||
for (url, has_runtime) in [
|
||||
("https://api.openai.com/v1", true),
|
||||
("https://provider.example/v1", false),
|
||||
] {
|
||||
let provider = context.model_provider(ModelProviderInfo::create_openai_provider(Some(
|
||||
url.to_string(),
|
||||
)));
|
||||
for code in ["invalid_agent_instance_assertion", "token_expired"] {
|
||||
let error = codex_api::TransportError::Http {
|
||||
status: http::StatusCode::UNAUTHORIZED,
|
||||
retry_after: None,
|
||||
url: Some(format!("{url}/responses")),
|
||||
headers: None,
|
||||
body: Some(json!({"error": {"code": code}}).to_string()),
|
||||
};
|
||||
assert_eq!(
|
||||
provider.is_recoverable_auth_error(&error),
|
||||
!has_runtime || code == "token_expired"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn permanent_runtime_refresh_failure_preserves_sign_in_error() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
// Exercise proactive refresh and registration's existing 401 recovery.
|
||||
for last_refresh in ["2000-01-01T00:00:00Z", "2099-01-01T00:00:00Z"] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
|
||||
"error": {"code": "refresh_token_invalidated"},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(401))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempfile::tempdir().expect("create auth home");
|
||||
let claims = json!({
|
||||
"https://api.openai.com/auth": {
|
||||
"chatgpt_user_id": "user-a",
|
||||
"chatgpt_account_id": "workspace-a",
|
||||
},
|
||||
});
|
||||
let token = format!(
|
||||
"e30.{}.signature",
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())
|
||||
);
|
||||
let stored = serde_json::from_value(json!({
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {
|
||||
"id_token": token, "access_token": "initial-token",
|
||||
"refresh_token": "revoked-refresh-token", "account_id": "workspace-a",
|
||||
"oauth_provenance": {
|
||||
"issuer": server.uri(), "client_id": "runtime-refresh-test",
|
||||
},
|
||||
},
|
||||
"last_refresh": last_refresh,
|
||||
}))
|
||||
.expect("construct stored OAuth credentials");
|
||||
codex_login::save_auth(
|
||||
home.path(),
|
||||
&stored,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
)
|
||||
.expect("save OAuth credentials");
|
||||
let credentials = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let original = credentials.auth_cached().expect("load OAuth credentials");
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: "00000000-0000-0000-0000-000000000000"
|
||||
.parse()
|
||||
.expect("parse installation ID"),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/register", server.uri())
|
||||
.parse()
|
||||
.expect("parse registration URL"),
|
||||
));
|
||||
let provider = ProviderAuthContext {
|
||||
credentials: Arc::clone(&credentials),
|
||||
runtime_auth: Some((Arc::clone(&runtime), mode)),
|
||||
}
|
||||
.model_provider(ModelProviderInfo::create_openai_provider(
|
||||
/*base_url*/ None,
|
||||
));
|
||||
|
||||
// A later request must preserve the cached rejection, not retry it as a stream error.
|
||||
for _ in 0..2 {
|
||||
let error = provider
|
||||
.request_auth(/*scope*/ None)
|
||||
.await
|
||||
.err()
|
||||
.expect("revoked refresh must reject request preparation");
|
||||
let failure = credentials
|
||||
.refresh_failure_for_auth(&original)
|
||||
.expect("permanent refresh rejection is cached");
|
||||
assert_eq!(failure.reason, RefreshTokenFailedReason::Revoked);
|
||||
let CodexErrorDetails::RefreshTokenFailed(actual) = error.details() else {
|
||||
panic!("expected sign-in error for {mode:?}/{last_refresh}, got {error:?}");
|
||||
};
|
||||
assert_eq!(actual, &failure);
|
||||
assert_eq!(error.retry_delay(/*retry_count*/ 1), None);
|
||||
}
|
||||
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
197
codex-rs/model-provider/src/shared_state.rs
Normal file
197
codex-rs/model-provider/src/shared_state.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::Weak;
|
||||
|
||||
use crate::gateway_export::GatewayExport;
|
||||
use codex_keyring_store::DefaultKeyringStore;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::AuthRuntimeConfig;
|
||||
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<(
|
||||
GatewayAuthConfig,
|
||||
AuthRuntimeConfig,
|
||||
Weak<OAuthSessionManager>,
|
||||
)>,
|
||||
>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GatewayExportEntry {
|
||||
owner: Weak<AuthManager>,
|
||||
provider: ModelProviderInfo,
|
||||
export: Weak<GatewayExport>,
|
||||
}
|
||||
|
||||
pub(crate) fn process_shared_state() -> &'static ModelProviderSharedState {
|
||||
static STATE: OnceLock<ModelProviderSharedState> = OnceLock::new();
|
||||
STATE.get_or_init(ModelProviderSharedState::default)
|
||||
}
|
||||
|
||||
impl ModelProviderSharedState {
|
||||
pub(crate) fn command_credentials(
|
||||
&self,
|
||||
config: &ModelProviderAuthInfo,
|
||||
runtime: &AuthRuntimeConfig,
|
||||
) -> Arc<AuthManager> {
|
||||
let mut owners = self
|
||||
.command_credentials
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
owners.retain(|(_, _, owner)| owner.strong_count() != 0);
|
||||
if let Some(owner) = owners
|
||||
.iter()
|
||||
.find(|(source, context, _)| source == config && context == runtime)
|
||||
.and_then(|(_, _, owner)| owner.upgrade())
|
||||
{
|
||||
return owner;
|
||||
}
|
||||
let owner = AuthManager::external_bearer_with_runtime(config.clone(), runtime.clone());
|
||||
owners.push((config.clone(), runtime.clone(), Arc::downgrade(&owner)));
|
||||
owner
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_oauth_session(
|
||||
&self,
|
||||
config: &GatewayOAuthSettings,
|
||||
runtime: &AuthRuntimeConfig,
|
||||
) -> std::io::Result<Arc<OAuthSessionManager>> {
|
||||
let oauth = GatewayAuthConfig {
|
||||
authorization_url: config.authorization_url.clone(),
|
||||
device_authorization_url: config.device_authorization_url.clone(),
|
||||
token_url: config.token_url.clone(),
|
||||
client_id: config.client_id.clone(),
|
||||
resource: config.resource.clone(),
|
||||
scopes: config.scopes.clone(),
|
||||
redirect_port: config.redirect_port,
|
||||
credentials_store: config.credentials_store,
|
||||
};
|
||||
let mut managers = self
|
||||
.oauth_sessions
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
managers.retain(|(_, _, manager)| manager.strong_count() != 0);
|
||||
if let Some(manager) = managers
|
||||
.iter()
|
||||
.find(|(cached_config, cached_runtime, _)| {
|
||||
cached_config == &oauth && cached_runtime == runtime
|
||||
})
|
||||
.and_then(|(_, _, manager)| manager.upgrade())
|
||||
{
|
||||
return Ok(manager);
|
||||
}
|
||||
let manager = Arc::new(OAuthSessionManager::new(
|
||||
oauth.clone(),
|
||||
runtime.codex_home.clone(),
|
||||
runtime.auth_route_config.http_client_factory(),
|
||||
Arc::new(DefaultKeyringStore),
|
||||
)?);
|
||||
managers.push((oauth, runtime.clone(), Arc::downgrade(&manager)));
|
||||
Ok(manager)
|
||||
}
|
||||
|
||||
// The catalog preflight and endpoint construct separate providers for the same owner.
|
||||
pub(crate) fn gateway_export(
|
||||
&self,
|
||||
provider: &ModelProviderInfo,
|
||||
command: &CredentialExportConfig,
|
||||
owner: &Arc<AuthManager>,
|
||||
) -> Arc<GatewayExport> {
|
||||
let owner_key = Arc::downgrade(owner);
|
||||
let mut entries = self
|
||||
.gateway_exports
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
entries.retain(|entry| entry.export.strong_count() != 0 && entry.owner.strong_count() != 0);
|
||||
if let Some(export) = entries
|
||||
.iter()
|
||||
.find(|entry| entry.owner.ptr_eq(&owner_key) && &entry.provider == provider)
|
||||
.and_then(|entry| entry.export.upgrade())
|
||||
{
|
||||
return export;
|
||||
}
|
||||
let export = Arc::new(GatewayExport::new(
|
||||
command.clone(),
|
||||
owner.application_network_policy(),
|
||||
));
|
||||
entries.push(GatewayExportEntry {
|
||||
owner: owner_key,
|
||||
provider: provider.clone(),
|
||||
export: Arc::downgrade(&export),
|
||||
});
|
||||
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"]
|
||||
pub(crate) mod test_support;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "shared_state_tests.rs"]
|
||||
mod tests;
|
||||
139
codex-rs/model-provider/src/shared_state_test_support.rs
Normal file
139
codex-rs/model-provider/src/shared_state_test_support.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
//! Seeds gateway credentials in the configured store for provider and agent integration tests.
|
||||
|
||||
#![allow(clippy::expect_used)] // Fixture setup failures should fail the calling test immediately.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use codex_keyring_store::CredentialStoreError;
|
||||
use codex_keyring_store::KeyringStore;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::GatewayAuthConfig;
|
||||
use codex_login::OAuthSessionManager;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::OAuthCredentialsStore;
|
||||
use codex_secrets::LocalSecretsNamespace;
|
||||
use codex_secrets::SecretName;
|
||||
use codex_secrets::SecretScope;
|
||||
use codex_secrets::SecretsBackendKind;
|
||||
use codex_secrets::SecretsManager;
|
||||
|
||||
use super::process_shared_state;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestKeyring(Mutex<Option<String>>);
|
||||
|
||||
impl KeyringStore for TestKeyring {
|
||||
fn load(
|
||||
&self,
|
||||
_service: &str,
|
||||
_account: &str,
|
||||
) -> std::result::Result<Option<String>, CredentialStoreError> {
|
||||
Ok(self
|
||||
.0
|
||||
.lock()
|
||||
.expect("gateway test token store lock")
|
||||
.clone())
|
||||
}
|
||||
fn save(
|
||||
&self,
|
||||
_service: &str,
|
||||
_account: &str,
|
||||
value: &str,
|
||||
) -> std::result::Result<(), CredentialStoreError> {
|
||||
*self.0.lock().expect("gateway test token store lock") = Some(value.to_string());
|
||||
Ok(())
|
||||
}
|
||||
fn delete(
|
||||
&self,
|
||||
_service: &str,
|
||||
_account: &str,
|
||||
) -> std::result::Result<bool, CredentialStoreError> {
|
||||
Ok(self
|
||||
.0
|
||||
.lock()
|
||||
.expect("gateway test token store lock")
|
||||
.take()
|
||||
.is_some())
|
||||
}
|
||||
}
|
||||
|
||||
/// Seeds a provider's configured gateway store, using a test passphrase for the keyring backend.
|
||||
/// Keep the returned manager alive while requests use this fixture.
|
||||
pub fn seed_gateway_auth(
|
||||
info: &ModelProviderInfo,
|
||||
primary: &AuthManager,
|
||||
token: serde_json::Value,
|
||||
) -> Arc<OAuthSessionManager> {
|
||||
let Some(codex_model_provider_info::GatewayOAuthConfig::OAuth(config)) =
|
||||
info.gateway_oauth.clone()
|
||||
else {
|
||||
panic!("expected gateway OAuth test configuration")
|
||||
};
|
||||
let runtime = primary.runtime_config();
|
||||
let oauth = GatewayAuthConfig {
|
||||
authorization_url: config.authorization_url,
|
||||
device_authorization_url: config.device_authorization_url,
|
||||
token_url: config.token_url,
|
||||
client_id: config.client_id,
|
||||
resource: config.resource,
|
||||
scopes: config.scopes,
|
||||
redirect_port: config.redirect_port,
|
||||
credentials_store: config.credentials_store,
|
||||
};
|
||||
// Repeated fixtures sharing a Codex home must use the same encryption key.
|
||||
let keyring = Arc::new(TestKeyring(Mutex::new(Some(
|
||||
"gateway-test-passphrase".to_string(),
|
||||
))));
|
||||
let manager = Arc::new(
|
||||
OAuthSessionManager::new(
|
||||
oauth.clone(),
|
||||
runtime.codex_home.clone(),
|
||||
runtime.auth_route_config.http_client_factory(),
|
||||
keyring.clone(),
|
||||
)
|
||||
.expect("gateway test HTTP client"),
|
||||
);
|
||||
let credential_id = manager.credential_id();
|
||||
match oauth.credentials_store {
|
||||
OAuthCredentialsStore::Keyring => {
|
||||
let secrets = SecretsManager::new_with_keyring_store_and_namespace(
|
||||
runtime.codex_home.clone(),
|
||||
SecretsBackendKind::Local,
|
||||
keyring,
|
||||
LocalSecretsNamespace::GatewayOAuth,
|
||||
);
|
||||
let digest = credential_id
|
||||
.strip_prefix("provider-oauth|")
|
||||
.expect("gateway credential ID");
|
||||
let name = SecretName::new(&format!("PROVIDER_OAUTH_{}", digest.to_ascii_uppercase()))
|
||||
.expect("gateway test credential name");
|
||||
secrets
|
||||
.set(&SecretScope::Global, &name, &token.to_string())
|
||||
.expect("seed encrypted gateway credentials");
|
||||
}
|
||||
OAuthCredentialsStore::File => {
|
||||
let dir = runtime.codex_home.join("secrets");
|
||||
std::fs::create_dir_all(&dir).expect("create test credentials directory");
|
||||
let file = dir.join("gateway_oauth.json");
|
||||
let mut tokens: std::collections::BTreeMap<String, serde_json::Value> =
|
||||
match std::fs::read(&file) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).expect("parse test gateway tokens"),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Default::default(),
|
||||
Err(err) => panic!("read test gateway file: {err}"),
|
||||
};
|
||||
tokens.insert(credential_id, token);
|
||||
std::fs::write(
|
||||
file,
|
||||
serde_json::to_vec(&tokens).expect("serialize test gateway tokens"),
|
||||
)
|
||||
.expect("seed test gateway file");
|
||||
}
|
||||
}
|
||||
process_shared_state()
|
||||
.oauth_sessions
|
||||
.lock()
|
||||
.expect("gateway test manager registry lock")
|
||||
.push((oauth, runtime, Arc::downgrade(&manager)));
|
||||
manager
|
||||
}
|
||||
841
codex-rs/model-provider/src/shared_state_tests.rs
Normal file
841
codex-rs/model-provider/src/shared_state_tests.rs
Normal file
@@ -0,0 +1,841 @@
|
||||
//! Tests gateway-manager sharing, credential refresh, and model catalog cache isolation.
|
||||
//! Discovery and inference must preserve primary auth and reject requests when gateway auth fails.
|
||||
|
||||
use super::*;
|
||||
use crate::AgentIdentitySessionFallback;
|
||||
use crate::ProviderAuthScope;
|
||||
use crate::create_model_provider;
|
||||
use crate::test_support::seed_gateway_auth;
|
||||
use codex_api::Compression;
|
||||
use codex_api::ResponsesClient;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::ReqwestTransport;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::auth::AgentIdentityAuthPolicy;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use codex_login::default_client::create_client_for_route;
|
||||
use codex_model_provider_info::GatewayOAuthConfig;
|
||||
use codex_model_provider_info::GatewayOAuthDelivery;
|
||||
use codex_model_provider_info::GatewayOAuthSettings;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::OAuthCredentialsStore;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::protocol::CodexErrorInfo;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderName;
|
||||
use http::HeaderValue;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_credentials_accompany_primary_auth_in_models_and_responses() {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/responses"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "text/event-stream")
|
||||
.set_body_string(
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r\"}}\n\n",
|
||||
),
|
||||
)
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
for delivery in [
|
||||
GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
GatewayOAuthDelivery::Cookie {
|
||||
name: "gateway_session".into(),
|
||||
},
|
||||
] {
|
||||
let config = GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token", server.uri()),
|
||||
client_id: "test".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
// Avoid spending the model discovery deadline on keyring-backed decryption.
|
||||
credentials_store: OAuthCredentialsStore::File,
|
||||
delivery: delivery.clone(),
|
||||
};
|
||||
let info = ModelProviderInfo {
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(config)),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let mut primary_headers = HeaderMap::new();
|
||||
primary_headers.insert(
|
||||
"authorization",
|
||||
HeaderValue::from_static("Bearer primary-token"),
|
||||
);
|
||||
primary_headers.insert("chatgpt-account-id", HeaderValue::from_static("account"));
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::Headers(AuthHeaders::new(primary_headers)),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let manager = seed_gateway_auth(
|
||||
&info,
|
||||
&primary,
|
||||
json!({"access_token": "gateway-token", "refresh_token": "refresh-secret", "expires_at": i64::MAX}),
|
||||
);
|
||||
let provider = create_model_provider(info.clone(), Some(primary));
|
||||
assert!(Arc::ptr_eq(
|
||||
&provider
|
||||
.gateway_auth_manager()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.oauth_session()
|
||||
.unwrap(),
|
||||
&manager,
|
||||
));
|
||||
let models = provider.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
models.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
models
|
||||
.raw_model_catalog(RefreshStrategy::Online, factory.clone())
|
||||
.await;
|
||||
let (api, resolved) = provider
|
||||
.request_provider_and_auth(/*scope*/ None)
|
||||
.await
|
||||
.unwrap();
|
||||
let auth = resolved.auth;
|
||||
let scoped = provider
|
||||
.api_auth_for_scope(ProviderAuthScope {
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Cli,
|
||||
agent_identity_session_fallback: AgentIdentitySessionFallback::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let mut expected = HeaderMap::from_iter([
|
||||
(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer primary-token"),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("chatgpt-account-id"),
|
||||
HeaderValue::from_static("account"),
|
||||
),
|
||||
]);
|
||||
let (name, value) = match delivery {
|
||||
GatewayOAuthDelivery::Header { .. } => ("x-gateway-auth", "Bearer gateway-token"),
|
||||
GatewayOAuthDelivery::Cookie { .. } => ("cookie", "gateway_session=gateway-token"),
|
||||
};
|
||||
expected.insert(
|
||||
HeaderName::from_static(name),
|
||||
HeaderValue::from_static(value),
|
||||
);
|
||||
// Legacy consumers and asynchronous handshakes preserve the same gateway credential.
|
||||
assert_eq!(auth.to_auth_headers().unwrap(), expected);
|
||||
assert_eq!(
|
||||
auth.apply_auth_headers(HeaderMap::new()).await.unwrap(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(scoped.auth.to_auth_headers().unwrap(), expected);
|
||||
assert!(auth.to_auth_headers().unwrap()[name].is_sensitive());
|
||||
let transport = ReqwestTransport::from_http_client(
|
||||
create_client_for_route(
|
||||
&factory,
|
||||
&api.url_for_path("responses"),
|
||||
ClientRouteClass::Api,
|
||||
ClientRedirectPolicy::Default,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let client = ResponsesClient::new(transport, api, auth);
|
||||
let _stream = client
|
||||
.stream(
|
||||
json!({"model": "test", "input": []}),
|
||||
HeaderMap::new(),
|
||||
Compression::None,
|
||||
/*turn_state*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 4);
|
||||
for request in requests {
|
||||
assert_eq!(request.headers["authorization"], "Bearer primary-token");
|
||||
assert!(
|
||||
request
|
||||
.headers
|
||||
.get("x-gateway-auth")
|
||||
.is_some_and(|value| value == "Bearer gateway-token")
|
||||
|| request
|
||||
.headers
|
||||
.get("cookie")
|
||||
.is_some_and(|value| value == "gateway_session=gateway-token")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_preserves_runtime_auth_and_rejects_header_collisions() {
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-a",
|
||||
"agent_host_id": "host-a",
|
||||
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary-token"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let info = ModelProviderInfo {
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token", server.uri()),
|
||||
client_id: "client".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
credentials_store: Default::default(),
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let _gateway = seed_gateway_auth(
|
||||
&info,
|
||||
&primary,
|
||||
json!({"access_token": "gateway-token", "expires_at": i64::MAX}),
|
||||
);
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&primary),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/register", server.uri()).parse().unwrap(),
|
||||
));
|
||||
let provider = crate::test_support::runtime_model_provider(info, primary, (runtime, mode));
|
||||
let auth = provider.api_auth().await.unwrap();
|
||||
let stale_headers = HeaderMap::from_iter([
|
||||
(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer stale"),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-openai-agent-assertion"),
|
||||
HeaderValue::from_static("stale"),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("chatgpt-account-id"),
|
||||
HeaderValue::from_static("stale"),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-caller"),
|
||||
HeaderValue::from_static("retained"),
|
||||
),
|
||||
]);
|
||||
let headers = auth
|
||||
.apply_auth_headers(stale_headers.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(headers["x-gateway-auth"], "Bearer gateway-token");
|
||||
assert_eq!(headers["x-caller"], "retained");
|
||||
assert!(!headers.contains_key("chatgpt-account-id"));
|
||||
let proof_header = match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(headers["authorization"], "Bearer primary-token");
|
||||
"x-openai-agent-assertion"
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
assert!(
|
||||
headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("AgentAssertion 1.")
|
||||
);
|
||||
"authorization"
|
||||
}
|
||||
};
|
||||
let mut request = codex_http_client::Request::new(http::Method::POST, server.uri());
|
||||
request.headers = stale_headers.clone();
|
||||
let signed = auth.apply_auth(request).await.unwrap();
|
||||
assert_eq!(signed.headers["x-gateway-auth"], "Bearer gateway-token");
|
||||
assert_ne!(headers[proof_header], signed.headers[proof_header]);
|
||||
|
||||
let mut collision = stale_headers;
|
||||
collision.insert("x-gateway-auth", HeaderValue::from_static("caller-token"));
|
||||
assert!(auth.apply_auth_headers(collision.clone()).await.is_err());
|
||||
let mut request = codex_http_client::Request::new(http::Method::POST, server.uri());
|
||||
request.headers = collision;
|
||||
assert!(auth.apply_auth(request).await.is_err());
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_refresh_preserves_primary_auth_and_hides_issuer_errors() {
|
||||
for succeeds in [true, false] {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary-token"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let info = ModelProviderInfo {
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token?credential=query-secret", server.uri()),
|
||||
client_id: "client".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
credentials_store: Default::default(),
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let body = if succeeds {
|
||||
json!({"access_token": "rotated-token", "expires_in": 3600})
|
||||
} else {
|
||||
json!({"error": "server_error", "error_description": format!("query-secret {}", "sensitive ".repeat(4000))})
|
||||
};
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(if succeeds { 200 } else { 500 }).set_body_json(body),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let _gateway = seed_gateway_auth(
|
||||
&info,
|
||||
&primary,
|
||||
json!({"access_token": "expired", "refresh_token": "refresh-secret", "expires_at": 0}),
|
||||
);
|
||||
let provider = create_model_provider(info, Some(primary.clone()));
|
||||
let result = provider.api_auth().await;
|
||||
if succeeds {
|
||||
assert_eq!(
|
||||
result.unwrap().to_auth_headers().unwrap(),
|
||||
HeaderMap::from_iter([
|
||||
(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer primary-token")
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-gateway-auth"),
|
||||
HeaderValue::from_static("Bearer rotated-token")
|
||||
),
|
||||
])
|
||||
);
|
||||
} else {
|
||||
let error = match result {
|
||||
Ok(_) => panic!("issuer failure should fail auth"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(error.retry_delay(/*retry_count*/ 1).is_some());
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"Gateway OAuth authentication failed; check the gateway configuration and credential store."
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
primary.auth_cached(),
|
||||
Some(CodexAuth::from_api_key("primary-token"))
|
||||
);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert!(!requests[0].headers.contains_key("authorization"));
|
||||
assert!(!requests[0].headers.contains_key("x-gateway-auth"));
|
||||
assert_eq!(
|
||||
std::str::from_utf8(&requests[0].body)
|
||||
.unwrap()
|
||||
.split('&')
|
||||
.collect::<std::collections::BTreeSet<_>>(),
|
||||
std::collections::BTreeSet::from([
|
||||
"grant_type=refresh_token",
|
||||
"refresh_token=refresh-secret",
|
||||
"client_id=client"
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_cache_is_reused_only_for_matching_gateway_configuration() {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary-token"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let mut info = ModelProviderInfo {
|
||||
model_catalog_url: Some(format!("{}/models", server.uri()).into()),
|
||||
http_headers: Some(std::collections::HashMap::from([(
|
||||
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
|
||||
"us".into(),
|
||||
)])),
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token", server.uri()),
|
||||
client_id: "client".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
// Keyring latency is outside the cache behavior under test.
|
||||
credentials_store: OAuthCredentialsStore::File,
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let mut model = codex_models_manager::bundled_models_response()
|
||||
.unwrap()
|
||||
.models
|
||||
.remove(0);
|
||||
for resource in ["first", "second"] {
|
||||
let Some(GatewayOAuthConfig::OAuth(settings)) = &mut info.gateway_oauth else {
|
||||
unreachable!()
|
||||
};
|
||||
settings.resource = Some(format!("{}/{resource}", server.uri()));
|
||||
model.slug = format!("catalog-{resource}");
|
||||
let _gateway = seed_gateway_auth(
|
||||
&info,
|
||||
&primary,
|
||||
json!({"access_token": resource, "refresh_token": "refresh-secret", "expires_at": i64::MAX}),
|
||||
);
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.and(wiremock::matchers::header(
|
||||
"x-gateway-auth",
|
||||
format!("Bearer {resource}"),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": [&model]})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
// Recreate the provider and models manager to exercise the shared disk cache.
|
||||
// The first call for each resource fetches; the second must reuse its catalog.
|
||||
for _ in 0..2 {
|
||||
let provider = create_model_provider(info.clone(), Some(primary.clone()));
|
||||
let models = provider.models_manager(
|
||||
home.path().to_path_buf(),
|
||||
/*config_model_catalog*/ None,
|
||||
);
|
||||
models.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let catalog = models
|
||||
.raw_model_catalog(RefreshStrategy::OnlineIfUncached, factory.clone())
|
||||
.await;
|
||||
assert_eq!(catalog.models, vec![model.clone()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_observe_gateway_rotation_from_the_same_provider_instance() {
|
||||
models_observe_gateway_rotation(ProviderInstance::Same).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_observe_gateway_rotation_from_a_separate_provider_instance() {
|
||||
models_observe_gateway_rotation(ProviderInstance::Separate).await;
|
||||
}
|
||||
|
||||
enum ProviderInstance {
|
||||
Same,
|
||||
Separate,
|
||||
}
|
||||
|
||||
async fn models_observe_gateway_rotation(instance: ProviderInstance) {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary-token"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let info = ModelProviderInfo {
|
||||
model_catalog_url: Some(format!("{}/models", server.uri()).into()),
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token", server.uri()),
|
||||
client_id: "client".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
credentials_store: Default::default(),
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let gateway = seed_gateway_auth(
|
||||
&info,
|
||||
&primary,
|
||||
json!({"access_token": "first", "refresh_token": "refresh-secret", "expires_at": i64::MAX}),
|
||||
);
|
||||
let provider = create_model_provider(info.clone(), Some(primary.clone()));
|
||||
let models = provider.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
models.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let requests_provider = match instance {
|
||||
ProviderInstance::Same => provider,
|
||||
ProviderInstance::Separate => create_model_provider(info, Some(primary)),
|
||||
};
|
||||
let mut first = codex_models_manager::bundled_models_response()
|
||||
.unwrap()
|
||||
.models
|
||||
.remove(0);
|
||||
first.slug = "catalog-first".into();
|
||||
let mut second = first.clone();
|
||||
second.slug = "catalog-second".into();
|
||||
for (token, model) in [("first", &first), ("second", &second)] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.and(wiremock::matchers::header(
|
||||
"x-gateway-auth",
|
||||
format!("Bearer {token}"),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": [model]})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
assert_eq!(
|
||||
requests_provider
|
||||
.api_auth()
|
||||
.await
|
||||
.unwrap()
|
||||
.to_auth_headers()
|
||||
.unwrap(),
|
||||
HeaderMap::from_iter([
|
||||
(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer primary-token")
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-gateway-auth"),
|
||||
HeaderValue::from_static("Bearer first")
|
||||
),
|
||||
])
|
||||
);
|
||||
models
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(models.get_remote_models().await, vec![first]);
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(json!({"access_token": "second", "expires_in": 3600})),
|
||||
)
|
||||
.expect(1)
|
||||
.up_to_n_times(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
gateway.refresh_access_token("first").await.unwrap();
|
||||
assert_eq!(
|
||||
requests_provider
|
||||
.api_auth()
|
||||
.await
|
||||
.unwrap()
|
||||
.to_auth_headers()
|
||||
.unwrap(),
|
||||
HeaderMap::from_iter([
|
||||
(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer primary-token")
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-gateway-auth"),
|
||||
HeaderValue::from_static("Bearer second")
|
||||
),
|
||||
])
|
||||
);
|
||||
models
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(models.get_remote_models().await, vec![second]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_setup_errors_are_reported_when_authentication_is_requested() {
|
||||
use codex_models_manager::manager::ModelsEndpointClient;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let mut info = ModelProviderInfo {
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token", server.uri()),
|
||||
client_id: "client".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
credentials_store: Default::default(),
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let provider = create_model_provider(info.clone(), /*auth_manager*/ None);
|
||||
assert_eq!(
|
||||
provider.gateway_auth_manager().unwrap_err().to_string(),
|
||||
"gateway_oauth requires auth runtime configuration"
|
||||
);
|
||||
let error = provider.api_auth().await.err().unwrap();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"gateway_oauth requires auth runtime configuration"
|
||||
);
|
||||
|
||||
let primary = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("primary"));
|
||||
let endpoint = crate::models_endpoint::OpenAiModelsEndpoint::new(
|
||||
info.clone(),
|
||||
Some(primary),
|
||||
Some(Err("failed to create provider OAuth HTTP client".into())),
|
||||
);
|
||||
let error = endpoint
|
||||
.list_models(
|
||||
"test",
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"failed to create provider OAuth HTTP client"
|
||||
);
|
||||
|
||||
let Some(GatewayOAuthConfig::OAuth(settings)) = &mut info.gateway_oauth else {
|
||||
unreachable!()
|
||||
};
|
||||
settings.client_id.clear();
|
||||
let primary = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("primary"));
|
||||
let error = create_model_provider(info, Some(primary))
|
||||
.api_auth()
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
codex_protocol::error::CodexErrorDetails::InvalidRequest(_)
|
||||
));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_login_required_invalidates_the_last_successful_catalog() {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary-token"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let info = ModelProviderInfo {
|
||||
model_catalog_url: Some(format!("{}/models", server.uri()).into()),
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token", server.uri()),
|
||||
client_id: "client".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
credentials_store: OAuthCredentialsStore::File,
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let login_control = codex_login::GatewayLoginControl::for_runtime(&primary.runtime_config());
|
||||
login_control.require_explicit_login();
|
||||
let gateway = seed_gateway_auth(
|
||||
&info,
|
||||
&primary,
|
||||
json!({"access_token": "first", "refresh_token": "revoked", "expires_at": i64::MAX}),
|
||||
);
|
||||
let provider = create_model_provider(info, Some(primary));
|
||||
let models = provider.models_manager(
|
||||
home.path().to_path_buf(),
|
||||
/*config_model_catalog*/ None,
|
||||
);
|
||||
models.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let catalog = codex_models_manager::bundled_models_response().unwrap();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(&catalog))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
assert_eq!(
|
||||
models
|
||||
.raw_model_catalog(RefreshStrategy::Online, factory.clone())
|
||||
.await,
|
||||
catalog
|
||||
);
|
||||
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/token"))
|
||||
.respond_with(ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let error = gateway.refresh_access_token("first").await.unwrap_err();
|
||||
assert!(matches!(
|
||||
error
|
||||
.get_ref()
|
||||
.and_then(|source| source.downcast_ref::<codex_login::GatewayAuthError>()),
|
||||
Some(codex_login::GatewayAuthError::LoginRequired)
|
||||
));
|
||||
assert_eq!(
|
||||
models
|
||||
.raw_model_catalog(RefreshStrategy::Online, factory.clone())
|
||||
.await,
|
||||
codex_protocol::openai_models::ModelsResponse::default()
|
||||
);
|
||||
// Recreate the manager to verify persistent invalidation as well as the in-memory result.
|
||||
let restarted = provider.models_manager(
|
||||
home.path().to_path_buf(),
|
||||
/*config_model_catalog*/ None,
|
||||
);
|
||||
restarted.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
assert_eq!(
|
||||
restarted
|
||||
.raw_model_catalog(RefreshStrategy::Offline, factory)
|
||||
.await,
|
||||
codex_protocol::openai_models::ModelsResponse::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_login_states_stop_request_retries() {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let primary = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("primary-token"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let info = ModelProviderInfo {
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: format!("{}/authorize", server.uri()),
|
||||
device_authorization_url: None,
|
||||
token_url: format!("{}/token", server.uri()),
|
||||
client_id: "client".into(),
|
||||
resource: None,
|
||||
scopes: vec![],
|
||||
redirect_port: None,
|
||||
credentials_store: Default::default(),
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
|
||||
};
|
||||
let login_control = codex_login::GatewayLoginControl::for_runtime(&primary.runtime_config());
|
||||
login_control.require_explicit_login();
|
||||
let provider = create_model_provider(info, Some(primary));
|
||||
let gateway = provider.gateway_auth_manager().unwrap().unwrap();
|
||||
let error = provider.api_auth().await.err().expect("login required");
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
CodexErrorDetails::GatewayLoginRequired(_)
|
||||
));
|
||||
assert_eq!(
|
||||
(
|
||||
error.to_string(),
|
||||
error.retry_delay(/*retry_count*/ 1),
|
||||
error.to_codex_protocol_error()
|
||||
),
|
||||
(
|
||||
codex_login::GatewayAuthError::LoginRequired.to_string(),
|
||||
None,
|
||||
CodexErrorInfo::Other
|
||||
),
|
||||
);
|
||||
let cancel = tokio::sync::Notify::new();
|
||||
let (url_tx, url_rx) = tokio::sync::oneshot::channel();
|
||||
let oauth = gateway.oauth_session().unwrap();
|
||||
let login = oauth.login_with_browser(cancel.notified(), |_| {
|
||||
let _ = url_tx.send(());
|
||||
});
|
||||
let check = async {
|
||||
url_rx.await.unwrap();
|
||||
let error = provider.api_auth().await.err().expect("login in progress");
|
||||
assert!(matches!(
|
||||
error.details(),
|
||||
CodexErrorDetails::InvalidRequest(_)
|
||||
));
|
||||
assert_eq!(
|
||||
(error.to_string(), error.retry_delay(/*retry_count*/ 1)),
|
||||
(
|
||||
codex_login::GatewayAuthError::LoginInProgress.to_string(),
|
||||
None
|
||||
),
|
||||
);
|
||||
cancel.notify_one();
|
||||
};
|
||||
let (result, ()) = tokio::join!(login, check);
|
||||
assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
25
codex-rs/model-provider/src/test_support.rs
Normal file
25
codex-rs/model-provider/src/test_support.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
//! Fixtures for integration tests that seed provider credentials and model caches.
|
||||
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::cache::ModelsCacheEntry;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
|
||||
/// Constructs a cache fixture matching the supplied test provider and authentication.
|
||||
pub fn models_cache_entry(
|
||||
provider_info: &ModelProviderInfo,
|
||||
auth: Option<&CodexAuth>,
|
||||
models: Vec<ModelInfo>,
|
||||
) -> ModelsCacheEntry {
|
||||
ModelsCacheEntry {
|
||||
fetched_at: std::time::SystemTime::now().into(),
|
||||
etag: None,
|
||||
client_version: Some(codex_models_manager::client_version_to_whole()),
|
||||
identity: crate::models_identity::identity(provider_info, auth).ok(),
|
||||
models,
|
||||
}
|
||||
}
|
||||
|
||||
pub use crate::shared_state::test_support::seed_gateway_auth;
|
||||
|
||||
pub use crate::provider::test_support::runtime_model_provider;
|
||||
107
codex-rs/model-provider/src/workspace_routing.rs
Normal file
107
codex-rs/model-provider/src/workspace_routing.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
//! Applies discovered routing and keeps requests within the selected ChatGPT backend.
|
||||
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingSession;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use http::HeaderValue;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use url::Url;
|
||||
|
||||
pub const ACCOUNT_ROUTING_HEADER: &str = "x-openai-account-routing-override";
|
||||
|
||||
/// Routing scope for one session's provider. Once routed, it cannot become
|
||||
/// independent merely because the account owner's bootstrap configuration changes.
|
||||
/// Clones serialize discovery and share the first successful routing transition.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WorkspaceRoutingContext {
|
||||
pub(crate) chatgpt_base_url: String,
|
||||
pub(crate) previously_routed: Arc<Mutex<bool>>,
|
||||
pub(crate) session: Option<Arc<WorkspaceRoutingSession>>,
|
||||
}
|
||||
|
||||
impl WorkspaceRoutingContext {
|
||||
pub fn new(chatgpt_base_url: String) -> Self {
|
||||
Self {
|
||||
chatgpt_base_url,
|
||||
previously_routed: Arc::new(Mutex::new(/*t*/ false)),
|
||||
session: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_session(mut self, session: WorkspaceRoutingSession) -> Self {
|
||||
self.session = Some(Arc::new(session));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes only the origin of requests to the selected ChatGPT backend.
|
||||
pub(crate) fn apply_workspace_routing(
|
||||
provider: &mut codex_api::Provider,
|
||||
routing: WorkspaceRouting,
|
||||
) -> io::Result<()> {
|
||||
let base_url = &mut provider.base_url;
|
||||
let headers = &mut provider.headers;
|
||||
let parse = |value: &str| Url::parse(value).map_err(io::Error::other);
|
||||
let mut url = parse(base_url)?;
|
||||
let backend = parse(&routing.backend_origin)?;
|
||||
if backend.scheme() != "https"
|
||||
|| backend.host_str().is_none()
|
||||
|| !backend.username().is_empty()
|
||||
|| backend.password().is_some()
|
||||
|| backend.path() != "/"
|
||||
|| backend.query().is_some()
|
||||
|| backend.fragment().is_some()
|
||||
{
|
||||
return Err(io::Error::other("invalid workspace backend origin"));
|
||||
}
|
||||
let header = match routing.account_routing_override.as_str() {
|
||||
"NO_CONSTRAINT" => None,
|
||||
"us" | "us_cr" => Some(
|
||||
HeaderValue::from_str(&routing.account_routing_override).map_err(io::Error::other)?,
|
||||
),
|
||||
_ => return Err(io::Error::other("invalid workspace routing override")),
|
||||
};
|
||||
url.set_scheme(backend.scheme())
|
||||
.map_err(|()| io::Error::other("invalid backend scheme"))?;
|
||||
url.set_host(backend.host_str()).map_err(io::Error::other)?;
|
||||
url.set_port(backend.port())
|
||||
.map_err(|()| io::Error::other("invalid backend port"))?;
|
||||
*base_url = url.into();
|
||||
headers.remove(ACCOUNT_ROUTING_HEADER);
|
||||
if let Some(header) = header {
|
||||
headers.insert(ACCOUNT_ROUTING_HEADER, header);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// API deployment and redirect policy resolved for one Responses request.
|
||||
/// Workspace routes reject redirects even when their routing override supplies no header.
|
||||
#[derive(Debug)]
|
||||
pub struct ResolvedResponsesProvider {
|
||||
pub provider: codex_api::Provider,
|
||||
pub redirect_policy: ClientRedirectPolicy,
|
||||
}
|
||||
|
||||
/// Effective destination and credentials that permit reusing a Responses socket.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResponsesConnectionKey {
|
||||
base_url: String,
|
||||
routing_header: Option<HeaderValue>,
|
||||
auth_revision: Option<u64>,
|
||||
}
|
||||
|
||||
impl ResponsesConnectionKey {
|
||||
pub fn new(provider: &codex_api::Provider, auth_revision: Option<u64>) -> Self {
|
||||
Self {
|
||||
base_url: provider.base_url.clone(),
|
||||
routing_header: provider.headers.get(ACCOUNT_ROUTING_HEADER).cloned(),
|
||||
auth_revision,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "workspace_routing_tests.rs"]
|
||||
mod workspace_routing_tests;
|
||||
200
codex-rs/model-provider/src/workspace_routing_tests.rs
Normal file
200
codex-rs/model-provider/src/workspace_routing_tests.rs
Normal file
@@ -0,0 +1,200 @@
|
||||
//! Routing is limited to the selected ChatGPT backend and successful discovery.
|
||||
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::ACCOUNT_ROUTING_HEADER;
|
||||
use crate::WorkspaceRoutingContext;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::create_model_provider;
|
||||
|
||||
struct Routing(WorkspaceRouting);
|
||||
|
||||
struct ChangedBootstrap {
|
||||
first_lookup: std::sync::atomic::AtomicBool,
|
||||
release_first: tokio::sync::Notify,
|
||||
}
|
||||
|
||||
impl WorkspaceRoutingResolver for ChangedBootstrap {
|
||||
fn resolve(
|
||||
&self,
|
||||
request: WorkspaceRoutingRequest,
|
||||
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
if self
|
||||
.first_lookup
|
||||
.swap(false, std::sync::atomic::Ordering::Relaxed)
|
||||
{
|
||||
self.release_first.notified().await;
|
||||
Ok(Some(WorkspaceRouting {
|
||||
chatgpt_account_id: "account_id".into(),
|
||||
backend_origin: "https://gov.chatgpt.com".into(),
|
||||
account_routing_override: "us_cr".into(),
|
||||
}))
|
||||
} else if request.previously_routed {
|
||||
Err(io::Error::other("bootstrap changed"))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_discovery_cannot_forget_established_routing() {
|
||||
let context = WorkspaceRoutingContext::new("https://chatgpt.com/backend-api".into());
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let resolver = Arc::new(ChangedBootstrap {
|
||||
first_lookup: std::sync::atomic::AtomicBool::new(true),
|
||||
release_first: tokio::sync::Notify::new(),
|
||||
});
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(
|
||||
&(resolver.clone() as Arc<dyn WorkspaceRoutingResolver>),
|
||||
));
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
Some(auth),
|
||||
);
|
||||
let mut first = provider.responses_api_provider(&context);
|
||||
let classifier_context = context.clone();
|
||||
let mut second = provider.responses_api_provider(&classifier_context);
|
||||
let early_second = std::future::poll_fn(|cx| {
|
||||
assert!(first.as_mut().poll(cx).is_pending());
|
||||
std::task::Poll::Ready(second.as_mut().poll(cx))
|
||||
})
|
||||
.await;
|
||||
resolver.release_first.notify_one();
|
||||
assert_eq!(
|
||||
first.await.unwrap().provider.base_url,
|
||||
"https://gov.chatgpt.com/backend-api/codex"
|
||||
);
|
||||
let second = match early_second {
|
||||
std::task::Poll::Ready(result) => result,
|
||||
std::task::Poll::Pending => second.await,
|
||||
};
|
||||
assert!(
|
||||
second.is_err(),
|
||||
"a concurrent lookup must retain the first lookup's routing scope"
|
||||
);
|
||||
}
|
||||
|
||||
impl WorkspaceRoutingResolver for Routing {
|
||||
fn resolve(
|
||||
&self,
|
||||
request: WorkspaceRoutingRequest,
|
||||
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
|
||||
Box::pin(async move {
|
||||
let origin = url::Url::parse(&request.provider_base_url)
|
||||
.unwrap()
|
||||
.origin();
|
||||
let bootstrap = url::Url::parse(&request.chatgpt_base_url).unwrap().origin();
|
||||
Ok((origin == bootstrap).then(|| self.0.clone()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn workspace_routing_preserves_paths_and_excludes_other_providers() {
|
||||
let routing_context = WorkspaceRoutingContext::new("https://chatgpt.com/backend-api".into());
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> = Arc::new(Routing(WorkspaceRouting {
|
||||
chatgpt_account_id: "account_id".into(),
|
||||
backend_origin: "https://gov.chatgpt.com:8443".into(),
|
||||
account_routing_override: "us_cr".into(),
|
||||
}));
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let provider = create_model_provider(info.clone(), Some(auth.clone()));
|
||||
let routed = provider
|
||||
.responses_api_provider(&routing_context)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
routed.provider.base_url.as_str(),
|
||||
routed.provider.headers[ACCOUNT_ROUTING_HEADER]
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
routed.redirect_policy,
|
||||
),
|
||||
(
|
||||
"https://gov.chatgpt.com:8443/backend-api/codex",
|
||||
"us_cr",
|
||||
ClientRedirectPolicy::Reject
|
||||
)
|
||||
);
|
||||
let mut custom_auth = info.clone();
|
||||
custom_auth.experimental_bearer_token = Some("custom-token".into());
|
||||
let mut unrelated_path = info.clone();
|
||||
unrelated_path.base_url = Some("https://chatgpt.com/v1".into());
|
||||
for info in [custom_auth, unrelated_path] {
|
||||
let provider = create_model_provider(info, Some(auth.clone()));
|
||||
let ordinary = provider.api_provider().await.unwrap();
|
||||
let responses = provider
|
||||
.responses_api_provider(&routing_context)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
responses.provider.base_url,
|
||||
responses.provider.headers,
|
||||
responses.redirect_policy
|
||||
),
|
||||
(
|
||||
ordinary.base_url,
|
||||
ordinary.headers,
|
||||
ClientRedirectPolicy::Default
|
||||
)
|
||||
);
|
||||
}
|
||||
let api_auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("api-key"));
|
||||
api_auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let api = create_model_provider(info, Some(api_auth))
|
||||
.responses_api_provider(&routing_context)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(api.provider.base_url, "https://api.openai.com/v1");
|
||||
assert!(!api.provider.headers.contains_key(ACCOUNT_ROUTING_HEADER));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_routing_owner_and_wrong_workspace_fail_closed() {
|
||||
let routing_context = WorkspaceRoutingContext::new("https://chatgpt.com/backend-api".into());
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> = Arc::new(Routing(WorkspaceRouting {
|
||||
chatgpt_account_id: "other-account".into(),
|
||||
backend_origin: "https://chatgpt.com".into(),
|
||||
account_routing_override: "NO_CONSTRAINT".into(),
|
||||
}));
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
Some(auth),
|
||||
);
|
||||
assert!(
|
||||
provider
|
||||
.responses_api_provider(&routing_context)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
drop(resolver);
|
||||
assert!(
|
||||
provider
|
||||
.responses_api_provider(&routing_context)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
305
codex-rs/model-provider/tests/runtime_catalog.rs
Normal file
305
codex-rs/model-provider/tests/runtime_catalog.rs
Normal file
@@ -0,0 +1,305 @@
|
||||
//! Exercise catalog auth through the public provider factory and real HTTPS transport.
|
||||
#![cfg(test)]
|
||||
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::model_info::model_info_from_slug;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::process::Command;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const CHILD_SERVER: &str = "CODEX_RUNTIME_CATALOG_TEST_SERVER";
|
||||
const TEST_NAME: &str = "production_catalog_uses_runtime_auth_and_preserves_provider_isolation";
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_catalog_uses_runtime_auth_and_preserves_provider_isolation() {
|
||||
if let Ok(server) = std::env::var(CHILD_SERVER) {
|
||||
check_catalog(&server).await;
|
||||
return;
|
||||
}
|
||||
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a",
|
||||
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":null},
|
||||
})))
|
||||
.expect(2).mount(&server).await;
|
||||
let catalog = ModelsResponse {
|
||||
models: vec![model_info_from_slug("runtime-catalog-marker")],
|
||||
};
|
||||
for (url, count) in [("/backend-api/codex/models", 4), ("/models", 2)] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(url))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(&catalog))
|
||||
.expect(count)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Scope proxy and CA configuration to a child process, preserving the real OpenAI
|
||||
// URL classification without changing environment variables used by other tests.
|
||||
let (ca, tls) = tls_config();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let ca_path = home.path().join("catalog-ca.pem");
|
||||
std::fs::write(&ca_path, ca).unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy_url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let upstream = *server.address();
|
||||
let proxy = tokio::spawn(async move {
|
||||
for _ in 0..4 {
|
||||
let (stream, _) = tokio::time::timeout(Duration::from_secs(30), listener.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let stream = stream.into_std().unwrap();
|
||||
let tls = Arc::clone(&tls);
|
||||
tokio::task::spawn_blocking(move || proxy_catalog(stream, tls, upstream))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let mut command = Command::new(std::env::current_exe().unwrap());
|
||||
command
|
||||
.arg("--exact")
|
||||
.arg(TEST_NAME)
|
||||
.arg("--nocapture")
|
||||
.kill_on_drop(/*kill_on_drop*/ true);
|
||||
for key in [
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
"NO_PROXY",
|
||||
"no_proxy",
|
||||
"OPENAI_API_KEY",
|
||||
"OPENAI_PROJECT",
|
||||
"OPENAI_ORGANIZATION",
|
||||
"SSL_CERT_FILE",
|
||||
"SSL_CERT_DIR",
|
||||
] {
|
||||
command.env_remove(key);
|
||||
}
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_secs(30),
|
||||
command
|
||||
.env(CHILD_SERVER, server.uri())
|
||||
.env("HTTPS_PROXY", proxy_url)
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("SSL_CERT_FILE", ca_path)
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if !output.status.success() {
|
||||
proxy.abort();
|
||||
}
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"catalog child failed:\n{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
proxy.await.unwrap();
|
||||
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let catalogs: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/backend-api/codex/models")
|
||||
.collect();
|
||||
assert_eq!(catalogs.len(), 4);
|
||||
let mut proofs = std::collections::HashSet::new();
|
||||
for request in catalogs {
|
||||
let authorization = request.headers["authorization"].to_str().unwrap();
|
||||
let proof = if let Some(proof) = request.headers.get("x-openai-agent-assertion") {
|
||||
assert_eq!(authorization, "Bearer catalog-key");
|
||||
proof.to_str().unwrap()
|
||||
} else {
|
||||
authorization.strip_prefix("AgentAssertion ").unwrap()
|
||||
};
|
||||
let payload: Value = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(proof.split('.').nth(2).unwrap())
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(payload["runtime_agent_instance"], "runtime-a");
|
||||
assert!(proofs.insert(payload["id"].as_str().unwrap().to_owned()));
|
||||
}
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/backend-api/codex/models"
|
||||
&& request.headers["originator"] == "codex_work_cca")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/models")
|
||||
{
|
||||
assert_eq!(request.headers["authorization"], "Bearer catalog-key");
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
async fn check_catalog(server: &str) {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("catalog-key"));
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: None,
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{server}/register").parse().unwrap(),
|
||||
));
|
||||
let context = ProviderAuthContext {
|
||||
credentials,
|
||||
runtime_auth: Some((runtime, mode)),
|
||||
};
|
||||
let info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
let provider = context.model_provider(info);
|
||||
let selected = provider
|
||||
.request_auth(/*scope*/ None)
|
||||
.await
|
||||
.unwrap()
|
||||
.runtime
|
||||
.unwrap();
|
||||
assert_eq!(selected.runtime().id(), "runtime-a");
|
||||
let models = provider.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
models.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let work = models.for_originator("codex_work_cca").unwrap();
|
||||
for manager in [models, work] {
|
||||
let result = manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
result
|
||||
.models
|
||||
.iter()
|
||||
.any(|model| model.slug == "runtime-catalog-marker"),
|
||||
"the returned catalog must contain the remote model"
|
||||
);
|
||||
}
|
||||
let mut other_info = ModelProviderInfo::create_openai_provider(Some(server.to_owned()));
|
||||
other_info.model_catalog_url = Some(format!("{server}/models").into());
|
||||
let other = context.model_provider(other_info);
|
||||
let models = other.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
models.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let result = models
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
result
|
||||
.models
|
||||
.iter()
|
||||
.any(|model| model.slug == "runtime-catalog-marker"),
|
||||
"the other provider must also receive its remote catalog"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn tls_config() -> (String, Arc<rustls::ServerConfig>) {
|
||||
codex_utils_rustls_provider::ensure_rustls_crypto_provider();
|
||||
let mut ca_params = rcgen::CertificateParams::default();
|
||||
ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
|
||||
ca_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
|
||||
let ca = rcgen::CertifiedIssuer::self_signed(ca_params, rcgen::KeyPair::generate().unwrap())
|
||||
.unwrap();
|
||||
let mut leaf = rcgen::CertificateParams::new(vec!["chatgpt.com".into()]).unwrap();
|
||||
leaf.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth];
|
||||
let key = rcgen::KeyPair::generate().unwrap();
|
||||
let cert = leaf.signed_by(&key, &ca).unwrap();
|
||||
let config = rustls::ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(
|
||||
vec![cert.der().clone()],
|
||||
rustls::pki_types::PrivateKeyDer::from(key),
|
||||
)
|
||||
.unwrap();
|
||||
(ca.pem(), Arc::new(config))
|
||||
}
|
||||
|
||||
fn proxy_catalog(
|
||||
mut stream: std::net::TcpStream,
|
||||
config: Arc<rustls::ServerConfig>,
|
||||
upstream: std::net::SocketAddr,
|
||||
) {
|
||||
stream.set_nonblocking(/*nonblocking*/ false).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
stream
|
||||
.set_write_timeout(Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
let connect = read_headers(&mut stream);
|
||||
assert!(connect.starts_with(b"CONNECT chatgpt.com:443 "));
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
.unwrap();
|
||||
let mut tls = rustls::StreamOwned::new(rustls::ServerConnection::new(config).unwrap(), stream);
|
||||
let mut headers = read_headers(&mut tls);
|
||||
assert!(headers.starts_with(b"GET /backend-api/codex/models?"));
|
||||
headers.truncate(headers.len() - 2);
|
||||
headers.extend_from_slice(b"connection: close\r\n\r\n");
|
||||
let mut origin = std::net::TcpStream::connect(upstream).unwrap();
|
||||
origin
|
||||
.set_read_timeout(Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
origin.write_all(&headers).unwrap();
|
||||
let mut response = Vec::new();
|
||||
origin.read_to_end(&mut response).unwrap();
|
||||
tls.write_all(&response).unwrap();
|
||||
tls.flush().unwrap();
|
||||
}
|
||||
|
||||
fn read_headers(reader: &mut impl Read) -> Vec<u8> {
|
||||
let mut headers = Vec::new();
|
||||
while !headers.ends_with(b"\r\n\r\n") {
|
||||
let mut byte = [0_u8];
|
||||
reader.read_exact(&mut byte).unwrap();
|
||||
headers.push(byte[0]);
|
||||
assert!(headers.len() < 64 * 1024);
|
||||
}
|
||||
headers
|
||||
}
|
||||
Reference in New Issue
Block a user