Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,166 @@
use codex_backend_client::Client as BackendClient;
use codex_backend_client::ConfigBundleResponse;
use codex_backend_client::DeliveredTomlFragment;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigFragment;
use codex_config::CloudConfigTomlBundle;
use codex_config::CloudRequirementsFragment;
use codex_config::CloudRequirementsTomlBundle;
use codex_http_client::HttpClientFactory;
use codex_login::CodexAuth;
use std::future::Future;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum RetryableFailureKind {
Request { status_code: Option<u16> },
AuthRecovery { status_code: Option<u16> },
}
impl RetryableFailureKind {
pub(crate) fn status_code(self) -> Option<u16> {
match self {
Self::Request { status_code } | Self::AuthRecovery { status_code } => status_code,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum BundleRequestError {
Policy(codex_http_client::NetworkPolicyDenied),
Fatal {
error: codex_config::CloudConfigBundleLoadError,
metric_reason: Option<&'static str>,
},
Retryable(RetryableFailureKind),
Unauthorized {
status_code: Option<u16>,
message: String,
},
}
impl BundleRequestError {
pub(crate) fn auth_failure(
status_code: Option<u16>,
message: impl Into<String>,
metric_reason: Option<&'static str>,
) -> Self {
Self::Fatal {
error: codex_config::CloudConfigBundleLoadError::new(
codex_config::CloudConfigBundleLoadErrorCode::Auth,
status_code,
message,
),
metric_reason,
}
}
}
/// Retrieves one cloud config bundle from the backend.
///
/// Implementations should return the backend-selected bundle exactly as delivered and leave
/// validation, caching, and config/requirements parsing decisions to the service layer.
pub(crate) trait BundleClient: Send + Sync {
fn get_bundle(
&self,
auth: &CodexAuth,
) -> impl Future<Output = Result<CloudConfigBundle, BundleRequestError>> + Send;
}
pub(crate) struct BackendBundleClient {
base_url: String,
http_client_factory: HttpClientFactory,
}
impl BackendBundleClient {
pub(crate) fn new(base_url: String, http_client_factory: HttpClientFactory) -> Self {
Self {
base_url,
http_client_factory,
}
}
}
impl BundleClient for BackendBundleClient {
async fn get_bundle(&self, auth: &CodexAuth) -> Result<CloudConfigBundle, BundleRequestError> {
let client = BackendClient::from_auth(
self.base_url.clone(),
auth,
self.http_client_factory.clone(),
);
fetch_bundle(&client).await
}
}
pub(crate) async fn fetch_bundle(
client: &BackendClient,
) -> Result<CloudConfigBundle, BundleRequestError> {
client
.get_config_bundle()
.await
.map(bundle_from_response)
.map_err(bundle_request_error)
}
fn bundle_request_error(error: codex_backend_client::RequestError) -> BundleRequestError {
if let codex_backend_client::RequestError::Policy(denied) = &error {
return BundleRequestError::Policy(*denied);
}
let status_code = error.status().map(|status| status.as_u16());
if error.is_unauthorized() {
BundleRequestError::Unauthorized {
status_code,
message: "Managed configuration sign-in is required".into(),
}
} else {
BundleRequestError::Retryable(RetryableFailureKind::Request { status_code })
}
}
pub(crate) fn bundle_from_response(response: ConfigBundleResponse) -> CloudConfigBundle {
let config_toml = response
.config_toml
.flatten()
.map(|config_toml| *config_toml)
.and_then(|config_toml| config_toml.enterprise_managed.flatten())
.unwrap_or_default()
.into_iter()
.map(config_fragment_from_delivered)
.collect();
let requirements_toml = response
.requirements_toml
.flatten()
.map(|requirements_toml| *requirements_toml)
.and_then(|requirements_toml| requirements_toml.enterprise_managed.flatten())
.unwrap_or_default()
.into_iter()
.map(requirements_fragment_from_delivered)
.collect();
CloudConfigBundle {
config_toml: CloudConfigTomlBundle {
enterprise_managed: config_toml,
},
requirements_toml: CloudRequirementsTomlBundle {
enterprise_managed: requirements_toml,
},
}
}
fn config_fragment_from_delivered(fragment: DeliveredTomlFragment) -> CloudConfigFragment {
CloudConfigFragment {
id: fragment.id,
name: fragment.name,
contents: fragment.contents,
}
}
fn requirements_fragment_from_delivered(
fragment: DeliveredTomlFragment,
) -> CloudRequirementsFragment {
CloudRequirementsFragment {
id: fragment.id,
name: fragment.name,
contents: fragment.contents,
}
}

View File

@@ -0,0 +1,261 @@
use crate::backend::BackendBundleClient;
use crate::chatgpt::ChatGptSource;
use crate::chatgpt::plan_requires_managed_config;
use crate::config_server::config_server_http_client_factory;
use crate::config_source::BundleSource;
use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT;
use crate::service::CloudConfigBundleService;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigRequirementsToml;
use codex_http_client::HttpClientFactory;
use codex_login::AuthConfig;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::account::PlanType;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::task::AbortHandle;
use tokio::task::JoinHandle;
pub fn managed_config_auth_manager(
auth: AuthConfig,
requirements: &ConfigRequirementsToml,
) -> std::io::Result<Option<codex_login::OAuthSessionManager>> {
let Some(service_config) = requirements.config_server.as_ref() else {
return Ok(None);
};
let factory = config_server_http_client_factory(service_config, &auth.auth_route_config);
crate::config_server_auth_manager(service_config, auth.codex_home, &factory)
}
/// Existing grants are left to the loader's normal cache and refresh handling.
pub async fn ensure_config_server_login(
auth: AuthConfig,
requirements: &ConfigRequirementsToml,
) -> std::io::Result<()> {
let Some(manager) = managed_config_auth_manager(auth, requirements)? else {
return Ok(());
};
if let Err(error) = manager.authorization_id().await {
if error
.get_ref()
.and_then(|source| source.downcast_ref::<codex_login::OAuthSessionError>())
!= Some(&codex_login::OAuthSessionError::LoginRequired)
{
return Err(error);
}
manager.login().await?;
}
Ok(())
}
pub fn managed_config_bundle_loader(
auth_manager: Arc<AuthManager>,
chatgpt_base_url: String,
codex_home: PathBuf,
factory: HttpClientFactory,
requirements: &ConfigRequirementsToml,
) -> CloudConfigBundleLoader {
if let Some(service_config) = requirements.config_server.as_ref() {
let factory = config_server_http_client_factory(
service_config,
&codex_login::AuthRouteConfig::from_http_client_factory(factory),
);
return crate::config_server_bundle_loader(service_config.clone(), codex_home, factory);
}
let endpoint = codex_backend_client::Client::new(chatgpt_base_url.clone(), factory.clone())
.config_bundle_url();
let policy = factory
.network_policy()
.clone()
.restrict_to_endpoints(endpoint.parse().into_iter().collect());
chatgpt_config_bundle_loader(
auth_manager,
chatgpt_base_url,
codex_home,
factory.with_network_policy(policy),
)
}
pub async fn managed_config_bundle_loader_for_storage(
auth_config: AuthConfig,
requirements: &ConfigRequirementsToml,
enable_codex_api_key_env: bool,
) -> std::io::Result<CloudConfigBundleLoader> {
if let Some(service_config) = requirements.config_server.as_ref() {
let factory =
config_server_http_client_factory(service_config, &auth_config.auth_route_config);
return Ok(crate::config_server_bundle_loader(
service_config.clone(),
auth_config.codex_home,
factory,
));
}
let service =
chatgpt_config_bundle_service_for_storage(auth_config, enable_codex_api_key_env).await?;
Ok(managed_config_bundle_loader_for_service(service).0)
}
struct CloudConfigBundleLoaderLifetime<C: BundleSource> {
service: Arc<CloudConfigBundleService<C>>,
refresh_task: AbortHandle,
}
impl<C: BundleSource> Drop for CloudConfigBundleLoaderLifetime<C> {
fn drop(&mut self) {
self.refresh_task.abort();
}
}
pub fn chatgpt_config_bundle_loader(
auth_manager: Arc<AuthManager>,
chatgpt_base_url: String,
codex_home: PathBuf,
http_client_factory: HttpClientFactory,
) -> CloudConfigBundleLoader {
let service = CloudConfigBundleService::new(
auth_manager,
Arc::new(BackendBundleClient::new(
chatgpt_base_url,
http_client_factory,
)),
codex_home,
CLOUD_CONFIG_BUNDLE_TIMEOUT,
);
let (loader, _) = managed_config_bundle_loader_for_service(service);
loader
}
pub(crate) fn managed_config_bundle_loader_for_service<C>(
service: CloudConfigBundleService<C>,
) -> (CloudConfigBundleLoader, JoinHandle<()>)
where
C: BundleSource + 'static,
{
let service = Arc::new(service);
let background_service = Arc::clone(&service);
let refresh_task = tokio::spawn(async move {
let _ = background_service.get_latest().await;
background_service.refresh_cache_in_background().await;
});
let abort_handle = refresh_task.abort_handle();
let lifetime = Arc::new(CloudConfigBundleLoaderLifetime {
service,
refresh_task: abort_handle,
});
let snapshot_lifetime = Arc::clone(&lifetime);
let policy = lifetime.service.policy.clone();
let loader = CloudConfigBundleLoader::from_getter(move || {
let lifetime = Arc::clone(&lifetime);
async move { lifetime.service.get_latest().await }
})
.with_ema_policy_snapshots(policy, move || {
let lifetime = Arc::clone(&snapshot_lifetime);
async move { lifetime.service.get_latest_snapshot().await }
});
(loader, refresh_task)
}
pub async fn chatgpt_config_bundle_loader_for_storage(
auth_config: AuthConfig,
enable_codex_api_key_env: bool,
) -> std::io::Result<CloudConfigBundleLoader> {
let service =
chatgpt_config_bundle_service_for_storage(auth_config, enable_codex_api_key_env).await?;
let (loader, _) = managed_config_bundle_loader_for_service(service);
Ok(loader)
}
/// Use the configured policy server or the supplied account's ChatGPT policy when eligible.
pub async fn managed_config_bundle_loader_for_auth(
config: AuthConfig,
auth: &CodexAuth,
requirements: &ConfigRequirementsToml,
) -> std::io::Result<CloudConfigBundleLoader> {
if requirements.config_server.is_some() {
return managed_config_bundle_loader_for_storage(
config,
requirements,
/*enable_codex_api_key_env*/ false,
)
.await;
}
// Only skip the policy lookup when the supplied account's plan is known.
if auth
.account_plan_type()
.is_some_and(|plan| plan != PlanType::Unknown && !plan_requires_managed_config(plan))
{
return Ok(CloudConfigBundleLoader::default());
}
let base_url = config
.chatgpt_base_url
.as_deref()
.unwrap_or("https://chatgpt.com/backend-api/");
codex_http_client::validate_https_endpoint_url(base_url, "ChatGPT policy endpoint")
.map_err(std::io::Error::other)?;
let mut client = codex_backend_client::Client::new_without_redirects(
base_url,
config.auth_route_config.http_client_factory().clone(),
)
.with_user_agent(codex_login::default_client::get_codex_user_agent())
.with_bearer_token(auth.get_token()?)
.map_err(std::io::Error::other)?
.with_chatgpt_account_id(
auth.get_account_id()
.ok_or_else(|| std::io::Error::other("missing ChatGPT account ID"))?,
);
if auth.is_fedramp_account() {
client = client.with_fedramp_routing_header();
}
let response = tokio::time::timeout(CLOUD_CONFIG_BUNDLE_TIMEOUT, client.get_config_bundle())
.await
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
"timed out loading ChatGPT account policy",
)
})?
.map_err(|_| std::io::Error::other("could not load ChatGPT account policy"))?;
let bundle = crate::backend::bundle_from_response(response);
Ok(CloudConfigBundleLoader::new(
async move { Ok(Some(bundle)) },
))
}
/// Fetches directly from the network on each load, without reading or writing
/// the disk cache or starting a background refresher.
pub async fn chatgpt_config_bundle_loader_for_storage_without_cache(
auth_config: AuthConfig,
enable_codex_api_key_env: bool,
) -> std::io::Result<CloudConfigBundleLoader> {
let service = Arc::new(
chatgpt_config_bundle_service_for_storage(auth_config, enable_codex_api_key_env)
.await?
.without_cache(),
);
Ok(CloudConfigBundleLoader::from_getter(move || {
let service = Arc::clone(&service);
async move { service.load_startup_bundle_with_timeout().await }
}))
}
async fn chatgpt_config_bundle_service_for_storage(
auth_config: AuthConfig,
enable_codex_api_key_env: bool,
) -> std::io::Result<CloudConfigBundleService<ChatGptSource<BackendBundleClient>>> {
let auth_manager =
AuthManager::shared_from_auth_config(auth_config.clone(), enable_codex_api_key_env).await?;
Ok(CloudConfigBundleService::new(
auth_manager,
Arc::new(BackendBundleClient::new(
auth_config
.chatgpt_base_url
.unwrap_or_else(|| "https://chatgpt.com/backend-api/".to_string()),
auth_config.auth_route_config.http_client_factory().clone(),
)),
auth_config.codex_home,
CLOUD_CONFIG_BUNDLE_TIMEOUT,
))
}

View File

@@ -0,0 +1,292 @@
//! Signed on-disk cache for cloud config bundles.
//!
//! The cache is scoped to the authenticated ChatGPT user and account, has a
//! short TTL, and is HMAC-signed so malformed or edited files fail closed.
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use chrono::DateTime;
use chrono::Duration as ChronoDuration;
use chrono::Utc;
use codex_config::AbsolutePathBuf;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundlePolicyRevision;
use hmac::Hmac;
use hmac::Mac;
use serde::Deserialize;
use serde::Serialize;
use sha2::Sha256;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use tempfile::NamedTempFile;
use thiserror::Error;
use tokio::fs;
const CLOUD_CONFIG_BUNDLE_CACHE_VERSION: u32 = 1;
pub(super) const CLOUD_CONFIG_BUNDLE_CACHE_FILENAME: &str = "cloud-config-bundle-cache.json";
const CLOUD_CONFIG_BUNDLE_CACHE_TTL: Duration = Duration::from_secs(60 * 60);
const CLOUD_CONFIG_BUNDLE_CACHE_WRITE_HMAC_KEY: &[u8] =
b"codex-cloud-config-bundle-cache-v1-6160ae70-bcfd-4ca8-a99b-40f73b3b072e";
const CLOUD_CONFIG_BUNDLE_CACHE_READ_HMAC_KEYS: &[&[u8]] =
&[CLOUD_CONFIG_BUNDLE_CACHE_WRITE_HMAC_KEY];
type HmacSha256 = Hmac<Sha256>;
#[derive(Clone)]
pub(super) struct CloudConfigBundleCache {
path: AbsolutePathBuf,
}
impl CloudConfigBundleCache {
pub(super) fn new(codex_home: AbsolutePathBuf) -> Self {
Self {
path: codex_home.join(CLOUD_CONFIG_BUNDLE_CACHE_FILENAME),
}
}
pub(super) fn for_source(codex_home: AbsolutePathBuf, namespace: &str) -> Self {
Self {
path: codex_home.join(format!("managed-config-{namespace}.json")),
}
}
pub(super) fn path(&self) -> &Path {
&self.path
}
pub(super) async fn load(
&self,
chatgpt_user_id: Option<&str>,
account_id: Option<&str>,
) -> Result<CloudConfigBundleCacheSignedPayload, CacheLoadStatus> {
let (Some(chatgpt_user_id), Some(account_id)) = (chatgpt_user_id, account_id) else {
return Err(CacheLoadStatus::AuthIdentityIncomplete);
};
let bytes = match fs::read(&self.path).await {
Ok(bytes) => bytes,
Err(err) => {
if err.kind() != std::io::ErrorKind::NotFound {
return Err(CacheLoadStatus::CacheReadFailed(err.to_string()));
}
return Err(CacheLoadStatus::CacheFileNotFound);
}
};
let cache_file: CloudConfigBundleCacheFile = match serde_json::from_slice(&bytes) {
Ok(cache_file) => cache_file,
Err(err) => {
return Err(CacheLoadStatus::CacheParseFailed(err.to_string()));
}
};
let payload_bytes = match cache_payload_bytes(&cache_file.signed_payload) {
Some(payload_bytes) => payload_bytes,
None => {
return Err(CacheLoadStatus::CacheParseFailed(
"failed to serialize cache payload".to_string(),
));
}
};
if !verify_cache_signature(&payload_bytes, &cache_file.signature) {
return Err(CacheLoadStatus::CacheSignatureInvalid);
}
if cache_file.signed_payload.version != CLOUD_CONFIG_BUNDLE_CACHE_VERSION {
return Err(CacheLoadStatus::CacheVersionUnsupported(
cache_file.signed_payload.version,
));
}
let (Some(cached_chatgpt_user_id), Some(cached_account_id)) = (
cache_file.signed_payload.chatgpt_user_id.as_deref(),
cache_file.signed_payload.account_id.as_deref(),
) else {
return Err(CacheLoadStatus::CacheIdentityIncomplete);
};
if cached_chatgpt_user_id != chatgpt_user_id || cached_account_id != account_id {
return Err(CacheLoadStatus::CacheIdentityMismatch);
}
if cache_file.signed_payload.expires_at <= Utc::now() {
return Err(CacheLoadStatus::CacheExpired);
}
Ok(cache_file.signed_payload)
}
pub(super) fn log_load_status(&self, status: &CacheLoadStatus) {
if matches!(status, CacheLoadStatus::CacheFileNotFound) {
return;
}
let warn = matches!(
status,
CacheLoadStatus::CacheReadFailed(_)
| CacheLoadStatus::CacheParseFailed(_)
| CacheLoadStatus::CacheSignatureInvalid
);
if warn {
tracing::warn!(path = %self.path.display(), "{status}");
} else {
tracing::info!(path = %self.path.display(), "{status}");
}
}
pub(super) async fn prepare(
&self,
chatgpt_user_id: Option<String>,
account_id: Option<String>,
bundle: CloudConfigBundle,
) -> Result<StagedCloudConfigBundleCache, CloudConfigBundleCacheError> {
let now = Utc::now();
let expires_at = now
.checked_add_signed(
ChronoDuration::from_std(CLOUD_CONFIG_BUNDLE_CACHE_TTL)
.map_err(|_| CloudConfigBundleCacheError)?,
)
.ok_or(CloudConfigBundleCacheError)?;
let signed_payload = CloudConfigBundleCacheSignedPayload {
version: CLOUD_CONFIG_BUNDLE_CACHE_VERSION,
cached_at: now,
expires_at,
chatgpt_user_id,
account_id,
bundle,
};
let payload_bytes =
cache_payload_bytes(&signed_payload).ok_or(CloudConfigBundleCacheError)?;
let serialized = serde_json::to_vec_pretty(&CloudConfigBundleCacheFile {
signature: sign_cache_payload(&payload_bytes).ok_or(CloudConfigBundleCacheError)?,
signed_payload,
})
.map_err(|_| CloudConfigBundleCacheError)?;
let destination = self.path.to_path_buf();
tokio::task::spawn_blocking(move || {
let parent = destination.parent().ok_or(CloudConfigBundleCacheError)?;
std::fs::create_dir_all(parent).map_err(|_| CloudConfigBundleCacheError)?;
let mut temporary =
NamedTempFile::new_in(parent).map_err(|_| CloudConfigBundleCacheError)?;
temporary
.write_all(&serialized)
.map_err(|_| CloudConfigBundleCacheError)?;
Ok(StagedCloudConfigBundleCache {
temporary,
destination,
})
})
.await
.map_err(|_| CloudConfigBundleCacheError)?
}
}
pub(super) struct StagedCloudConfigBundleCache {
temporary: NamedTempFile,
destination: PathBuf,
}
impl StagedCloudConfigBundleCache {
pub(super) async fn publish_if_current(
self,
revision: CloudConfigBundlePolicyRevision,
) -> Result<(), CloudConfigBundleCacheError> {
tokio::task::spawn_blocking(move || {
revision.commit_if_current(|| {
self.temporary
.persist(self.destination)
.map(|_| ())
.map_err(|_| CloudConfigBundleCacheError)
})
})
.await
.map_err(|_| CloudConfigBundleCacheError)?
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub(super) enum CacheLoadStatus {
#[error("Skipping cloud config bundle cache read because auth identity is incomplete.")]
AuthIdentityIncomplete,
#[error("Cloud config bundle cache file not found.")]
CacheFileNotFound,
#[error("Failed to read cloud config bundle cache: {0}.")]
CacheReadFailed(String),
#[error("Failed to parse cloud config bundle cache: {0}.")]
CacheParseFailed(String),
#[error("Cloud config bundle cache failed signature verification.")]
CacheSignatureInvalid,
#[error("Ignoring cloud config bundle cache because cached identity is incomplete.")]
CacheIdentityIncomplete,
#[error("Ignoring cloud config bundle cache for different auth identity.")]
CacheIdentityMismatch,
#[error("Ignoring cloud config bundle cache with unsupported version {0}.")]
CacheVersionUnsupported(u32),
#[error("Cloud config bundle cache expired.")]
CacheExpired,
#[error("Ignoring cloud config bundle cache because the cached bundle is invalid.")]
CacheInvalidBundle,
}
#[derive(Debug, Error)]
#[error("failed to write cloud config bundle cache")]
pub(super) struct CloudConfigBundleCacheError;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(super) struct CloudConfigBundleCacheFile {
pub(super) signed_payload: CloudConfigBundleCacheSignedPayload,
pub(super) signature: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(super) struct CloudConfigBundleCacheSignedPayload {
pub(super) version: u32,
pub(super) cached_at: DateTime<Utc>,
pub(super) expires_at: DateTime<Utc>,
pub(super) chatgpt_user_id: Option<String>,
pub(super) account_id: Option<String>,
pub(super) bundle: CloudConfigBundle,
}
pub(super) fn cache_payload_bytes(
payload: &CloudConfigBundleCacheSignedPayload,
) -> Option<Vec<u8>> {
serde_json::to_vec(&payload).ok()
}
pub(super) fn sign_cache_payload(payload_bytes: &[u8]) -> Option<String> {
let mut mac = HmacSha256::new_from_slice(CLOUD_CONFIG_BUNDLE_CACHE_WRITE_HMAC_KEY).ok()?;
mac.update(payload_bytes);
let signature = mac.finalize().into_bytes();
Some(BASE64_STANDARD.encode(signature))
}
pub(super) fn verify_cache_signature(payload_bytes: &[u8], signature: &str) -> bool {
let signature_bytes = match BASE64_STANDARD.decode(signature) {
Ok(signature_bytes) => signature_bytes,
Err(_) => return false,
};
CLOUD_CONFIG_BUNDLE_CACHE_READ_HMAC_KEYS
.iter()
.any(|key| verify_cache_signature_with_key(payload_bytes, &signature_bytes, key))
}
fn verify_cache_signature_with_key(
payload_bytes: &[u8],
signature_bytes: &[u8],
key: &[u8],
) -> bool {
let mut mac = match HmacSha256::new_from_slice(key) {
Ok(mac) => mac,
Err(_) => return false,
};
mac.update(payload_bytes);
mac.verify_slice(signature_bytes).is_ok()
}
#[cfg(test)]
#[path = "cache_tests.rs"]
mod tests;

View File

@@ -0,0 +1,212 @@
use super::*;
use codex_config::AbsolutePathBuf;
use codex_config::CloudConfigFragment;
use codex_config::CloudConfigTomlBundle;
use codex_config::CloudRequirementsFragment;
use codex_config::CloudRequirementsTomlBundle;
use pretty_assertions::assert_eq;
use std::path::Path;
use tempfile::tempdir;
fn test_bundle() -> CloudConfigBundle {
CloudConfigBundle {
config_toml: CloudConfigTomlBundle {
enterprise_managed: vec![CloudConfigFragment {
id: "cfg_1".to_string(),
name: "Base config".to_string(),
contents: "model = \"gpt-5\"".to_string(),
}],
},
requirements_toml: CloudRequirementsTomlBundle {
enterprise_managed: vec![CloudRequirementsFragment {
id: "req_1".to_string(),
name: "Base requirements".to_string(),
contents: "allowed_approval_policies = [\"never\"]".to_string(),
}],
},
}
}
fn signed_cache_file(
signed_payload: CloudConfigBundleCacheSignedPayload,
) -> CloudConfigBundleCacheFile {
let payload_bytes = cache_payload_bytes(&signed_payload).expect("payload bytes");
CloudConfigBundleCacheFile {
signature: sign_cache_payload(&payload_bytes).expect("signature"),
signed_payload,
}
}
fn valid_signed_payload() -> CloudConfigBundleCacheSignedPayload {
let cached_at = Utc::now();
CloudConfigBundleCacheSignedPayload {
version: CLOUD_CONFIG_BUNDLE_CACHE_VERSION,
cached_at,
expires_at: cached_at + ChronoDuration::minutes(30),
chatgpt_user_id: Some("user-12345".to_string()),
account_id: Some("account-12345".to_string()),
bundle: test_bundle(),
}
}
fn write_cache_file(cache: &CloudConfigBundleCache, cache_file: &CloudConfigBundleCacheFile) {
std::fs::write(
cache.path(),
serde_json::to_vec_pretty(cache_file).expect("serialize cache"),
)
.expect("write cache");
}
fn create_test_cache(codex_home: &Path) -> CloudConfigBundleCache {
CloudConfigBundleCache::new(AbsolutePathBuf::resolve_path_against_base(codex_home, "/"))
}
#[tokio::test]
async fn save_writes_signed_payload_and_loads_for_matching_identity() {
let codex_home = tempdir().expect("tempdir");
let cache = create_test_cache(codex_home.path());
let bundle = test_bundle();
let revision = codex_config::CloudConfigBundlePolicy::default()
.observe_remote_bundle(&bundle)
.expect("cache revision");
cache
.prepare(
Some("user-12345".to_string()),
Some("account-12345".to_string()),
bundle.clone(),
)
.await
.expect("stage cache")
.publish_if_current(revision)
.await
.expect("save cache");
let cache_file: CloudConfigBundleCacheFile =
serde_json::from_slice(&std::fs::read(cache.path()).expect("read cache"))
.expect("parse cache");
assert!(
cache_file.signed_payload.expires_at
<= cache_file.signed_payload.cached_at + ChronoDuration::minutes(60)
);
assert!(cache_file.signed_payload.expires_at > cache_file.signed_payload.cached_at);
assert_eq!(
cache_file,
signed_cache_file(CloudConfigBundleCacheSignedPayload {
version: CLOUD_CONFIG_BUNDLE_CACHE_VERSION,
cached_at: cache_file.signed_payload.cached_at,
expires_at: cache_file.signed_payload.expires_at,
chatgpt_user_id: Some("user-12345".to_string()),
account_id: Some("account-12345".to_string()),
bundle,
})
);
assert_eq!(
cache.load(Some("user-12345"), Some("account-12345")).await,
Ok(cache_file.signed_payload)
);
}
#[tokio::test]
async fn load_rejects_missing_request_identity_before_reading_cache_file() {
let codex_home = tempdir().expect("tempdir");
let cache = create_test_cache(codex_home.path());
assert_eq!(
cache
.load(/*chatgpt_user_id*/ None, Some("account-12345"))
.await,
Err(CacheLoadStatus::AuthIdentityIncomplete)
);
assert_eq!(
cache.load(Some("user-12345"), /*account_id*/ None).await,
Err(CacheLoadStatus::AuthIdentityIncomplete)
);
}
#[tokio::test]
async fn load_reports_missing_and_malformed_cache_files() {
let codex_home = tempdir().expect("tempdir");
let cache = create_test_cache(codex_home.path());
assert_eq!(
cache.load(Some("user-12345"), Some("account-12345")).await,
Err(CacheLoadStatus::CacheFileNotFound)
);
std::fs::write(cache.path(), "{").expect("write malformed cache");
assert!(matches!(
cache.load(Some("user-12345"), Some("account-12345")).await,
Err(CacheLoadStatus::CacheParseFailed(_))
));
}
#[tokio::test]
async fn load_rejects_tampered_payload() {
let codex_home = tempdir().expect("tempdir");
let cache = create_test_cache(codex_home.path());
let mut cache_file = signed_cache_file(valid_signed_payload());
cache_file
.signed_payload
.bundle
.requirements_toml
.enterprise_managed[0]
.contents = "allowed_approval_policies = [\"on-request\"]".to_string();
write_cache_file(&cache, &cache_file);
assert_eq!(
cache.load(Some("user-12345"), Some("account-12345")).await,
Err(CacheLoadStatus::CacheSignatureInvalid)
);
}
#[tokio::test]
async fn load_rejects_cache_for_incomplete_or_different_identity() {
let codex_home = tempdir().expect("tempdir");
let cache = create_test_cache(codex_home.path());
let cache_file = signed_cache_file(valid_signed_payload());
write_cache_file(&cache, &cache_file);
assert_eq!(
cache.load(Some("user-99999"), Some("account-12345")).await,
Err(CacheLoadStatus::CacheIdentityMismatch)
);
let mut signed_payload = valid_signed_payload();
signed_payload.chatgpt_user_id = None;
write_cache_file(&cache, &signed_cache_file(signed_payload));
assert_eq!(
cache.load(Some("user-12345"), Some("account-12345")).await,
Err(CacheLoadStatus::CacheIdentityIncomplete)
);
}
#[tokio::test]
async fn load_rejects_expired_cache() {
let codex_home = tempdir().expect("tempdir");
let cache = create_test_cache(codex_home.path());
let mut signed_payload = valid_signed_payload();
signed_payload.expires_at = Utc::now() - ChronoDuration::seconds(1);
write_cache_file(&cache, &signed_cache_file(signed_payload));
assert_eq!(
cache.load(Some("user-12345"), Some("account-12345")).await,
Err(CacheLoadStatus::CacheExpired)
);
}
#[tokio::test]
async fn load_rejects_unsupported_cache_version() {
let codex_home = tempdir().expect("tempdir");
let cache = create_test_cache(codex_home.path());
let mut signed_payload = valid_signed_payload();
signed_payload.version = 2;
write_cache_file(&cache, &signed_cache_file(signed_payload));
assert_eq!(
cache.load(Some("user-12345"), Some("account-12345")).await,
Err(CacheLoadStatus::CacheVersionUnsupported(2))
);
}

View File

@@ -0,0 +1,103 @@
//! ChatGPT eligibility, credentials, and account identity for managed configuration.
use crate::backend::BundleClient;
use crate::backend::BundleRequestError;
use crate::backend::RetryableFailureKind;
use crate::config_source::BundleSource;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLoadError;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::RefreshTokenError;
use codex_login::UnauthorizedRecovery;
use codex_protocol::account::PlanType;
use std::sync::Arc;
const CLOUD_CONFIG_BUNDLE_AUTH_RECOVERY_FAILED_MESSAGE: &str = concat!(
"Your authentication session could not be refreshed automatically. ",
"Please log out and sign in again."
);
pub(super) fn plan_requires_managed_config(plan: PlanType) -> bool {
plan.is_business_like()
|| plan.is_education_like()
|| matches!(
plan,
PlanType::Enterprise | PlanType::Sci | PlanType::SciPlus
)
}
pub(crate) struct ChatGptSource<C> {
pub(crate) auth_manager: Arc<AuthManager>,
pub(crate) client: Arc<C>,
}
impl<C: BundleClient> BundleSource for ChatGptSource<C> {
type Auth = CodexAuth;
type FetchContext = UnauthorizedRecovery;
fn begin_fetch(&self) -> Self::FetchContext {
self.auth_manager.unauthorized_recovery()
}
async fn auth(&self) -> Result<Option<CodexAuth>, CloudConfigBundleLoadError> {
Ok(self.auth_manager.auth().await.filter(|auth| {
auth.uses_codex_backend()
&& auth
.account_plan_type()
.is_some_and(plan_requires_managed_config)
}))
}
fn identity(&self, auth: &CodexAuth) -> (Option<String>, Option<String>) {
(auth.get_chatgpt_user_id(), auth.get_account_id())
}
async fn get_bundle(
&self,
auth: &mut CodexAuth,
_context: &mut UnauthorizedRecovery,
) -> Result<CloudConfigBundle, BundleRequestError> {
self.client.get_bundle(auth).await
}
async fn recover_auth(
&self,
auth: &mut CodexAuth,
recovery: &mut UnauthorizedRecovery,
status_code: Option<u16>,
_recovery_attempt: usize,
) -> Result<bool, BundleRequestError> {
if !recovery.has_next() {
return Err(BundleRequestError::auth_failure(
status_code,
CLOUD_CONFIG_BUNDLE_AUTH_RECOVERY_FAILED_MESSAGE,
Some("auth_recovery_unavailable"),
));
}
match recovery.next().await {
Ok(_) => {
*auth = self.auth_manager.auth().await.ok_or_else(|| {
BundleRequestError::auth_failure(
status_code,
CLOUD_CONFIG_BUNDLE_AUTH_RECOVERY_FAILED_MESSAGE,
Some("auth_recovery_missing_auth"),
)
})?;
Ok(true)
}
Err(RefreshTokenError::Transient(_)) => Err(BundleRequestError::Retryable(
RetryableFailureKind::AuthRecovery { status_code },
)),
Err(RefreshTokenError::Permanent(failed)) => Err(BundleRequestError::auth_failure(
status_code,
failed.message,
Some("auth_recovery_unrecoverable"),
)),
Err(RefreshTokenError::Policy(error)) => Err(BundleRequestError::auth_failure(
status_code,
error.to_string(),
/*metric_reason*/ None,
)),
}
}
}

View File

@@ -0,0 +1,274 @@
//! Fetch managed configuration from a custom config server.
//! Cache entries are scoped to the endpoint and the current OAuth sign-in.
use crate::backend::BundleRequestError;
use crate::backend::RetryableFailureKind;
use crate::backend::fetch_bundle;
use crate::config_source::BundleSource;
use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT;
use crate::service::CloudConfigBundleService;
use codex_backend_client::Client as BackendClient;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigServer;
use codex_http_client::HttpClientFactory;
use codex_keyring_store::DefaultKeyringStore;
use codex_login::AuthRouteConfig;
use codex_login::OAuthSessionConfig;
use codex_login::OAuthSessionError;
use codex_login::OAuthSessionManager;
use codex_login::OAuthSessionRequest;
use sha2::Digest;
use sha2::Sha256;
use std::path::PathBuf;
use std::sync::Arc;
pub fn config_server_bundle_loader(
config: ConfigServer,
codex_home: PathBuf,
factory: HttpClientFactory,
) -> CloudConfigBundleLoader {
match ConfigServerSource::from_config_server(config.clone(), codex_home.clone(), factory) {
Ok(source) => {
let service = CloudConfigBundleService::from_source(
source,
codex_home,
CLOUD_CONFIG_BUNDLE_TIMEOUT,
);
crate::bundle_loader::managed_config_bundle_loader_for_service(service).0
}
Err(error) => CloudConfigBundleLoader::new(std::future::ready(Err(error))),
}
.with_config_server(config)
}
pub fn config_server_auth_manager(
service_config: &ConfigServer,
codex_home: PathBuf,
factory: &HttpClientFactory,
) -> std::io::Result<Option<OAuthSessionManager>> {
service_config
.validated_base_url()
.map_err(std::io::Error::other)?;
oauth_session_manager(service_config.oauth.as_deref(), codex_home, factory)
}
pub(crate) fn config_server_http_client_factory(
config: &ConfigServer,
routes: &AuthRouteConfig,
) -> HttpClientFactory {
let endpoint = config.validated_base_url().ok().map(|base_url| {
BackendClient::for_config_endpoint(base_url, routes.http_client_factory().clone())
.config_bundle_url()
});
let endpoints = endpoint
.as_deref()
.into_iter()
.chain(config.oauth.as_ref().map(|oauth| oauth.token_url.as_str()))
.chain(
config
.oauth
.as_ref()
.and_then(|oauth| oauth.device_authorization_url.as_deref()),
)
.filter_map(|endpoint| endpoint.parse().ok());
routes.http_client_factory_for_bootstrap(endpoints)
}
struct ConfigServerSource {
cache_namespace: String,
client: BackendClient,
auth: Option<OAuthSessionManager>,
}
fn oauth_session_manager(
oauth: Option<&OAuthSessionConfig>,
codex_home: PathBuf,
factory: &HttpClientFactory,
) -> std::io::Result<Option<OAuthSessionManager>> {
oauth
.map(|oauth| {
OAuthSessionManager::new(
oauth.clone(),
codex_home,
factory,
Arc::new(DefaultKeyringStore),
)
.map(OAuthSessionManager::without_interactive_login)
})
.transpose()
}
impl ConfigServerSource {
fn from_config_server(
config: ConfigServer,
codex_home: PathBuf,
factory: HttpClientFactory,
) -> Result<Self, CloudConfigBundleLoadError> {
let base_url = config.validated_base_url().map_err(|message| {
CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::Internal,
/*status_code*/ None,
message,
)
})?;
Self::new(
base_url,
config.oauth.map(|oauth| *oauth),
codex_home,
factory,
)
}
fn new(
base_url: String,
oauth: Option<OAuthSessionConfig>,
codex_home: PathBuf,
factory: HttpClientFactory,
) -> Result<Self, CloudConfigBundleLoadError> {
let auth =
oauth_session_manager(oauth.as_ref(), codex_home, &factory).map_err(auth_io_error)?;
let client = BackendClient::for_config_endpoint(base_url, factory);
// Reuse the OAuth session's issuer/client/audience/scope identity; the endpoint
// additionally separates policy authorities that share one OAuth grant.
let namespace = serde_json::to_vec(&(
client.config_bundle_url(),
auth.as_ref().map(OAuthSessionManager::credential_id),
))
.map_err(|_| auth_failure())?;
Ok(Self {
client,
cache_namespace: format!("{:x}", Sha256::digest(namespace)),
auth,
})
}
}
impl BundleSource for ConfigServerSource {
type Auth = Option<String>;
type FetchContext = Option<OAuthSessionRequest>;
fn begin_fetch(&self) -> Self::FetchContext {
self.auth.as_ref().map(OAuthSessionManager::begin_request)
}
async fn auth(&self) -> Result<Option<Self::Auth>, CloudConfigBundleLoadError> {
// Cache reads need the grant identity, not a refreshed access token.
Ok(Some(match &self.auth {
Some(auth) => Some(auth.authorization_id().await.map_err(auth_io_error)?),
None => None,
}))
}
fn cache_namespace(&self) -> Option<String> {
Some(self.cache_namespace.clone())
}
fn identity(&self, auth: &Self::Auth) -> (Option<String>, Option<String>) {
(
Some(auth.clone().unwrap_or_else(|| "anonymous".into())),
self.cache_namespace(),
)
}
async fn get_bundle(
&self,
identity: &mut Self::Auth,
context: &mut Self::FetchContext,
) -> Result<CloudConfigBundle, BundleRequestError> {
let Some(request) = context else {
return fetch_bundle(&self.client).await;
};
let credentials = request
.credentials()
.await
.map_err(|error| auth_request_error(error, request.is_recovering()))?;
if credentials.authorization_id.is_none() {
return Err(BundleRequestError::Fatal {
error: auth_failure(),
metric_reason: Some("auth"),
});
}
*identity = credentials.authorization_id;
let client = self
.client
.clone()
.with_bearer_token(credentials.access_token)
.map_err(|_| BundleRequestError::Fatal {
error: auth_failure(),
metric_reason: Some("auth"),
})?;
fetch_bundle(&client).await
}
async fn recover_auth(
&self,
_identity: &mut Self::Auth,
context: &mut Self::FetchContext,
status_code: Option<u16>,
recovery_attempt: usize,
) -> Result<bool, BundleRequestError> {
let Some(auth) = context else {
return Ok(false);
};
if status_code != Some(401) || recovery_attempt != 0 {
return Ok(false);
}
Ok(auth.reject_credentials())
}
}
fn auth_request_error(error: std::io::Error, recovering: bool) -> BundleRequestError {
if error
.get_ref()
.is_some_and(<dyn std::error::Error + Send + Sync>::is::<OAuthSessionError>)
|| matches!(
error.kind(),
std::io::ErrorKind::PermissionDenied
| std::io::ErrorKind::InvalidInput
| std::io::ErrorKind::InvalidData
)
{
BundleRequestError::Fatal {
error: auth_io_error(error),
metric_reason: Some("auth"),
}
} else {
BundleRequestError::Retryable(if recovering {
RetryableFailureKind::AuthRecovery {
status_code: Some(401),
}
} else {
RetryableFailureKind::Request { status_code: None }
})
}
}
fn auth_io_error(error: std::io::Error) -> CloudConfigBundleLoadError {
if error
.get_ref()
.and_then(|source| source.downcast_ref::<OAuthSessionError>())
== Some(&OAuthSessionError::LoginRequired)
{
CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::Auth,
/*status_code*/ None,
"Sign in to the configuration server to load your organization's settings",
)
} else {
auth_failure()
}
}
fn auth_failure() -> CloudConfigBundleLoadError {
CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::Auth,
/*status_code*/ None,
"Could not authenticate with the configuration server",
)
}
#[cfg(test)]
#[path = "config_server_tests.rs"]
mod tests;

View File

@@ -0,0 +1,209 @@
#![cfg(test)]
use super::*;
use crate::bundle_loader::managed_config_bundle_loader_for_service;
use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT;
use crate::service::CloudConfigBundleService;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigServer;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_keyring_store::tests::MockKeyringStore;
use codex_login::test_support::transport_default_auth_route_config;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use tempfile::tempdir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
// HTTP fixtures exercise the same service while production enforces HTTPS at construction.
fn remote_loader(url: String, codex_home: PathBuf) -> CloudConfigBundleLoader {
let factory = transport_default_auth_route_config()
.http_client_factory()
.clone();
let source = ConfigServerSource::new(url, /*oauth*/ None, codex_home.clone(), factory).unwrap();
managed_config_bundle_loader_for_service(CloudConfigBundleService::from_source(
source,
codex_home,
CLOUD_CONFIG_BUNDLE_TIMEOUT,
))
.0
}
fn oauth_config(base_url: &str) -> OAuthSessionConfig {
OAuthSessionConfig {
authorization_url: format!("{base_url}/authorize"),
token_url: format!("{base_url}/token"),
device_authorization_url: None,
client_id: "company-client".into(),
resource: None,
scopes: vec![],
redirect_port: None,
credentials_store: Default::default(),
}
}
#[tokio::test]
async fn a_supplied_chatgpt_token_does_not_replace_config_server_sign_in() {
let server = MockServer::start().await;
let home = tempdir().unwrap();
let endpoint = format!("https://{}", server.address());
let mut config = codex_core::config::ConfigBuilder::default()
.codex_home(home.path().into())
.build()
.await
.unwrap()
.auth_config();
config.chatgpt_base_url = Some(server.uri());
let requirements = codex_config::ConfigRequirementsToml {
config_server: Some(ConfigServer {
base_url: format!("{endpoint}/settings"),
oauth: Some(Box::new(oauth_config(&endpoint))),
}),
..Default::default()
};
let chatgpt = codex_login::CodexAuth::from_external_chatgpt_tokens(
"e30.e30.c2ln",
"endor",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let loader = crate::managed_config_bundle_loader_for_auth(config, &chatgpt, &requirements)
.await
.unwrap();
assert_eq!(loader.config_server(), requirements.config_server.as_ref());
let error = loader.get().await.unwrap_err();
assert_eq!(error.code(), CloudConfigBundleLoadErrorCode::Auth);
assert_eq!(
error.to_string(),
"Sign in to the configuration server to load your organization's settings"
);
assert!(server.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn policy_fetch_uses_replacement_config_server_credentials() {
let server = MockServer::start().await;
let sign_in = AtomicUsize::new(0);
Mock::given(path("/token"))
.respond_with(move |_: &wiremock::Request| {
ResponseTemplate::new(200).set_body_json(json!({
"access_token": format!("account-{}", sign_in.fetch_add(1, Ordering::Relaxed)),
"token_type": "Bearer", "expires_in": 3600,
}))
})
.mount(&server)
.await;
let policies = ["never", "on-request"].map(|approval| {
CloudConfigBundleFixture::enterprise_requirement(format!(
"allowed_approval_policies = ['{approval}']"
))
.into_bundle()
});
for (account, policy) in policies.iter().enumerate() {
Mock::given(path("/settings/codex/config/bundle"))
.and(header("authorization", format!("Bearer account-{account}")))
.respond_with(ResponseTemplate::new(200).set_body_json(policy))
.mount(&server)
.await;
}
let home = tempdir().unwrap();
let factory = transport_default_auth_route_config()
.http_client_factory()
.clone();
let oauth = oauth_config(&server.uri());
let keyring = Arc::new(MockKeyringStore::default());
let manager = || {
OAuthSessionManager::new(
oauth.clone(),
home.path().to_path_buf(),
&factory,
keyring.clone(),
)
.unwrap()
};
let gateway = manager();
gateway
.login_with_browser(std::future::pending(), complete_browser_authorization)
.await
.unwrap();
let source = ConfigServerSource {
cache_namespace: "test".into(),
client: BackendClient::for_config_endpoint(
format!("{}/settings", server.uri()),
factory.clone(),
),
auth: Some(manager().without_interactive_login()),
};
let service = CloudConfigBundleService::from_source(
source,
home.path().to_path_buf(),
CLOUD_CONFIG_BUNDLE_TIMEOUT,
);
assert_eq!(
service.load_startup_bundle_with_timeout().await.unwrap(),
Some(policies[0].clone())
);
gateway
.login_with_browser(std::future::pending(), complete_browser_authorization)
.await
.unwrap();
// The old access token is still valid, so this must detect the changed grant.
assert_eq!(
service.load_startup_bundle_with_timeout().await.unwrap(),
Some(policies[1].clone())
);
}
fn complete_browser_authorization(url: &wiremock::http::Url) {
let query = url
.query_pairs()
.collect::<std::collections::HashMap<_, _>>();
let callback = format!(
"{}?code=browser-authorization-code&state={}",
query["redirect_uri"], query["state"]
);
tokio::spawn(async move {
codex_login::auth::default_client::create_client_without_request_logging()
.get(callback)
.send()
.await
.expect("OAuth callback");
});
}
#[tokio::test]
async fn cached_policy_is_reused_only_for_the_same_endpoint() {
let server = MockServer::start().await;
let home = tempdir().unwrap();
let endpoint = format!("{}/settings", server.uri());
let loader = || remote_loader(endpoint.clone(), home.path().to_path_buf());
let bundle =
CloudConfigBundleFixture::enterprise_requirement("allowed_approval_policies = ['never']")
.into_bundle();
Mock::given(method("GET"))
.and(path("/settings/codex/config/bundle"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(&bundle))
.mount(&server)
.await;
let first = loader();
assert_eq!(first.get().await.unwrap(), Some(bundle.clone()));
drop(first);
server.reset().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(/*s*/ 403))
.mount(&server)
.await;
assert_eq!(loader().get().await.unwrap(), Some(bundle));
let different = remote_loader(
format!("{}/different", server.uri()),
home.path().to_path_buf(),
);
assert_eq!(different.get().await.unwrap_err().status_code(), Some(403));
}

View File

@@ -0,0 +1,43 @@
//! Common interface for fetching managed configuration
use crate::backend::BundleRequestError;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLoadError;
use std::future::Future;
/// Supplies authentication and cache identity to the managed-config service.
/// Cache lookup and fetch must use the same authorization identity.
pub(crate) trait BundleSource: Send + Sync {
type Auth: Send + Sync;
type FetchContext: Send;
/// One context per load or refresh, retained across the service's retries.
fn begin_fetch(&self) -> Self::FetchContext;
/// `None` means this source does not apply, such as an ineligible ChatGPT plan.
/// A required source returns `Some` even when its endpoint is unauthenticated.
fn auth(
&self,
) -> impl Future<Output = Result<Option<Self::Auth>, CloudConfigBundleLoadError>> + Send;
/// Stable subject and authority identifiers; missing values disable cache reads.
fn identity(&self, auth: &Self::Auth) -> (Option<String>, Option<String>);
/// Cache lookups do not call this operation or require a token refresh.
fn get_bundle(
&self,
auth: &mut Self::Auth,
context: &mut Self::FetchContext,
) -> impl Future<Output = Result<CloudConfigBundle, BundleRequestError>> + Send;
/// Recover one unauthorized request. The service retries only when this returns true.
fn recover_auth(
&self,
auth: &mut Self::Auth,
context: &mut Self::FetchContext,
status_code: Option<u16>,
recovery_attempt: usize,
) -> impl Future<Output = Result<bool, BundleRequestError>> + Send;
/// The default preserves the existing ChatGPT cache location.
fn cache_namespace(&self) -> Option<String> {
None
}
}

View File

@@ -0,0 +1,25 @@
//! Cloud-hosted configuration data for Codex.
//!
//! This crate owns transport, caching, and refresh behavior for cloud-delivered
//! config data. Parsing and composition remain in `codex-config`.
mod backend;
mod bundle_loader;
mod cache;
mod chatgpt;
mod config_server;
mod config_source;
mod metrics;
mod service;
mod validation;
pub use bundle_loader::chatgpt_config_bundle_loader;
pub use bundle_loader::chatgpt_config_bundle_loader_for_storage;
pub use bundle_loader::chatgpt_config_bundle_loader_for_storage_without_cache;
pub use bundle_loader::ensure_config_server_login;
pub use bundle_loader::managed_config_auth_manager;
pub use bundle_loader::managed_config_bundle_loader;
pub use bundle_loader::managed_config_bundle_loader_for_auth;
pub use bundle_loader::managed_config_bundle_loader_for_storage;
pub use config_server::config_server_auth_manager;
pub use config_server::config_server_bundle_loader;

View File

@@ -0,0 +1,95 @@
use codex_config::CloudConfigBundle;
const CLOUD_CONFIG_BUNDLE_FETCH_ATTEMPT_METRIC: &str = "codex.cloud_config_bundle.fetch_attempt";
const CLOUD_CONFIG_BUNDLE_FETCH_FINAL_METRIC: &str = "codex.cloud_config_bundle.fetch_final";
const CLOUD_CONFIG_BUNDLE_LOAD_METRIC: &str = "codex.cloud_config_bundle.load";
pub(crate) fn emit_fetch_attempt_metric(
trigger: &str,
attempt: usize,
outcome: &str,
status_code: Option<u16>,
) {
let attempt_tag = attempt.to_string();
let status_code_tag = status_code_tag(status_code);
emit_metric(
CLOUD_CONFIG_BUNDLE_FETCH_ATTEMPT_METRIC,
vec![
("trigger", trigger.to_string()),
("attempt", attempt_tag),
("outcome", outcome.to_string()),
("status_code", status_code_tag),
],
);
}
pub(crate) fn emit_fetch_final_metric(
trigger: &str,
outcome: &str,
reason: &str,
attempt_count: usize,
status_code: Option<u16>,
bundle: Option<&CloudConfigBundle>,
) {
let attempt_count_tag = attempt_count.to_string();
let status_code_tag = status_code_tag(status_code);
emit_metric(
CLOUD_CONFIG_BUNDLE_FETCH_FINAL_METRIC,
vec![
("trigger", trigger.to_string()),
("outcome", outcome.to_string()),
("reason", reason.to_string()),
("attempt_count", attempt_count_tag),
("status_code", status_code_tag),
("bundle_shape", bundle_shape_tag(bundle)),
],
);
}
pub(crate) fn emit_load_metric(trigger: &str, outcome: &str, bundle: Option<&CloudConfigBundle>) {
emit_metric(
CLOUD_CONFIG_BUNDLE_LOAD_METRIC,
vec![
("trigger", trigger.to_string()),
("outcome", outcome.to_string()),
("bundle_shape", bundle_shape_tag(bundle)),
],
);
}
pub(crate) fn bundle_shape_tag(bundle: Option<&CloudConfigBundle>) -> String {
let Some(bundle) = bundle else {
return "none".to_string();
};
let mut sources = Vec::new();
if !bundle.config_toml.enterprise_managed.is_empty() {
sources.push("enterprise_config");
}
if !bundle.requirements_toml.enterprise_managed.is_empty() {
sources.push("enterprise_requirements");
}
if sources.is_empty() {
"empty".to_string()
} else {
sources.sort_unstable();
sources.join(",")
}
}
fn status_code_tag(status_code: Option<u16>) -> String {
status_code
.map(|status_code| status_code.to_string())
.unwrap_or_else(|| "none".to_string())
}
fn emit_metric(metric_name: &str, tags: Vec<(&str, String)>) {
if let Some(metrics) = codex_otel::global() {
let tag_refs = tags
.iter()
.map(|(key, value)| (*key, value.as_str()))
.collect::<Vec<_>>();
let _ = metrics.counter(metric_name, /*inc*/ 1, &tag_refs);
}
}

View File

@@ -0,0 +1,521 @@
//! Cloud config bundle lifecycle orchestration.
//!
//! Startup loads a shared bundle from cache or backend, and background refresh
//! updates both the on-disk cache and the bundle observed by future config loads.
//! One-shot network loads can disable disk-cache reads and writes.
use crate::backend::BundleClient;
use crate::backend::BundleRequestError;
use crate::backend::RetryableFailureKind;
use crate::cache::CacheLoadStatus;
use crate::cache::CloudConfigBundleCache;
use crate::chatgpt::ChatGptSource;
use crate::config_source::BundleSource;
use crate::metrics::emit_fetch_attempt_metric;
use crate::metrics::emit_fetch_final_metric;
use crate::metrics::emit_load_metric;
use crate::validation::validate_bundle;
use codex_async_utils::backoff;
use codex_config::AbsolutePathBuf;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::CloudConfigBundlePolicy;
use codex_config::CloudConfigBundleSnapshot;
use codex_login::AuthManager;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::Mutex;
use tokio::sync::OnceCell;
use tokio::time::sleep;
use tokio::time::timeout;
pub(crate) const CLOUD_CONFIG_BUNDLE_TIMEOUT: Duration = Duration::from_secs(20);
const CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS: usize = 5;
const CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL: Duration = Duration::from_secs(15 * 60);
const CLOUD_CONFIG_BUNDLE_TIMEOUT_RETRY_INTERVAL: Duration = Duration::from_secs(5);
const CLOUD_CONFIG_BUNDLE_LOAD_FAILED_MESSAGE: &str =
"Failed to load cloud config bundle (workspace-managed policies).";
fn optional_bundle(bundle: CloudConfigBundle) -> Option<CloudConfigBundle> {
if bundle.is_empty() {
None
} else {
Some(bundle)
}
}
enum CachedBundleLookup {
Hit(Option<CloudConfigBundle>),
Miss,
}
pub(crate) struct CloudConfigBundleService<S: BundleSource> {
source: S,
cache: CloudConfigBundleCache,
cache_enabled: bool,
codex_home: AbsolutePathBuf,
timeout: Duration,
latest_bundle: OnceCell<Mutex<CloudConfigBundleSnapshot>>,
pub(crate) policy: CloudConfigBundlePolicy,
}
impl<C: BundleClient + 'static> CloudConfigBundleService<ChatGptSource<C>> {
pub(crate) fn new(
auth_manager: Arc<AuthManager>,
client: Arc<C>,
codex_home: PathBuf,
timeout: Duration,
) -> Self {
Self::from_source(
ChatGptSource {
auth_manager,
client,
},
codex_home,
timeout,
)
}
}
impl<S: BundleSource + 'static> CloudConfigBundleService<S> {
pub(crate) fn from_source(source: S, codex_home: PathBuf, timeout: Duration) -> Self {
let codex_home = AbsolutePathBuf::resolve_path_against_base(codex_home, "/");
let cache = match source.cache_namespace() {
Some(namespace) => CloudConfigBundleCache::for_source(codex_home.clone(), &namespace),
None => CloudConfigBundleCache::new(codex_home.clone()),
};
Self {
source,
cache,
cache_enabled: true,
codex_home,
timeout,
latest_bundle: OnceCell::new(),
policy: CloudConfigBundlePolicy::default(),
}
}
pub(crate) fn without_cache(mut self) -> Self {
self.cache_enabled = false;
self
}
pub(crate) async fn get_latest(
&self,
) -> Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError> {
self.get_latest_snapshot().await.bundle
}
pub(crate) async fn get_latest_snapshot(&self) -> CloudConfigBundleSnapshot {
self.latest_snapshot().await.lock().await.clone()
}
async fn latest_snapshot(&self) -> &Mutex<CloudConfigBundleSnapshot> {
self.latest_bundle
.get_or_init(|| async {
let mut snapshot = CloudConfigBundleSnapshot {
config_server: None,
bundle: self.load_startup_bundle_with_timeout().await,
binding: None,
};
self.policy.publish_snapshot(&mut snapshot);
Mutex::new(snapshot)
})
.await
}
pub(crate) async fn load_startup_bundle_with_timeout(
&self,
) -> Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError> {
let _timer =
codex_otel::start_global_timer("codex.cloud_config_bundle.fetch.duration_ms", &[]);
let started_at = Instant::now();
let load_result = timeout(self.timeout, self.load_startup_bundle())
.await
.inspect_err(|_| {
let message = format!(
"Timed out waiting for cloud config bundle after {}s",
self.timeout.as_secs()
);
tracing::error!("{message}");
emit_load_metric("startup", "error", /*bundle*/ None);
})
.map_err(|_| {
CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::Timeout,
/*status_code*/ None,
format!(
"timed out waiting for cloud config bundle after {}s",
self.timeout.as_secs()
),
)
})?;
let result = match load_result {
Ok(result) => result,
Err(err) => {
emit_load_metric("startup", "error", /*bundle*/ None);
return Err(err);
}
};
match result.as_ref() {
Some(bundle) => {
tracing::info!(
elapsed_ms = started_at.elapsed().as_millis(),
config_fragments = bundle.config_toml.enterprise_managed.len(),
requirements_fragments = bundle.requirements_toml.enterprise_managed.len(),
"Cloud config bundle load completed"
);
emit_load_metric("startup", "success", Some(bundle));
}
None => {
tracing::info!(
elapsed_ms = started_at.elapsed().as_millis(),
"Cloud config bundle load completed (none)"
);
emit_load_metric("startup", "success", /*bundle*/ None);
}
}
Ok(result)
}
async fn load_startup_bundle(
&self,
) -> Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError> {
let Some(auth) = self.source.auth().await? else {
return Ok(None);
};
if self.cache_enabled {
// Startup prefers a valid, identity-matched cache entry. The backend is
// only consulted on cache miss or invalid cache contents.
let (chatgpt_user_id, account_id) = self.source.identity(&auth);
match self
.load_valid_cached_bundle(chatgpt_user_id.as_deref(), account_id.as_deref())
.await
{
CachedBundleLookup::Hit(bundle) => return Ok(bundle),
CachedBundleLookup::Miss => {}
}
}
self.fetch_remote_bundle_and_update_cache_with_retries(auth, "startup")
.await
}
async fn load_valid_cached_bundle(
&self,
chatgpt_user_id: Option<&str>,
account_id: Option<&str>,
) -> CachedBundleLookup {
match self.cache.load(chatgpt_user_id, account_id).await {
Ok(signed_payload) => {
if let Err(err) = validate_bundle(&signed_payload.bundle, &self.codex_home) {
tracing::warn!(
path = %self.cache.path().display(),
error = %err,
"Ignoring invalid cached cloud config bundle"
);
self.cache
.log_load_status(&CacheLoadStatus::CacheInvalidBundle);
CachedBundleLookup::Miss
} else {
tracing::info!(
path = %self.cache.path().display(),
"Using cached cloud config bundle"
);
CachedBundleLookup::Hit(optional_bundle(signed_payload.bundle))
}
}
Err(cache_load_status) => {
self.cache.log_load_status(&cache_load_status);
CachedBundleLookup::Miss
}
}
}
async fn fetch_remote_bundle_and_update_cache_with_retries(
&self,
mut auth: S::Auth,
trigger: &'static str,
) -> Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError> {
let mut context = self.source.begin_fetch();
let mut attempt = 1;
let mut last_status_code: Option<u16> = None;
while attempt <= CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS {
match self
.fetch_with_auth_recovery(&mut auth, &mut context, trigger, attempt)
.await
{
Ok(bundle) => {
return self
.validate_and_cache_remote_bundle(&auth, trigger, attempt, bundle)
.await;
}
Err(BundleRequestError::Policy(denied)) => {
return Err(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::RequestFailed,
/*status_code*/ None,
denied.to_string(),
));
}
Err(BundleRequestError::Retryable(status)) => {
last_status_code = status.status_code();
if self
.retry_after_request_failure(trigger, attempt, status)
.await
{
attempt += 1;
continue;
}
}
Err(BundleRequestError::Fatal {
error,
metric_reason,
}) => {
if let Some(reason) = metric_reason {
emit_fetch_final_metric(
trigger,
"error",
reason,
attempt,
error.status_code(),
/*bundle*/ None,
);
}
return Err(error);
}
Err(BundleRequestError::Unauthorized {
status_code,
message,
}) => {
emit_fetch_final_metric(
trigger,
"error",
"auth",
attempt,
status_code,
/*bundle*/ None,
);
return Err(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::Auth,
status_code,
message,
));
}
}
break;
}
emit_fetch_final_metric(
trigger,
"error",
"request_retry_exhausted",
CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS,
last_status_code,
/*bundle*/ None,
);
tracing::error!(
path = %self.cache.path().display(),
"{CLOUD_CONFIG_BUNDLE_LOAD_FAILED_MESSAGE}"
);
Err(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::RequestFailed,
last_status_code,
CLOUD_CONFIG_BUNDLE_LOAD_FAILED_MESSAGE,
))
}
async fn fetch_with_auth_recovery(
&self,
auth: &mut S::Auth,
context: &mut S::FetchContext,
trigger: &'static str,
attempt: usize,
) -> Result<CloudConfigBundle, BundleRequestError> {
let mut recovery_attempt = 0;
loop {
let result = self.source.get_bundle(auth, context).await;
let Err(BundleRequestError::Unauthorized { status_code, .. }) = &result else {
return result;
};
emit_fetch_attempt_metric(trigger, attempt, "unauthorized", *status_code);
if !self
.source
.recover_auth(auth, context, *status_code, recovery_attempt)
.await?
{
return result;
}
recovery_attempt += 1;
}
}
async fn validate_and_cache_remote_bundle(
&self,
auth: &S::Auth,
trigger: &'static str,
attempt: usize,
bundle: CloudConfigBundle,
) -> Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError> {
emit_fetch_attempt_metric(trigger, attempt, "success", /*status_code*/ None);
let revision = self.policy.observe_remote_bundle(&bundle);
if let Err(err) = validate_bundle(&bundle, &self.codex_home) {
emit_fetch_final_metric(
trigger,
"error",
"invalid_bundle",
attempt,
/*status_code*/ None,
/*bundle*/ None,
);
return Err(err);
}
let (chatgpt_user_id, account_id) = self.source.identity(auth);
if self.cache_enabled
&& let Some(revision) = revision
{
let result = match self
.cache
.prepare(chatgpt_user_id, account_id, bundle.clone())
.await
{
Ok(staged) => staged.publish_if_current(revision).await,
Err(err) => Err(err),
};
if let Err(err) = result {
tracing::warn!(error = %err, "Failed to write cloud config bundle cache");
}
}
emit_fetch_final_metric(
trigger,
"success",
"none",
attempt,
/*status_code*/ None,
Some(&bundle),
);
Ok(optional_bundle(bundle))
}
async fn retry_after_request_failure(
&self,
trigger: &'static str,
attempt: usize,
status: RetryableFailureKind,
) -> bool {
let status_code = status.status_code();
if matches!(status, RetryableFailureKind::Request { .. }) {
emit_fetch_attempt_metric(trigger, attempt, "error", status_code);
}
if attempt < CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS {
tracing::warn!(
status = ?status,
attempt,
max_attempts = CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS,
"Failed to fetch cloud config bundle; retrying"
);
sleep(backoff(attempt as u64)).await;
true
} else {
false
}
}
pub(crate) async fn refresh_cache_in_background(&self) {
loop {
let mut refresh_interval = CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL;
if let Some(latest_bundle) = self.latest_bundle.get()
&& matches!(
&latest_bundle.lock().await.bundle,
Err(error) if error.code() == CloudConfigBundleLoadErrorCode::Timeout
)
{
// Recover startup timeouts through this worker without making
// readers fetch concurrently or extending the startup deadline.
refresh_interval = CLOUD_CONFIG_BUNDLE_TIMEOUT_RETRY_INTERVAL;
}
sleep(refresh_interval).await;
match timeout(self.timeout, self.refresh_cache_once()).await {
Ok(true) => {}
Ok(false) => break,
Err(_) => {
tracing::error!(
"Timed out refreshing cloud config bundle cache from remote; keeping existing cache"
);
emit_load_metric("refresh", "error", /*bundle*/ None);
self.publish_refresh_result(Err(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::Timeout,
/*status_code*/ None,
"timed out refreshing cloud config bundle",
)))
.await;
}
}
}
}
async fn refresh_cache_once(&self) -> bool {
let auth = match self.source.auth().await {
Ok(Some(auth)) => auth,
Ok(None) => return false,
Err(error) => {
self.publish_refresh_result(Err(error)).await;
return true;
}
};
match self
.fetch_remote_bundle_and_update_cache_with_retries(auth, "refresh")
.await
{
Ok(bundle) => {
emit_load_metric("refresh", "success", bundle.as_ref());
self.publish_refresh_result(Ok(bundle)).await;
}
Err(err) => {
tracing::error!(
path = %self.cache.path().display(),
error = %err,
"Failed to refresh cloud config bundle cache from remote"
);
emit_load_metric("refresh", "error", /*bundle*/ None);
self.publish_refresh_result(Err(err)).await;
}
}
true
}
async fn publish_refresh_result(
&self,
result: Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError>,
) {
let Some(latest) = self.latest_bundle.get() else {
return;
};
let mut latest = latest.lock().await;
if result.is_ok() {
*latest = CloudConfigBundleSnapshot {
config_server: None,
bundle: result,
binding: None,
};
self.policy.publish_snapshot(&mut latest);
} else if latest.bundle.is_err() {
latest.bundle = result;
latest.binding = None;
}
}
}
#[cfg(test)]
#[path = "service_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
use codex_config::AbsolutePathBuf;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLayers;
use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::compose_requirements;
use codex_config::config_toml::validate_model_providers;
pub(crate) fn validate_bundle(
bundle: &CloudConfigBundle,
base_dir: &AbsolutePathBuf,
) -> Result<(), CloudConfigBundleLoadError> {
let bundle_layers =
CloudConfigBundleLayers::from_bundle(bundle.clone(), base_dir).map_err(|_| {
CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::InvalidBundle,
/*status_code*/ None,
"invalid cloud config bundle: invalid TOML",
)
})?;
let CloudConfigBundleLayers {
enterprise_managed_config: _,
enterprise_managed_requirements,
} = bundle_layers;
let requirements = compose_requirements(enterprise_managed_requirements).map_err(|_| {
CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::InvalidBundle,
/*status_code*/ None,
"invalid cloud config bundle: invalid requirements",
)
})?;
if let Some(providers) = requirements.and_then(|requirements| requirements.model_providers) {
validate_model_providers(&providers).map_err(|_| {
CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::InvalidBundle,
/*status_code*/ None,
"invalid cloud config bundle: invalid model provider configuration",
)
})?;
}
Ok(())
}
#[cfg(test)]
#[path = "validation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,78 @@
use super::*;
use codex_config::CloudRequirementsFragment;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[test]
fn cloud_validation_rejects_mixed_network_requirements() {
let home = tempdir().expect("tempdir");
let base_dir = AbsolutePathBuf::from_absolute_path(home.path()).expect("absolute path");
let mut bundle = CloudConfigBundle::default();
for alias in ["experimental_network", "network_proxy"] {
let nested = "[permissions.network]\nenabled = false";
let top_level = format!("[{alias}]\nenabled = false");
for contents in [
vec![format!("{nested}\n{top_level}")],
vec![nested.to_owned(), top_level],
] {
bundle.requirements_toml.enterprise_managed = contents
.into_iter()
.enumerate()
.map(|(index, contents)| CloudRequirementsFragment {
id: index.to_string(),
name: index.to_string(),
contents,
})
.collect();
let err = validate_bundle(&bundle, &base_dir).expect_err("mixed policy spellings");
assert_eq!(err.code(), CloudConfigBundleLoadErrorCode::InvalidBundle);
}
}
}
#[test]
fn cloud_fragments_combine_before_provider_validation() {
let home = tempdir().expect("tempdir");
let base_dir = AbsolutePathBuf::from_absolute_path(home.path()).expect("absolute path");
let mut bundle = CloudConfigBundle::default();
// Cloud fragments arrive highest-priority first.
bundle.requirements_toml.enterprise_managed = vec![
CloudRequirementsFragment {
id: "high".to_string(),
name: "URL".to_string(),
contents: "[model_providers.gateway]\nbase_url = 'https://gateway.example/v1'\n[model_providers.gateway.auth]\ntimeout_ms = 10000\ncwd = 'auth'"
.to_string(),
},
CloudRequirementsFragment {
id: "low".to_string(),
name: "Name".to_string(),
contents: "[model_providers.gateway]\nname = 'Gateway'\n[model_providers.gateway.auth]\ncommand = 'get-token'".to_string(),
},
];
assert_eq!(validate_bundle(&bundle, &base_dir), Ok(()));
}
#[test]
fn cloud_bedrock_overrides_accept_supported_fields() {
let home = tempdir().expect("tempdir");
let base_dir = AbsolutePathBuf::from_absolute_path(home.path()).expect("absolute path");
for provider in ["amazon-bedrock", "amazon-bedrock-runtime"] {
let mut bundle = CloudConfigBundle::default();
bundle.requirements_toml.enterprise_managed = vec![CloudRequirementsFragment {
id: "bedrock".to_string(),
name: "Bedrock".to_string(),
contents: format!(
r#"
[model_providers.{provider}]
base_url = "https://bedrock.example"
[model_providers.{provider}.http_headers]
X-Managed = "required"
[model_providers.{provider}.aws]
profile = "managed"
region = "us-east-1"
"#
),
}];
assert_eq!(validate_bundle(&bundle, &base_dir), Ok(()));
}
}