mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Add AWS credential export commands for Amazon Bedrock (#44028)
## What changed Support `model_providers.amazon-bedrock.aws.credential_export` with `command`, `args`, and `timeout_ms` to supply SigV4 signing credentials from a command's JSON output. Accept both flat credential-process output and nested STS `Credentials` objects. Cache credentials in memory, refresh before expiration, and share exports across sessions with matching AWS configuration. On recoverable authentication failures, run the optional `aws.auth_refresh` command before exporting fresh credentials, coalescing concurrent recovery attempts. Bound command execution time and output size, and keep credential values out of errors. Reject combining `aws.credential_export` with `aws.profile`. Bedrock setup and login reject changes while an exporter is configured, preserving configuration and saved credentials. ## Testing Add coverage for output formats, expiration, credential precedence, caching, concurrent recovery, command failures, and secret redaction. Integration tests verify request signing with rotated credentials, bounded recovery attempts, and setup/login rejection across configuration layers. GitOrigin-RevId: 4ef799f88ab5e3b2578f8f41a5e56e4f30e2cd81
This commit is contained in:
1 parent
2ce38ae6d8
commit
fe52d795c9
26 files changed
+1790
-89
No files matched your search
@@ -19,6 +19,7 @@ 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;
|
||||
@@ -34,6 +35,7 @@ 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,
|
||||
@@ -55,6 +57,12 @@ pub(super) fn auth_source(
|
||||
) -> 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()
|
||||
@@ -93,6 +101,24 @@ pub(super) async fn resolve_auth_method(
|
||||
"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)
|
||||
.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(
|
||||
@@ -234,6 +260,17 @@ fn aws_auth_error_to_codex_error(error: AwsAuthError) -> CodexErr {
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -303,9 +340,12 @@ impl AuthProvider for BedrockSigV4AuthProvider {
|
||||
|
||||
#[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;
|
||||
|
||||
@@ -322,6 +362,18 @@ mod tests {
|
||||
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 =
|
||||
@@ -342,6 +394,22 @@ mod tests {
|
||||
&[&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()),
|
||||
@@ -418,6 +486,7 @@ mod tests {
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some(" us-west-2 ".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
|name| match name {
|
||||
@@ -450,6 +519,7 @@ mod tests {
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
|name| match name {
|
||||
@@ -468,6 +538,7 @@ mod tests {
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
|name| match name {
|
||||
@@ -486,6 +557,7 @@ mod tests {
|
||||
&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
},
|
||||
missing_env_var,
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
//! 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::ops::Deref;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
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::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
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);
|
||||
const MAX_CREDENTIAL_OUTPUT_BYTES: u64 = 64 * 1024;
|
||||
|
||||
#[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 program = Path::new(&self.config.command);
|
||||
let mut components = program.components();
|
||||
let is_bare_command = matches!(
|
||||
(components.next(), components.next()),
|
||||
(Some(Component::Normal(name)), None) if name == program.as_os_str()
|
||||
);
|
||||
if self.config.command.trim().is_empty() || (!program.is_absolute() && !is_bare_command) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"AWS credential export command must be an absolute path or a bare executable name",
|
||||
));
|
||||
}
|
||||
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
.args(self.config.args.iter().map(Deref::deref))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
|
||||
let mut child = command.spawn().map_err(|error| {
|
||||
io::Error::new(
|
||||
error.kind(),
|
||||
format!(
|
||||
"failed to run AWS credential export command `{}`: {error}",
|
||||
self.config.command
|
||||
),
|
||||
)
|
||||
})?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| io::Error::other("AWS credential export stdout is unavailable"))?;
|
||||
let output = tokio::time::timeout(self.config.timeout(), async {
|
||||
let mut output = Vec::new();
|
||||
stdout
|
||||
.take(MAX_CREDENTIAL_OUTPUT_BYTES + 1)
|
||||
.read_to_end(&mut output)
|
||||
.await?;
|
||||
if output.len() as u64 > MAX_CREDENTIAL_OUTPUT_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"AWS credential export output exceeds 64 KiB",
|
||||
));
|
||||
}
|
||||
let status = child.wait().await?;
|
||||
if !status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"AWS credential export command exited with {status}"
|
||||
)));
|
||||
}
|
||||
Ok(output)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
format!(
|
||||
"AWS credential export command timed out after {} ms",
|
||||
self.config.timeout_ms
|
||||
),
|
||||
)
|
||||
})??;
|
||||
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,348 @@
|
||||
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 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 as usize)
|
||||
);
|
||||
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 as usize, 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 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!(
|
||||
!refresh
|
||||
.expect_err("queued login recovery must still run")
|
||||
.is_retryable()
|
||||
);
|
||||
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(())
|
||||
}
|
||||
@@ -4,6 +4,9 @@ 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, ",
|
||||
@@ -11,6 +14,11 @@ pub(super) const BEDROCK_EXPIRED_SIGNATURE_MESSAGE: &str = concat!(
|
||||
);
|
||||
|
||||
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
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
use std::num::NonZeroU64;
|
||||
|
||||
use codex_api::ApiError;
|
||||
use codex_api::TransportError;
|
||||
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";
|
||||
|
||||
@@ -144,3 +152,62 @@ fn classifies_only_refreshable_bedrock_auth_failures() {
|
||||
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).is_retryable(), retryable);
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,7 @@ mod tests {
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: Some("codex-bedrock".to_string()),
|
||||
region: None,
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
@@ -110,6 +111,7 @@ mod tests {
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some(" us-west-2 ".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod auth;
|
||||
mod auth_refresh;
|
||||
mod catalog;
|
||||
mod credential_export;
|
||||
mod error;
|
||||
mod mantle;
|
||||
mod runtime;
|
||||
@@ -43,6 +44,7 @@ use auth::resolve_provider_auth as resolve_bedrock_provider_auth;
|
||||
pub(crate) use auth_refresh::AwsAuthRecovery;
|
||||
use catalog::normalize_bedrock_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_supported_amazon_bedrock_region;
|
||||
use runtime::bedrock_runtime_base_url;
|
||||
@@ -61,6 +63,7 @@ pub(crate) struct AmazonBedrockModelProvider {
|
||||
aws: ModelProviderAwsAuthInfo,
|
||||
endpoint: BedrockEndpoint,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
credential_export: Option<Arc<AwsCredentialExport>>,
|
||||
auth_recovery: Option<Arc<AwsAuthRecovery>>,
|
||||
}
|
||||
|
||||
@@ -80,11 +83,20 @@ impl AmazonBedrockModelProvider {
|
||||
.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::auth_source(&provider_info, auth_manager.as_deref(), std::env::var),
|
||||
auth::BedrockAuthSource::ConfiguredAwsProfile | auth::BedrockAuthSource::AwsSdk
|
||||
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)
|
||||
@@ -97,6 +109,7 @@ impl AmazonBedrockModelProvider {
|
||||
aws,
|
||||
endpoint,
|
||||
auth_manager,
|
||||
credential_export,
|
||||
auth_recovery,
|
||||
}
|
||||
}
|
||||
@@ -125,11 +138,13 @@ impl AmazonBedrockModelProvider {
|
||||
}
|
||||
|
||||
fn uses_aws_auth_recovery(&self) -> bool {
|
||||
self.auth_recovery.is_some()
|
||||
&& matches!(
|
||||
self.auth_source(),
|
||||
auth::BedrockAuthSource::ConfiguredAwsProfile | auth::BedrockAuthSource::AwsSdk
|
||||
)
|
||||
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> {
|
||||
@@ -140,7 +155,8 @@ impl AmazonBedrockModelProvider {
|
||||
},
|
||||
auth::BedrockAuthSource::ManagedBearerToken
|
||||
| auth::BedrockAuthSource::ManagedAccessKeys => self.managed_auth(),
|
||||
auth::BedrockAuthSource::ConfiguredAwsProfile
|
||||
auth::BedrockAuthSource::CredentialExport
|
||||
| auth::BedrockAuthSource::ConfiguredAwsProfile
|
||||
| auth::BedrockAuthSource::EnvBearerToken
|
||||
| auth::BedrockAuthSource::EnvAwsCredentials
|
||||
| auth::BedrockAuthSource::AwsSdk => None,
|
||||
@@ -231,7 +247,8 @@ impl ModelProvider for AmazonBedrockModelProvider {
|
||||
auth::BedrockAuthSource::CommandBearerToken
|
||||
| auth::BedrockAuthSource::ManagedBearerToken
|
||||
| auth::BedrockAuthSource::ManagedAccessKeys => self.auth_manager.clone(),
|
||||
auth::BedrockAuthSource::ConfiguredAwsProfile
|
||||
auth::BedrockAuthSource::CredentialExport
|
||||
| auth::BedrockAuthSource::ConfiguredAwsProfile
|
||||
| auth::BedrockAuthSource::EnvBearerToken
|
||||
| auth::BedrockAuthSource::EnvAwsCredentials
|
||||
| auth::BedrockAuthSource::AwsSdk => None,
|
||||
@@ -257,16 +274,39 @@ impl ModelProvider for AmazonBedrockModelProvider {
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, Result<ProviderUnauthorizedRecovery>> {
|
||||
Box::pin(async move {
|
||||
let Some(recovery) = self
|
||||
.auth_recovery
|
||||
.as_ref()
|
||||
.filter(|_| self.uses_aws_auth_recovery())
|
||||
else {
|
||||
if !self.uses_aws_auth_recovery() {
|
||||
return Ok(ProviderUnauthorizedRecovery::NotConfigured);
|
||||
};
|
||||
}
|
||||
|
||||
recovery.refresh().await.map_err(|error| {
|
||||
if error.kind() == std::io::ErrorKind::InvalidInput {
|
||||
// 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 result: std::io::Result<()> = async {
|
||||
if let Some(recovery) = &self.auth_recovery {
|
||||
recovery.refresh().await?;
|
||||
}
|
||||
if let Some(exporter) = export_refresh {
|
||||
exporter.refresh().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
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)
|
||||
@@ -388,6 +428,7 @@ mod tests {
|
||||
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()],
|
||||
@@ -423,6 +464,7 @@ mod tests {
|
||||
regional_provider_info.aws = Some(ModelProviderAwsAuthInfo {
|
||||
profile: None,
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
});
|
||||
let regional_provider =
|
||||
@@ -448,6 +490,7 @@ mod tests {
|
||||
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()],
|
||||
|
||||
@@ -19,6 +19,7 @@ fn aws_auth_config_uses_bedrock_service() {
|
||||
aws_auth_config(&ModelProviderAwsAuthInfo {
|
||||
profile: Some("runtime-profile".to_string()),
|
||||
region: Some(" eu-west-1 ".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
}),
|
||||
AwsAuthConfig {
|
||||
|
||||
@@ -514,13 +514,17 @@ impl ModelProvider for ConfiguredModelProvider {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::future::Future;
|
||||
use std::num::NonZeroU64;
|
||||
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;
|
||||
@@ -766,6 +770,7 @@ mod tests {
|
||||
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(
|
||||
@@ -823,6 +828,7 @@ mod tests {
|
||||
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(
|
||||
@@ -903,6 +909,93 @@ mod tests {
|
||||
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 {
|
||||
|
||||
@@ -6,10 +6,12 @@ use std::sync::Weak;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
|
||||
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 {
|
||||
aws_credential_exports: Mutex<Vec<(ModelProviderAwsAuthInfo, Weak<AwsCredentialExport>)>>,
|
||||
aws_auth_recoveries: Mutex<Vec<(ModelProviderAwsAuthInfo, Weak<AwsAuthRecovery>)>>,
|
||||
}
|
||||
|
||||
@@ -19,6 +21,30 @@ pub(crate) fn process_shared_state() -> &'static ModelProviderSharedState {
|
||||
}
|
||||
|
||||
impl ModelProviderSharedState {
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user