aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT

- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser,
  device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity,
  runtime agent instance, backend-client e openapi-models, workspace routing.
- Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin
  remoti (catalogo, sync, share), cyber access program, daybreak, cloud config
  e requirements (config_server ora fail-closed), attestation, frozen cloud
  skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/
  routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime.
- Messaggi d'errore senza link a chatgpt.com.
- Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed.
- Test: cancellati solo quelli del codice rimosso; test di sicurezza
  (sandbox estensioni, permessi, redazione, auth storage, requirements)
  adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents).
- Istruzioni di sistema invariate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -206,7 +206,6 @@ pub(super) async fn resolve_provider_auth(
BedrockAuthMethod::ManagedBearerToken { token, .. }
| BedrockAuthMethod::EnvBearerToken { token, .. } => Ok(Arc::new(BearerAuthProvider {
token: Some(token),
account_id: None,
is_fedramp_account: false,
})),
BedrockAuthMethod::AwsSdkAuth { context } => {
@@ -510,7 +509,6 @@ mod tests {
.expect("configured region should resolve");
let provider = BearerAuthProvider {
token: Some(token),
account_id: None,
is_fedramp_account: false,
};
let mut headers = http::HeaderMap::new();

View File

@@ -184,7 +184,7 @@ impl AmazonBedrockModelProvider {
async fn api_provider(&self) -> Result<Provider> {
let mut api_provider_info = self.info.clone();
api_provider_info.base_url = self.runtime_base_url().await?;
api_provider_info.to_api_provider(/*auth_mode*/ None)
api_provider_info.to_api_provider()
}
async fn runtime_base_url(&self) -> Result<Option<String>> {
@@ -280,7 +280,6 @@ impl ModelProvider for AmazonBedrockModelProvider {
fn capabilities(&self) -> ProviderCapabilities {
ProviderCapabilities {
reasoning_summaries: true,
image_generation: false,
web_search: self.endpoint == BedrockEndpoint::Mantle,
external_web_access: false,
remote_compaction: RemoteCompactionSupport::V2,
@@ -491,7 +490,7 @@ mod tests {
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None);
api_provider_info.base_url = Some(mantle::base_url(region).expect("supported region"));
let api_provider = api_provider_info
.to_api_provider(/*auth_mode*/ None)
.to_api_provider()
.expect("api provider should build");
assert_eq!(
@@ -690,7 +689,7 @@ mod tests {
}
#[test]
fn capabilities_enable_web_search_but_disable_image_generation() {
fn capabilities_enable_web_search() {
let provider = AmazonBedrockModelProvider::new(
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
/*auth_manager*/ None,
@@ -700,7 +699,6 @@ mod tests {
provider.capabilities(),
ProviderCapabilities {
reasoning_summaries: true,
image_generation: false,
web_search: true,
external_web_access: false,
remote_compaction: RemoteCompactionSupport::V2,
@@ -719,7 +717,6 @@ mod tests {
provider.capabilities(),
ProviderCapabilities {
reasoning_summaries: true,
image_generation: false,
web_search: false,
external_web_access: false,
remote_compaction: RemoteCompactionSupport::V2,

View File

@@ -1,87 +1,41 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use codex_agent_identity::AgentIdentityKey;
use codex_agent_identity::authorization_header_for_agent_task;
use codex_api::AgentIdentityTelemetry;
use codex_api::AuthError;
use codex_api::AuthHeadersFuture;
use codex_api::AuthProvider;
use codex_api::SharedAuthProvider;
use codex_features::RuntimeAuthMode;
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use codex_login::AuthHeaders;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::auth::AgentIdentityAuth;
use codex_login::auth::AgentIdentityAuthError;
use codex_login::auth::AgentIdentityAuthPolicy;
use codex_model_provider_info::ModelProviderInfo;
use codex_protocol::error::CodexErr;
use codex_protocol::protocol::SessionSource;
use codex_runtime_agent_instance::RuntimeAuth;
use codex_runtime_agent_instance::RuntimeAuthError;
use codex_runtime_agent_instance::RuntimeAuthManager;
use http::HeaderMap;
use http::HeaderValue;
use crate::bearer_auth_provider::BearerAuthProvider;
const BEDROCK_API_KEY_UNSUPPORTED_MESSAGE: &str =
"Bedrock API key auth is only supported by the Amazon Bedrock model provider";
/// Credential ownership and optional OpenAI runtime auth for one harness/thread context.
/// Publish these together so auxiliary clients cannot select another thread's credentials.
/// Credential ownership for one harness/thread context.
/// Publish this so auxiliary clients cannot select another thread's credentials.
#[derive(Clone, Debug)]
pub struct ProviderAuthContext {
pub credentials: Arc<AuthManager>,
pub runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
}
impl ProviderAuthContext {
pub fn model_provider(&self, info: ModelProviderInfo) -> crate::SharedModelProvider {
crate::provider::create_model_provider_with_runtime(
info,
Some(Arc::clone(&self.credentials)),
self.runtime_auth.clone(),
)
crate::create_model_provider(info, Some(Arc::clone(&self.credentials)))
}
}
#[derive(Clone, Debug)]
pub struct ProviderAuthScope {
pub agent_identity_policy: AgentIdentityAuthPolicy,
pub session_source: SessionSource,
pub agent_identity_session_fallback: AgentIdentitySessionFallback,
}
#[derive(Clone, Debug, Default)]
pub struct AgentIdentitySessionFallback {
engaged: Arc<AtomicBool>,
}
impl AgentIdentitySessionFallback {
pub fn is_engaged(&self) -> bool {
self.engaged.load(Ordering::Relaxed)
}
fn engage(&self) -> bool {
!self.engaged.swap(true, Ordering::Relaxed)
}
}
/// Provider auth resolved for a request, plus metadata describing the effective auth.
/// Provider auth resolved for a request, plus the credential that produced it.
#[derive(Clone)]
pub struct ResolvedProviderAuth {
/// Login selected with these headers; routing must use the same credential.
pub credential: Option<CodexAuth>,
pub auth: SharedAuthProvider,
pub agent_identity_telemetry: Option<AgentIdentityTelemetry>,
pub runtime: Option<RuntimeAuth>,
}
impl ResolvedProviderAuth {
@@ -89,107 +43,8 @@ impl ResolvedProviderAuth {
Self {
credential: None,
auth,
agent_identity_telemetry: None,
runtime: None,
}
}
pub(crate) fn for_runtime(selected: RuntimeAuth, mode: RuntimeAuthMode) -> Self {
Self {
credential: Some(selected.auth().clone()),
auth: selected.clone().into_auth_provider(mode),
agent_identity_telemetry: None,
runtime: Some(selected),
}
}
/// Preserve the caller's transport configuration and bind it to the selected login.
pub fn bind_http_client_factory(
&self,
factory: HttpClientFactory,
) -> Result<HttpClientFactory, AuthError> {
match &self.runtime {
Some(runtime) => runtime.bind_http_client_factory(factory),
None => Ok(factory),
}
}
/// Preserve the caller's connection pool and bind it to the selected login.
pub fn bind_http_client_pool(
&self,
pool: &RouteAwareClientPool,
) -> Result<RouteAwareClientPool, AuthError> {
match &self.runtime {
Some(runtime) => pool
.with_account_binding(runtime.http_client_factory().network_policy())
.ok_or_else(|| {
AuthError::Build(
"runtime credentials and transport must share the application network policy"
.to_string(),
)
}),
None => Ok(pool.clone()),
}
}
/// Reject account selectors that disagree with the selected runtime.
pub fn validate_headers(&self, headers: &HeaderMap) -> codex_protocol::error::Result<()> {
if let Some(runtime) = &self.runtime {
crate::validate_runtime_selectors(headers, runtime.runtime().actor().info())?;
}
Ok(())
}
fn for_agent_identity(auth: AgentIdentityAuth) -> Self {
let agent_identity_telemetry = agent_identity_telemetry(&auth);
Self {
credential: None,
auth: Arc::new(AgentIdentityAuthProvider { auth }),
agent_identity_telemetry: Some(agent_identity_telemetry),
runtime: None,
}
}
}
pub(crate) fn agent_identity_telemetry(auth: &AgentIdentityAuth) -> AgentIdentityTelemetry {
AgentIdentityTelemetry {
agent_id: auth.record().agent_runtime_id.clone(),
task_id: auth.run_task_id().to_string(),
}
}
#[derive(Clone, Debug)]
struct AgentIdentityAuthProvider {
auth: AgentIdentityAuth,
}
impl AuthProvider for AgentIdentityAuthProvider {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
let record = self.auth.record();
let header_value = authorization_header_for_agent_task(
AgentIdentityKey {
agent_runtime_id: &record.agent_runtime_id,
private_key_pkcs8_base64: &record.agent_private_key,
},
self.auth.run_task_id(),
)
.map_err(std::io::Error::other);
if let Ok(header_value) = header_value
&& let Ok(header) = HeaderValue::from_str(&header_value)
{
let _ = headers.insert(http::header::AUTHORIZATION, header);
}
if let Ok(header) = HeaderValue::from_str(self.auth.account_id()) {
let _ = headers.insert(CHATGPT_ACCOUNT_ID_HEADER, header);
}
if self.auth.is_fedramp_account() {
let _ = headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
}
Ok(())
}
}
#[derive(Clone, Debug)]
@@ -206,17 +61,14 @@ impl AuthProvider for HeaderAuthProvider {
struct AuthManagerAuthProvider {
auth_manager: Arc<AuthManager>,
// Startup auth is only the account-scoped identity anchor. Request
// headers always come from the current AuthManager snapshot below.
// Startup auth only anchors the credential kind. Request headers always
// come from the current AuthManager snapshot below.
expected_auth: CodexAuth,
}
impl AuthManagerAuthProvider {
fn is_expected_auth(&self, auth: &CodexAuth) -> bool {
auth.uses_codex_backend()
&& auth.get_account_id() == self.expected_auth.get_account_id()
&& auth.get_chatgpt_user_id() == self.expected_auth.get_chatgpt_user_id()
&& auth.is_workspace_account() == self.expected_auth.is_workspace_account()
auth.auth_mode() == self.expected_auth.auth_mode()
}
fn current_auth(&self) -> Option<CodexAuth> {
@@ -296,7 +148,7 @@ impl AuthProvider for AuthManagerAuthProvider {
}
// Some providers are meant to send no auth headers. Examples include local OSS
// providers and custom test providers with `requires_openai_auth = false`.
// providers and custom providers that do not use the stored API key.
#[derive(Clone, Debug)]
struct UnauthenticatedAuthProvider;
@@ -367,74 +219,6 @@ pub(crate) fn resolve_provider_auth(
})
}
pub(crate) async fn resolve_provider_auth_for_scope(
auth_manager: Option<Arc<AuthManager>>,
auth: Option<&CodexAuth>,
provider: &ModelProviderInfo,
scope: ProviderAuthScope,
) -> codex_protocol::error::Result<ResolvedProviderAuth> {
let ProviderAuthScope {
agent_identity_policy,
session_source,
agent_identity_session_fallback,
} = scope;
if let Some(CodexAuth::AgentIdentity(agent_identity_auth)) = auth {
return Ok(ResolvedProviderAuth::for_agent_identity(
agent_identity_auth.clone(),
));
}
if !should_bootstrap_chatgpt_agent_identity(agent_identity_policy, auth)
|| agent_identity_session_fallback.is_engaged()
{
return resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new);
}
let Some(auth_manager) = auth_manager else {
return resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new);
};
match auth_manager
.agent_identity_auth(agent_identity_policy, session_source)
.await
{
Ok(Some(agent_identity_auth)) => Ok(ResolvedProviderAuth::for_agent_identity(
agent_identity_auth,
)),
Ok(None) => resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new),
Err(err) => {
if let Some(AgentIdentityAuthError::BootstrapUnavailable {
operation,
attempts,
message,
}) = err
.get_ref()
.and_then(|source| source.downcast_ref::<AgentIdentityAuthError>())
{
let newly_engaged = agent_identity_session_fallback.engage();
tracing::warn!(
operation,
attempts = *attempts,
error = %message,
newly_engaged,
"agent identity bootstrap unavailable; using ChatGPT bearer auth for this session"
);
resolve_provider_auth(auth, provider).map(ResolvedProviderAuth::new)
} else {
Err(err.into())
}
}
}
}
fn should_bootstrap_chatgpt_agent_identity(
agent_identity_policy: AgentIdentityAuthPolicy,
auth: Option<&CodexAuth>,
) -> bool {
agent_identity_policy == AgentIdentityAuthPolicy::ChatGptAuth
&& matches!(auth, Some(CodexAuth::Chatgpt(_)))
}
pub(crate) fn bearer_auth_for_provider(
provider: &ModelProviderInfo,
) -> codex_protocol::error::Result<Option<BearerAuthProvider>> {
@@ -466,86 +250,29 @@ pub(crate) fn uses_fedramp_api_key(
&& auth.is_some_and(CodexAuth::is_fedramp_account))
}
/// Select the shared runtime without changing the identity of captured request data.
pub async fn auth_provider_for_request(
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
headers: &HeaderMap,
) -> Result<ResolvedProviderAuth, RuntimeAuthError> {
observe_auth_selection(runtime.map(|(_, mode)| *mode), "request", async {
match runtime {
Some((manager, mode)) => {
let manager = Arc::clone(manager);
let auth = auth.clone();
let selection = crate::runtime_auth::resource_selection(headers)?;
let selected = crate::runtime_auth::finish_runtime_selection(async move {
manager.auth_for(&auth, &selection).await
})
.await?;
Ok(ResolvedProviderAuth::for_runtime(selected, *mode))
}
None => {
let mut resolved = ResolvedProviderAuth::new(auth_provider_from_auth(auth));
resolved.credential = Some(auth.clone());
Ok(resolved)
}
}
})
.await
/// Builds request auth for an already selected credential.
pub fn auth_provider_for_request(auth: &CodexAuth) -> ResolvedProviderAuth {
let mut resolved = ResolvedProviderAuth::new(auth_provider_from_auth(auth));
resolved.credential = Some(auth.clone());
resolved
}
/// Record bounded auth-mode and outcome labels without changing the selection result.
pub(crate) async fn observe_auth_selection<T, E>(
mode: Option<RuntimeAuthMode>,
operation: &'static str,
selection: impl Future<Output = Result<T, E>>,
) -> Result<T, E> {
let started = std::time::Instant::now();
let result = selection.await;
let mode = match mode {
None => "ordinary",
Some(RuntimeAuthMode::DualHeader) => "dual_header",
Some(RuntimeAuthMode::AssertionOnly) => "assertion_only",
};
let _ = codex_otel::record_global_operation(
"codex.auth.selection",
"codex.auth.selection.duration",
started.elapsed(),
&[
("mode", mode),
("operation", operation),
("outcome", if result.is_ok() { "success" } else { "error" }),
],
);
result
}
/// Builds request-header auth for a first-party Codex credential.
/// Builds request-header auth for a stored or host-supplied credential.
pub fn auth_provider_from_auth(auth: &CodexAuth) -> SharedAuthProvider {
match auth {
CodexAuth::AgentIdentity(auth) => {
Arc::new(AgentIdentityAuthProvider { auth: auth.clone() })
}
CodexAuth::Headers(auth) => Arc::new(HeaderAuthProvider { auth: auth.clone() }),
CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_) => {
unreachable!("{BEDROCK_API_KEY_UNSUPPORTED_MESSAGE}")
}
CodexAuth::ApiKey(_)
| CodexAuth::Chatgpt(_)
| CodexAuth::ChatgptAuthTokens(_)
| CodexAuth::PersonalAccessToken(_) => Arc::new(BearerAuthProvider {
CodexAuth::ApiKey(_) => Arc::new(BearerAuthProvider {
token: auth.get_token().ok(),
account_id: auth.get_account_id(),
is_fedramp_account: auth.is_fedramp_account(),
}),
}
}
/// Builds request-header auth that reads the current managed auth snapshot on
/// every request while remaining scoped to the expected auth identity.
///
/// Callers with account-scoped state should pass the same snapshot that keyed
/// that state so a later account switch cannot reuse it.
/// every request while remaining scoped to the expected credential kind.
pub fn auth_provider_from_auth_manager(
auth_manager: Arc<AuthManager>,
expected_auth: &CodexAuth,

View File

@@ -1,9 +1,7 @@
//! Verifies that concurrent proactive and unauthorized requests share one OAuth refresh.
//! Verifies that concurrent unauthorized requests share one external-auth refresh.
use super::auth_provider_from_auth_manager;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthHeaders;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::ExternalAuth;
@@ -13,29 +11,11 @@ use codex_login::auth::RefreshTokenFailedReason;
use http::HeaderMap;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::task::Poll;
use tempfile::TempDir;
use tokio::sync::Barrier;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn concurrent_and_late_rejections_share_one_refresh() {
check_concurrent_refresh(RefreshTrigger::Unauthorized).await;
}
#[tokio::test]
async fn concurrent_proactive_requests_share_one_refresh() {
check_concurrent_refresh(RefreshTrigger::Proactive).await;
}
struct RotatingExternalAuth {
refreshes: AtomicUsize,
@@ -105,159 +85,3 @@ async fn concurrent_external_rejections_share_one_refresh() {
"Bearer replacement"
);
}
#[derive(Clone, Copy)]
enum RefreshTrigger {
Unauthorized,
Proactive,
}
async fn check_concurrent_refresh(trigger: RefreshTrigger) {
let server = MockServer::start().await;
let home = TempDir::new().unwrap();
let auth = json!({
"tokens": {
"id_token": "e30.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoib3JpZ2luYWwtdXNlciIsImNoYXRncHRfYWNjb3VudF9pZCI6Im9yaWdpbmFsLWFjY291bnQifX0.sig",
"access_token": "initial-token",
"refresh_token": "initial-refresh-token",
"account_id": "original-account",
"oauth_provenance": {
"issuer": server.uri(),
"client_id": "concurrent-refresh-test"
}
},
"last_refresh": match trigger {
RefreshTrigger::Unauthorized => "2099-01-01T00:00:00Z",
RefreshTrigger::Proactive => "2000-01-01T00:00:00Z",
}
});
std::fs::write(
home.path().join("auth.json"),
serde_json::to_vec(&auth).unwrap(),
)
.unwrap();
let manager = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::default(),
codex_login::test_support::transport_default_auth_route_config(),
)
.await,
);
let provider =
auth_provider_from_auth_manager(manager.clone(), &manager.auth_cached().unwrap());
let rejected_headers = provider.to_auth_headers().unwrap();
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_partial_json(
json!({"refresh_token": "initial-refresh-token"}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "replacement-token",
"refresh_token": "replacement-refresh-token"
})))
.expect(1)
.mount(&server)
.await;
// A redundant refresh could permanently fail even though the replacement works.
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_partial_json(
json!({"refresh_token": "replacement-refresh-token"}),
))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"error": "invalid_grant",
})))
.with_priority(10)
.expect(0)
.mount(&server)
.await;
let refresh = || async {
match trigger {
RefreshTrigger::Unauthorized => {
provider
.refresh_after_unauthorized(rejected_headers.clone())
.await
}
RefreshTrigger::Proactive => {
let headers = provider.apply_auth_headers(HeaderMap::new()).await.unwrap();
assert_eq!(
headers[http::header::AUTHORIZATION],
"Bearer replacement-token"
);
true
}
}
};
let mut first = Box::pin(refresh());
let mut second = Box::pin(refresh());
let mut third = Box::pin(refresh());
// Queue both waiters before the runtime can service the first OAuth request.
std::future::poll_fn(|cx| {
assert!(first.as_mut().poll(cx).is_pending());
assert!(second.as_mut().poll(cx).is_pending());
assert!(third.as_mut().poll(cx).is_pending());
Poll::Ready(())
})
.await;
assert_eq!(tokio::join!(first, second, third), (true, true, true));
// A delayed 401 for the old token also reuses the completed refresh.
assert!(
provider
.refresh_after_unauthorized(rejected_headers.clone())
.await
);
let updated_headers = provider.apply_auth_headers(HeaderMap::new()).await.unwrap();
assert_eq!(
updated_headers[http::header::AUTHORIZATION],
"Bearer replacement-token"
);
// A rejection of the new credential must still be able to refresh again.
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_partial_json(
json!({"refresh_token": "replacement-refresh-token"}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "next-token",
"refresh_token": "next-refresh-token"
})))
.expect(1)
.mount(&server)
.await;
assert!(provider.refresh_after_unauthorized(updated_headers).await);
assert_eq!(
provider.apply_auth_headers(HeaderMap::new()).await.unwrap()[http::header::AUTHORIZATION],
"Bearer next-token"
);
// A permanent failure must not prevent a later guarded reload of fresh credentials.
let rejected = provider.to_auth_headers().unwrap();
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_partial_json(
json!({"refresh_token": "next-refresh-token"}),
))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"})))
.expect(1)
.mount(&server)
.await;
assert!(!provider.refresh_after_unauthorized(rejected.clone()).await);
let path = home.path().join("auth.json");
let mut stored: serde_json::Value =
serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
stored["tokens"]["access_token"] = json!("reloaded-token");
std::fs::write(path, serde_json::to_vec(&stored).unwrap()).unwrap();
assert!(provider.refresh_after_unauthorized(rejected).await);
assert_eq!(
provider.to_auth_headers().unwrap()[http::header::AUTHORIZATION],
"Bearer reloaded-token"
);
server.verify().await;
}

View File

@@ -1,70 +1,32 @@
//! Unit tests for the auth module.
use codex_agent_identity::generate_agent_key_material;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthDotJson;
use codex_login::AuthKeyringBackendKind;
use codex_login::auth::AgentIdentityAuthRecord;
use codex_login::auth::BedrockApiKeyAuth;
use codex_login::auth::login_with_chatgpt_auth_tokens;
use codex_login::save_auth;
use codex_model_provider_info::WireApi;
use codex_model_provider_info::create_oss_provider_with_base_url;
use codex_protocol::account::PlanType;
use codex_protocol::auth::AuthMode;
use codex_protocol::config_types::ModelProviderAuthInfo;
use codex_protocol::error::CodexErrorDetails;
use http::HeaderValue;
use http::header::AUTHORIZATION;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::num::NonZeroU64;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
static NEXT_CODEX_HOME_ID: AtomicUsize = AtomicUsize::new(0);
const TEST_CHATGPT_ID_TOKEN: &str = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaHR0cHM6Ly9hcGkub3BlbmFpLmNvbS9hdXRoIjp7ImNoYXRncHRfdXNlcl9pZCI6InVzZXItMTIzNDUiLCJ1c2VyX2lkIjoidXNlci0xMjM0NSIsImNoYXRncHRfcGxhbl90eXBlIjoicHJvIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoiYWNjb3VudC0xMjMifX0.c2ln";
async fn agent_identity_auth(chatgpt_account_is_fedramp: bool) -> AgentIdentityAuth {
let key_material = generate_agent_key_material().expect("generate key material");
AgentIdentityAuth::from_record(
AgentIdentityAuthRecord {
agent_runtime_id: "agent-runtime-1".to_string(),
agent_private_key: key_material.private_key_pkcs8_base64,
account_id: "account-1".to_string(),
chatgpt_user_id: "user-1".to_string(),
email: Some("agent@example.com".to_string()),
plan_type: PlanType::Plus,
chatgpt_account_is_fedramp,
task_id: Some("task-run-1".to_string()),
},
"https://auth.openai.com/api/accounts",
&codex_login::test_support::transport_default_auth_route_config(),
)
.await
.expect("agent identity auth record should include task id")
}
fn provider_auth_scope(
policy: AgentIdentityAuthPolicy,
fallback: AgentIdentitySessionFallback,
) -> ProviderAuthScope {
ProviderAuthScope {
agent_identity_policy: policy,
session_source: SessionSource::Cli,
agent_identity_session_fallback: fallback,
}
}
fn test_codex_home() -> PathBuf {
let id = NEXT_CODEX_HOME_ID.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"codex-model-provider-agent-identity-{pid}-{id}",
"codex-model-provider-auth-{pid}-{id}",
pid = std::process::id()
));
let _ = std::fs::remove_dir_all(&path);
@@ -72,59 +34,23 @@ fn test_codex_home() -> PathBuf {
path
}
fn write_chatgpt_auth_json(codex_home: &Path) {
let auth_json = json!({
"tokens": {
"id_token": TEST_CHATGPT_ID_TOKEN,
"access_token": "test-access-token",
"refresh_token": "test-refresh-token",
"account_id": "account-123"
},
"last_refresh": "2099-01-01T00:00:00Z"
});
std::fs::write(
codex_home.join("auth.json"),
serde_json::to_string_pretty(&auth_json).expect("serialize auth.json"),
)
.expect("write auth.json");
}
async fn chatgpt_auth_manager(
agent_identity_authapi_base_url: String,
) -> (PathBuf, Arc<AuthManager>, CodexAuth) {
let codex_home = test_codex_home();
write_chatgpt_auth_json(&codex_home);
let auth_manager = AuthManager::shared(
codex_home.clone(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
fn save_ephemeral_auth(codex_home: &Path, auth: AuthDotJson) {
save_auth(
codex_home,
&auth,
AuthCredentialsStoreMode::Ephemeral,
AuthKeyringBackendKind::default(),
codex_login::test_support::transport_default_auth_route_config(),
)
.await;
let auth = auth_manager.auth().await.expect("auth should load");
let auth_manager = AuthManager::from_auth_for_testing_with_agent_identity_authapi_base_url(
auth.clone(),
agent_identity_authapi_base_url,
);
(codex_home, auth_manager, auth)
.expect("save ephemeral auth");
}
async fn mount_transient_agent_registration(
server: &MockServer,
status: u16,
registration_count: Arc<AtomicUsize>,
) {
Mock::given(method("POST"))
.and(path("/v1/agent/register"))
.respond_with(move |_request: &wiremock::Request| {
registration_count.fetch_add(1, Ordering::SeqCst);
ResponseTemplate::new(status)
})
.mount(server)
.await;
fn api_key_auth_json(api_key: &str) -> AuthDotJson {
AuthDotJson {
auth_mode: Some(AuthMode::ApiKey),
openai_api_key: Some(api_key.to_string()),
bedrock_api_key: None,
bedrock_access_keys: None,
}
}
#[test]
@@ -311,22 +237,14 @@ fn openai_provider_rejects_bedrock_api_key_auth() {
}
#[tokio::test]
async fn auth_manager_provider_follows_refreshes_but_not_account_switches() {
async fn auth_manager_provider_follows_reloads_but_not_credential_kind_switches() {
let codex_home = test_codex_home();
login_with_chatgpt_auth_tokens(
&codex_home,
"header.e30.first",
"test-account",
/*chatgpt_plan_type*/ None,
)
.expect("save initial auth");
save_ephemeral_auth(&codex_home, api_key_auth_json("first-key"));
let auth_manager = Arc::new(
AuthManager::new(
codex_home.clone(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::Ephemeral,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::default(),
codex_login::test_support::transport_default_auth_route_config(),
)
@@ -343,18 +261,12 @@ async fn auth_manager_provider_follows_refreshes_but_not_account_switches() {
assert_eq!(
provider.to_auth_headers().unwrap().get(AUTHORIZATION),
Some(&HeaderValue::from_static("Bearer header.e30.first"))
Some(&HeaderValue::from_static("Bearer first-key"))
);
login_with_chatgpt_auth_tokens(
&codex_home,
"header.e30.reloaded",
"test-account",
/*chatgpt_plan_type*/ None,
)
.expect("save reloaded auth");
save_ephemeral_auth(&codex_home, api_key_auth_json("reloaded-key"));
// Ordinary requests retain the manager's cache until refresh or recovery runs.
// Ordinary requests retain the manager's cache until a reload runs.
assert_eq!(
provider
.apply_auth_headers(HeaderMap::new())
@@ -362,30 +274,31 @@ async fn auth_manager_provider_follows_refreshes_but_not_account_switches() {
.expect("cached auth headers"),
initial_headers
);
assert_eq!(
tokio::join!(
provider.refresh_after_unauthorized(initial_headers.clone()),
provider.refresh_after_unauthorized(initial_headers),
),
(true, true)
);
// Stored API keys cannot be refreshed after a 401.
assert!(!provider.refresh_after_unauthorized(initial_headers).await);
auth_manager.reload().await;
let resolved_headers = provider
.apply_auth_headers(HeaderMap::new())
.await
.expect("managed auth headers should resolve");
assert_eq!(
resolved_headers.get(AUTHORIZATION),
Some(&HeaderValue::from_static("Bearer header.e30.reloaded"))
Some(&HeaderValue::from_static("Bearer reloaded-key"))
);
login_with_chatgpt_auth_tokens(
save_ephemeral_auth(
&codex_home,
"header.e30.other-account",
"other-account",
/*chatgpt_plan_type*/ None,
)
.expect("save switched-account auth");
AuthDotJson {
auth_mode: Some(AuthMode::BedrockApiKey),
openai_api_key: None,
bedrock_api_key: Some(BedrockApiKeyAuth {
api_key: "bedrock-api-key-test".to_string(),
region: "us-east-1".to_string(),
}),
bedrock_access_keys: None,
},
);
assert!(!provider.refresh_after_unauthorized(resolved_headers).await);
auth_manager.reload().await;
@@ -443,6 +356,13 @@ impl codex_login::ExternalAuth for FailingRefreshAuth {
}
}
fn header_auth(authorization: &'static str) -> CodexAuth {
CodexAuth::Headers(AuthHeaders::new(HeaderMap::from_iter([(
AUTHORIZATION,
HeaderValue::from_static(authorization),
)])))
}
#[tokio::test]
async fn failed_refresh_retries_only_with_newer_credentials() {
for failure in [
@@ -450,18 +370,14 @@ async fn failed_refresh_retries_only_with_newer_credentials() {
RefreshFailure::Permanent,
RefreshFailure::Policy,
] {
for (token, account, changed) in [
("Bearer old", "account", false),
("Bearer new", "account", true),
("Bearer new", "other-account", false),
for (replacement, changed) in [
(header_auth("Bearer old"), false),
(header_auth("Bearer new"), true),
// A different credential kind is never adopted by an existing request.
(CodexAuth::from_api_key("new-api-key"), false),
] {
let initial = CodexAuth::Headers(AuthHeaders::new(HeaderMap::from_iter([
(AUTHORIZATION, HeaderValue::from_static("Bearer old")),
(
http::HeaderName::from_static("chatgpt-account-id"),
HeaderValue::from_static("account"),
),
])));
let initial = header_auth("Bearer old");
let unchanged = replacement == initial;
let (updates, auth) = tokio::sync::watch::channel(initial.clone());
let external = Arc::new(FailingRefreshAuth {
auth,
@@ -475,199 +391,16 @@ async fn failed_refresh_retries_only_with_newer_credentials() {
let recovery = provider.refresh_after_unauthorized(rejected);
let concurrent_update = async {
external.barrier.wait().await;
updates.send_replace(CodexAuth::Headers(AuthHeaders::new(HeaderMap::from_iter(
[
(AUTHORIZATION, HeaderValue::from_static(token)),
(
http::HeaderName::from_static("chatgpt-account-id"),
HeaderValue::from_static(account),
),
],
))));
updates.send_replace(replacement);
manager.reload().await;
external.barrier.wait().await;
};
let (retry, ()) = tokio::join!(recovery, concurrent_update);
assert_eq!(retry, changed && !matches!(failure, RefreshFailure::Policy));
if matches!(failure, RefreshFailure::Permanent) && token == "Bearer old" {
if matches!(failure, RefreshFailure::Permanent) && unchanged {
// Even a late rejection must not reuse a credential known to have failed.
assert!(!provider.refresh_after_unauthorized(HeaderMap::new()).await);
}
}
}
}
#[tokio::test]
async fn first_party_run_scope_uses_agent_assertion_and_exposes_telemetry() {
let auth =
CodexAuth::AgentIdentity(agent_identity_auth(/*chatgpt_account_is_fedramp*/ false).await);
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
let auth = resolve_provider_auth_for_scope(
/*auth_manager*/ None,
Some(&auth),
&provider,
provider_auth_scope(
AgentIdentityAuthPolicy::JwtOnly,
AgentIdentitySessionFallback::default(),
),
)
.await
.expect("auth should resolve");
assert_eq!(
auth.agent_identity_telemetry,
Some(AgentIdentityTelemetry {
agent_id: "agent-runtime-1".to_string(),
task_id: "task-run-1".to_string(),
})
);
let headers = auth.auth.to_auth_headers().unwrap();
assert!(
headers
.get(http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.starts_with("AgentAssertion "))
);
}
#[tokio::test]
async fn agent_identity_auth_provider_preserves_account_routing_headers() {
let auth = agent_identity_auth(/*chatgpt_account_is_fedramp*/ true).await;
let provider = auth_provider_from_auth(&CodexAuth::AgentIdentity(auth));
let headers = provider.to_auth_headers().unwrap();
assert!(
headers
.get(http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.starts_with("AgentAssertion "))
);
assert_eq!(
headers
.get("ChatGPT-Account-ID")
.and_then(|value| value.to_str().ok()),
Some("account-1")
);
assert_eq!(
headers
.get("X-OpenAI-Fedramp")
.and_then(|value| value.to_str().ok()),
Some("true")
);
}
#[tokio::test]
async fn chatgpt_bootstrap_unavailable_uses_session_bearer_fallback() {
let server = MockServer::start().await;
let registration_count = Arc::new(AtomicUsize::new(0));
mount_transient_agent_registration(
&server,
/*status*/ 503,
Arc::clone(&registration_count),
)
.await;
let (_codex_home, auth_manager, auth) = chatgpt_auth_manager(server.uri()).await;
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
let fallback = AgentIdentitySessionFallback::default();
let provider_auth = resolve_provider_auth_for_scope(
Some(auth_manager),
Some(&auth),
&provider,
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, fallback.clone()),
)
.await
.expect("fallback should resolve bearer auth");
let headers = provider_auth.auth.to_auth_headers().unwrap();
assert_eq!(
headers
.get(http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok()),
Some("Bearer test-access-token")
);
assert_eq!(
headers
.get("ChatGPT-Account-ID")
.and_then(|value| value.to_str().ok()),
Some("account-123")
);
assert!(fallback.is_engaged());
assert_eq!(registration_count.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn chatgpt_session_fallback_skips_later_agent_identity_bootstrap() {
let server = MockServer::start().await;
let registration_count = Arc::new(AtomicUsize::new(0));
mount_transient_agent_registration(
&server,
/*status*/ 503,
Arc::clone(&registration_count),
)
.await;
let (_codex_home, auth_manager, auth) = chatgpt_auth_manager(server.uri()).await;
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
let fallback = AgentIdentitySessionFallback::default();
resolve_provider_auth_for_scope(
Some(Arc::clone(&auth_manager)),
Some(&auth),
&provider,
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, fallback.clone()),
)
.await
.expect("first fallback should resolve bearer auth");
resolve_provider_auth_for_scope(
Some(auth_manager),
Some(&auth),
&provider,
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, fallback),
)
.await
.expect("second fallback should resolve bearer auth");
assert_eq!(registration_count.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn chatgpt_sessions_share_bootstrap_failure_cooldown() {
let server = MockServer::start().await;
let registration_count = Arc::new(AtomicUsize::new(0));
mount_transient_agent_registration(
&server,
/*status*/ 503,
Arc::clone(&registration_count),
)
.await;
let (_codex_home, auth_manager, auth) = chatgpt_auth_manager(server.uri()).await;
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
let first_fallback = AgentIdentitySessionFallback::default();
let second_fallback = AgentIdentitySessionFallback::default();
resolve_provider_auth_for_scope(
Some(Arc::clone(&auth_manager)),
Some(&auth),
&provider,
provider_auth_scope(AgentIdentityAuthPolicy::ChatGptAuth, first_fallback.clone()),
)
.await
.expect("first session fallback should resolve bearer auth");
resolve_provider_auth_for_scope(
Some(auth_manager),
Some(&auth),
&provider,
provider_auth_scope(
AgentIdentityAuthPolicy::ChatGptAuth,
second_fallback.clone(),
),
)
.await
.expect("second session fallback should resolve bearer auth");
assert!(first_fallback.is_engaged());
assert!(second_fallback.is_engaged());
assert_eq!(registration_count.load(Ordering::SeqCst), 3);
}

View File

@@ -1,5 +1,4 @@
use codex_api::AuthProvider;
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
use codex_login::auth::is_fedramp_api_key;
use http::HeaderMap;
use http::HeaderValue;
@@ -8,7 +7,6 @@ use http::HeaderValue;
#[derive(Clone, Default)]
pub struct BearerAuthProvider {
pub token: Option<String>,
pub account_id: Option<String>,
pub is_fedramp_account: bool,
}
@@ -17,15 +15,13 @@ impl BearerAuthProvider {
let is_fedramp_account = is_fedramp_api_key(&token);
Self {
token: Some(token),
account_id: None,
is_fedramp_account,
}
}
pub fn for_test(token: Option<&str>, account_id: Option<&str>) -> Self {
pub fn for_test(token: Option<&str>) -> Self {
Self {
token: token.map(str::to_string),
account_id: account_id.map(str::to_string),
is_fedramp_account: false,
}
}
@@ -38,11 +34,6 @@ impl AuthProvider for BearerAuthProvider {
{
let _ = headers.insert(http::header::AUTHORIZATION, header);
}
if let Some(account_id) = self.account_id.as_ref()
&& let Ok(header) = HeaderValue::from_str(account_id)
{
let _ = headers.insert(CHATGPT_ACCOUNT_ID_HEADER, header);
}
if self.is_fedramp_account {
let _ = headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
}

View File

@@ -7,7 +7,6 @@ use pretty_assertions::assert_eq;
fn bearer_auth_provider_reports_when_auth_header_will_attach() {
let auth = BearerAuthProvider {
token: Some("access-token".to_string()),
account_id: None,
is_fedramp_account: false,
};
@@ -22,7 +21,7 @@ fn bearer_auth_provider_reports_when_auth_header_will_attach() {
#[test]
fn bearer_auth_provider_adds_auth_headers() {
let auth = BearerAuthProvider::for_test(Some("access-token"), Some("workspace-123"));
let auth = BearerAuthProvider::for_test(Some("access-token"));
let mut headers = HeaderMap::new();
auth.add_auth_headers(&mut headers).unwrap();
@@ -33,19 +32,13 @@ fn bearer_auth_provider_adds_auth_headers() {
.and_then(|value| value.to_str().ok()),
Some("Bearer access-token")
);
assert_eq!(
headers
.get("ChatGPT-Account-ID")
.and_then(|value| value.to_str().ok()),
Some("workspace-123")
);
assert_eq!(headers.get("ChatGPT-Account-ID"), None);
}
#[test]
fn bearer_auth_provider_adds_fedramp_routing_header_for_fedramp_accounts() {
let auth = BearerAuthProvider {
token: Some("access-token".to_string()),
account_id: Some("workspace-123".to_string()),
is_fedramp_account: true,
};
let mut headers = HeaderMap::new();

View File

@@ -12,7 +12,6 @@ use codex_model_provider_info::RemoteCompactionSupport;
pub struct ProviderCapabilities {
/// Whether requests may include the Responses API `reasoning.summary` parameter.
pub reasoning_summaries: bool,
pub image_generation: bool,
pub web_search: bool,
pub external_web_access: bool,
pub remote_compaction: RemoteCompactionSupport,
@@ -22,7 +21,6 @@ impl Default for ProviderCapabilities {
fn default() -> Self {
Self {
reasoning_summaries: true,
image_generation: true,
web_search: true,
external_web_access: true,
remote_compaction: RemoteCompactionSupport::Unsupported,

View File

@@ -1,121 +0,0 @@
//! Authentication for clients that reuse a connection across requests.
use crate::ResolvedProviderAuth;
use codex_api::AuthError;
use codex_api::SharedAuthProvider;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClientFactory;
use codex_login::CodexAuth;
use codex_protocol::error::Result as CodexResult;
use codex_runtime_agent_instance::RuntimeAuthBinding;
use codex_runtime_agent_instance::RuntimeAuthManager;
use http::HeaderMap;
use std::sync::Arc;
/// Keeps a reusable client's credential source fixed while allowing token refresh.
/// Each request resolves fresh auth using the same source as the client transport.
#[derive(Clone)]
pub struct ClientAuth {
source: ClientAuthSource,
}
#[derive(Clone)]
enum ClientAuthSource {
Provider(SharedAuthProvider),
Runtime {
manager: Arc<RuntimeAuthBinding>,
mode: RuntimeAuthMode,
source_generation: u64,
},
}
impl ClientAuth {
pub fn new(provider: SharedAuthProvider) -> Self {
Self {
source: ClientAuthSource::Provider(provider),
}
}
/// Select the auth source and matching transport for a reusable client's request headers.
/// The caller selects runtime auth only for a supported OpenAI destination.
pub async fn for_auth(
auth: &CodexAuth,
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
factory: HttpClientFactory,
headers: &HeaderMap,
) -> anyhow::Result<(Self, HttpClientFactory)> {
let resolved = crate::auth_provider_for_request(auth, runtime, headers).await?;
let factory = resolved.bind_http_client_factory(factory)?;
let source = match (runtime, resolved.runtime) {
(Some((_, mode)), Some(selected)) => ClientAuthSource::Runtime {
manager: Arc::clone(selected.binding()),
mode: *mode,
source_generation: selected.change_state().source_generation,
},
_ => ClientAuthSource::Provider(resolved.auth),
};
Ok((Self { source }, factory))
}
/// Replace ordinary authentication; reject changes to a runtime-bound client.
pub fn set_provider(&mut self, provider: SharedAuthProvider) -> Result<(), AuthError> {
match &mut self.source {
ClientAuthSource::Provider(current) => {
*current = provider;
Ok(())
}
ClientAuthSource::Runtime { .. } => Err(AuthError::Build(
"cannot replace credentials on a runtime-bound client".to_string(),
)),
}
}
/// Resolve one request, preserving the source that authenticated the client.
pub async fn resolve(&self, headers: &HeaderMap) -> Result<ResolvedProviderAuth, AuthError> {
let mode = match &self.source {
ClientAuthSource::Provider(_) => None,
ClientAuthSource::Runtime { mode, .. } => Some(*mode),
};
crate::auth::observe_auth_selection(mode, "client_request", async {
match &self.source {
ClientAuthSource::Provider(provider) => {
Ok(ResolvedProviderAuth::new(Arc::clone(provider)))
}
ClientAuthSource::Runtime {
manager,
mode,
source_generation,
} => {
let selected =
crate::select_runtime_auth_for_source(manager, *source_generation, headers)
.await?;
Ok(ResolvedProviderAuth::for_runtime(selected, *mode))
}
}
})
.await
}
/// Allow OpenAI requests and the original origin, never an unrelated provider.
pub fn validate_destination(&self, base_url: &str, url: &str) -> CodexResult<()> {
if matches!(&self.source, ClientAuthSource::Provider(_)) {
return Ok(());
}
crate::validate_runtime_destination(Some(url))?;
if codex_runtime_agent_instance::is_openai_api_url(url) {
return Ok(());
}
let origin = |value| {
url::Url::parse(value)
.map(|url| url.origin())
.map_err(std::io::Error::other)
};
if origin(url)? != origin(base_url)? {
return Err(std::io::Error::other(
"runtime-authenticated clients cannot send requests to another provider",
)
.into());
}
Ok(())
}
}

View File

@@ -0,0 +1,17 @@
//! Identity of a reusable Responses connection.
/// Effective destination and credentials that permit reusing a Responses socket.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResponsesConnectionKey {
base_url: String,
auth_revision: Option<u64>,
}
impl ResponsesConnectionKey {
pub fn new(provider: &codex_api::Provider, auth_revision: Option<u64>) -> Self {
Self {
base_url: provider.base_url.clone(),
auth_revision,
}
}
}

View File

@@ -59,7 +59,7 @@ impl GcpModelProvider {
async fn api_provider(&self) -> Result<Provider> {
let mut provider_info = self.info.clone();
provider_info.base_url = self.runtime_base_url().await?;
provider_info.to_api_provider(/*auth_mode*/ None)
provider_info.to_api_provider()
}
async fn runtime_base_url(&self) -> Result<Option<String>> {
@@ -81,7 +81,6 @@ impl ModelProvider for GcpModelProvider {
fn capabilities(&self) -> ProviderCapabilities {
ProviderCapabilities {
reasoning_summaries: false,
image_generation: false,
web_search: false,
external_web_access: false,
remote_compaction: RemoteCompactionSupport::V2,

View File

@@ -4,8 +4,8 @@ mod bearer_auth_provider;
mod capabilities;
mod catalog_factory;
mod chatgpt_base_url;
mod client_auth;
mod combined_auth;
mod connection_key;
mod gateway_auth;
mod gateway_export;
mod gcp;
@@ -14,21 +14,13 @@ mod models_identity;
mod provider;
mod request_preparation;
mod request_setup;
mod runtime_auth;
mod shared_state;
pub mod test_support;
mod workspace_routing;
pub use workspace_routing::ACCOUNT_ROUTING_HEADER;
pub use workspace_routing::ResolvedResponsesProvider;
pub use workspace_routing::ResponsesConnectionKey;
pub use workspace_routing::WorkspaceRoutingContext;
pub use amazon_bedrock::is_amazon_bedrock_gov_cloud_region;
pub use amazon_bedrock::is_supported_amazon_bedrock_region;
pub use amazon_bedrock::resolve_amazon_bedrock_region;
pub use auth::AgentIdentitySessionFallback;
pub use auth::ProviderAuthContext;
pub use auth::ProviderAuthScope;
pub use auth::ResolvedProviderAuth;
pub use auth::auth_provider_for_request;
pub use auth::auth_provider_from_auth;
@@ -38,12 +30,11 @@ pub use bearer_auth_provider::BearerAuthProvider;
pub use bearer_auth_provider::BearerAuthProvider as CoreAuthProvider;
pub use capabilities::ProviderCapabilities;
pub use catalog_factory::ModelCatalogFactory;
pub use connection_key::ResponsesConnectionKey;
pub use chatgpt_base_url::ChatgptBaseUrl;
pub use chatgpt_base_url::DEFAULT_CHATGPT_BASE_URL;
pub use client_auth::ClientAuth;
pub use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
pub use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
pub use codex_model_provider_info::CHATGPT_CODEX_BASE_URL;
pub use codex_model_provider_info::GCP_PROVIDER_ID;
pub use codex_model_provider_info::RemoteCompactionSupport;
pub use codex_protocol::account::ProviderAccount;
@@ -57,17 +48,10 @@ pub use provider::ProviderAuthRecoveryMessages;
pub use provider::ProviderUnauthorizedRecovery;
pub use provider::SharedModelProvider;
pub use provider::create_model_provider;
pub use provider::provider_uses_first_party_auth_path;
pub use provider::provider_uses_stored_auth;
pub use provider::resolve_api_provider;
pub use request_preparation::prepare_provider_request;
pub use request_setup::ResolvedProviderRequest;
pub use request_setup::request_auth_owner;
pub use request_setup::resolve_request;
pub use runtime_auth::runtime_auth_for_url;
pub use runtime_auth::select_runtime_auth_for;
pub(crate) use runtime_auth::select_runtime_auth_for_source;
pub use runtime_auth::select_runtime_provider;
pub use runtime_auth::validate_runtime_destination;
pub use runtime_auth::validate_runtime_environment;
pub use runtime_auth::validate_runtime_selectors;

View File

@@ -6,14 +6,12 @@ use std::sync::Arc;
use std::time::Duration;
use crate::GatewayAuthManager;
use codex_api::AgentIdentityTelemetry;
use codex_api::ModelsClient;
use codex_api::RequestTelemetry;
use codex_api::ReqwestTransport;
use codex_api::TransportError;
use codex_api::auth_header_telemetry;
use codex_api::map_api_error;
use codex_features::RuntimeAuthMode;
use codex_feedback::FeedbackRequestTags;
use codex_feedback::emit_feedback_request_tags_with_auth_env;
use codex_http_client::ClientRouteClass;
@@ -24,7 +22,6 @@ use codex_login::CodexAuth;
use codex_login::collect_auth_env_telemetry;
use codex_login::default_client::ClientRedirectPolicy;
use codex_login::default_client::create_client_for_route_async;
use codex_model_provider_info::CHATGPT_CODEX_BASE_URL;
use codex_model_provider_info::GatewayOAuthConfig;
use codex_model_provider_info::ModelProviderInfo;
use codex_models_manager::ModelCatalogOriginator;
@@ -36,19 +33,15 @@ use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CoreResult;
use codex_response_debug_context::extract_response_debug_context;
use codex_response_debug_context::telemetry_transport_error_message;
use codex_runtime_agent_instance::RuntimeAuthManager;
use http::HeaderMap;
use tokio::time::timeout;
use crate::auth::agent_identity_telemetry;
use crate::auth::uses_fedramp_api_key;
use crate::combined_auth::compose_auth;
use crate::provider::resolve_api_provider;
use crate::request_setup::resolve_request_auth;
const MODELS_REFRESH_TIMEOUT: Duration = Duration::from_secs(5);
const MODELS_ENDPOINT: &str = "/models";
const FEDRAMP_CODEX_BASE_URL: &str = "https://gov.chatgpt.com/backend-api/codex";
/// Provider-owned OpenAI-compatible `/models` endpoint.
#[derive(Debug)]
@@ -57,7 +50,6 @@ pub(crate) struct OpenAiModelsEndpoint {
auth_manager: Option<Arc<AuthManager>>,
gateway_auth_manager: Option<Result<Arc<GatewayAuthManager>, String>>,
transport_builder: Arc<dyn ModelsTransportBuilder>,
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
}
impl OpenAiModelsEndpoint {
@@ -77,7 +69,6 @@ impl OpenAiModelsEndpoint {
ClientRedirectPolicy::Default
};
Self {
runtime_auth: None,
provider_info,
auth_manager,
gateway_auth_manager,
@@ -85,35 +76,6 @@ impl OpenAiModelsEndpoint {
}
}
/// Use the same runtime owner as the harness's model sessions.
pub(crate) fn with_runtime_auth(
mut self,
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> Self {
self.runtime_auth = runtime_auth;
self
}
async fn auth(&self) -> Option<CodexAuth> {
let auth_manager = self.auth_manager.clone()?;
// Catalog startup has its own deadline. Let rotating credentials finish
// saving even when that caller stops waiting.
match tokio::spawn(async move { auth_manager.auth().await }).await {
Ok(auth) => auth,
Err(error) => {
tracing::warn!(?error, "model catalog authentication task failed");
None
}
}
}
async fn uses_codex_backend(&self) -> bool {
self.auth()
.await
.as_ref()
.is_some_and(CodexAuth::uses_codex_backend)
}
async fn list_models(
&self,
client_version: &str,
@@ -132,26 +94,15 @@ impl OpenAiModelsEndpoint {
client_version: &str,
http_client_factory: HttpClientFactory,
) -> CoreResult<ModelsEndpointResponse> {
let resolved = resolve_request_auth(
self.provider_info.clone(),
self.auth_manager.clone(),
self.runtime_auth.clone(),
/*scope*/ None,
self.provider_info
.model_catalog_url
.as_deref()
.map(String::as_str)
.or(self.provider_info.base_url.as_deref())
.map(str::to_owned),
)
.await?;
let resolved =
resolve_request_auth(self.provider_info.clone(), self.auth_manager.clone()).await?;
let auth = resolved.credential.clone();
let metric_auth_mode = if self.has_provider_api_key()
|| auth.as_ref().is_some_and(CodexAuth::is_api_key_auth)
{
"api_key"
} else if auth.is_some() {
"chatgpt"
"headers"
} else {
"none"
};
@@ -161,24 +112,7 @@ impl OpenAiModelsEndpoint {
);
let identity = crate::models_identity::identity(&self.provider_info, auth.as_ref())?;
let auth_mode = auth.as_ref().map(CodexAuth::auth_mode);
let mut api_provider = resolve_api_provider(&self.provider_info, auth.as_ref())?;
if (auth.as_ref().is_some_and(CodexAuth::is_api_key_auth) || self.has_provider_api_key())
&& self.supports_api_key_models()
&& self.provider_info.base_url.is_none()
&& self.provider_info.model_catalog_url.is_none()
{
// Codex metadata is served by the Codex backend, not the public /v1/models API.
api_provider.base_url = if uses_fedramp_api_key(auth.as_ref(), &self.provider_info)? {
FEDRAMP_CODEX_BASE_URL
} else {
CHATGPT_CODEX_BASE_URL
}
.to_string();
}
let http_client_factory = resolved
.bind_http_client_factory(http_client_factory)
.map_err(|error| map_api_error(error.into()))?;
resolved.validate_headers(&api_provider.headers)?;
let api_provider = resolve_api_provider(&self.provider_info, auth.as_ref())?;
let resolved = compose_auth(
&self.provider_info,
self.gateway_auth_manager.as_ref(),
@@ -197,17 +131,11 @@ impl OpenAiModelsEndpoint {
};
let auth_telemetry = auth_header_telemetry(api_auth.as_ref())
.map_err(|error| map_api_error(error.into()))?;
let agent_identity_telemetry = if let Some(CodexAuth::AgentIdentity(auth)) = auth.as_ref() {
Some(agent_identity_telemetry(auth))
} else {
None
};
let request_telemetry: Arc<dyn RequestTelemetry> = Arc::new(ModelsRequestTelemetry {
include_response_debug: self.provider_info.model_catalog_url.is_none(),
auth_mode: auth_mode.map(|mode| TelemetryAuthMode::from(mode).to_string()),
auth_header_attached: auth_telemetry.attached,
auth_header_name: auth_telemetry.name,
agent_identity_telemetry,
auth_env: self.auth_env(),
});
let (models, etag) = {
@@ -284,14 +212,12 @@ impl ModelsEndpointClient for OpenAiModelsEndpoint {
provider_info,
auth_manager: self.auth_manager.clone(),
gateway_auth_manager: self.gateway_auth_manager.clone(),
runtime_auth: self.runtime_auth.clone(),
transport_builder: Arc::clone(&self.transport_builder),
}))
}
fn supports_api_key_models(&self) -> bool {
self.provider_info.model_catalog_url.is_some()
|| (self.provider_info.is_openai() && self.provider_info.base_url.is_none())
}
fn has_provider_api_key(&self) -> bool {
@@ -311,10 +237,6 @@ impl ModelsEndpointClient for OpenAiModelsEndpoint {
self.provider_info.has_command_auth()
}
fn uses_codex_backend(&self) -> ModelsEndpointFuture<'_, bool> {
Box::pin(OpenAiModelsEndpoint::uses_codex_backend(self))
}
fn list_models<'a>(
&'a self,
client_version: &'a str,
@@ -377,7 +299,6 @@ struct ModelsRequestTelemetry {
auth_mode: Option<String>,
auth_header_attached: bool,
auth_header_name: Option<&'static str>,
agent_identity_telemetry: Option<AgentIdentityTelemetry>,
auth_env: AuthEnvTelemetry,
}
@@ -413,14 +334,11 @@ impl RequestTelemetry for ModelsRequestTelemetry {
auth.env_codex_api_key_enabled = self.auth_env.codex_api_key_env_enabled,
auth.env_provider_key_name = self.auth_env.provider_env_key_name.as_deref(),
auth.env_provider_key_present = self.auth_env.provider_env_key_present,
auth.env_refresh_token_url_override_present = self.auth_env.refresh_token_url_override_present,
auth.request_id = response_debug.request_id.as_deref(),
auth.cf_ray = response_debug.cf_ray.as_deref(),
auth.error = response_debug.auth_error.as_deref(),
auth.error_code = response_debug.auth_error_code.as_deref(),
auth.mode = self.auth_mode.as_deref(),
auth.agent_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.agent_id.as_str()),
auth.task_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.task_id.as_str()),
);
tracing::event!(
target: "codex_otel.trace_safe",
@@ -439,14 +357,11 @@ impl RequestTelemetry for ModelsRequestTelemetry {
auth.env_codex_api_key_enabled = self.auth_env.codex_api_key_env_enabled,
auth.env_provider_key_name = self.auth_env.provider_env_key_name.as_deref(),
auth.env_provider_key_present = self.auth_env.provider_env_key_present,
auth.env_refresh_token_url_override_present = self.auth_env.refresh_token_url_override_present,
auth.request_id = response_debug.request_id.as_deref(),
auth.cf_ray = response_debug.cf_ray.as_deref(),
auth.error = response_debug.auth_error.as_deref(),
auth.error_code = response_debug.auth_error_code.as_deref(),
auth.mode = self.auth_mode.as_deref(),
auth.agent_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.agent_id.as_str()),
auth.task_id = self.agent_identity_telemetry.as_ref().map(|metadata| metadata.task_id.as_str()),
);
emit_feedback_request_tags_with_auth_env(
&FeedbackRequestTags {
@@ -481,11 +396,3 @@ mod originator_tests;
#[cfg(test)]
#[path = "models_endpoint_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "models_endpoint_runtime_auth_tests.rs"]
mod runtime_auth_tests;
#[cfg(test)]
#[path = "models_endpoint_refresh_tests.rs"]
mod refresh_tests;

View File

@@ -1,289 +0,0 @@
//! A catalog deadline must not interrupt rotating OAuth credentials before persistence.
use super::*;
use base64::Engine;
use codex_http_client::OutboundProxyPolicy;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthRouteConfig;
use codex_models_manager::manager::ModelsManager;
use codex_models_manager::manager::OpenAiModelsManager;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[derive(Clone, Copy)]
enum Caller {
Catalog,
Startup,
CapturedCredential,
SourceGeneration,
}
#[tokio::test]
async fn catalog_timeout_preserves_refreshed_tokens_with_and_without_runtime_auth() {
check_timeout_preserves_refreshed_tokens(Caller::Catalog).await;
}
#[tokio::test]
async fn catalog_startup_timeout_preserves_refreshed_tokens() {
check_timeout_preserves_refreshed_tokens(Caller::Startup).await;
}
#[tokio::test]
async fn cancelled_runtime_client_selection_persists_the_rotated_token() {
check_timeout_preserves_refreshed_tokens(Caller::CapturedCredential).await;
check_timeout_preserves_refreshed_tokens(Caller::SourceGeneration).await;
}
async fn check_timeout_preserves_refreshed_tokens(caller: Caller) {
for mode in [
None,
Some(RuntimeAuthMode::DualHeader),
Some(RuntimeAuthMode::AssertionOnly),
] {
if matches!(
caller,
Caller::CapturedCredential | Caller::SourceGeneration
) && mode != Some(RuntimeAuthMode::DualHeader)
{
continue;
}
let server = MockServer::start().await;
let home = tempfile::tempdir().unwrap();
let token = |expires| {
let payload = json!({
"iss": server.uri(), "session_id": "session-a", "exp": expires,
"https://api.openai.com/auth": {
"chatgpt_user_id": "user-a", "chatgpt_account_id": "workspace-a",
"chatgpt_plan_type": "plus",
},
});
format!(
"e30.{}.signature",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload.to_string())
)
};
let old_token = token(0);
let new_token = token(chrono::Utc::now().timestamp() + 3600);
let stored = serde_json::from_value(json!({
"auth_mode": "chatgpt",
"tokens": {
"id_token": old_token, "access_token": old_token,
"refresh_token": "refresh-before", "account_id": "workspace-a",
"oauth_provenance": {"issuer": server.uri(), "client_id": "test-client"},
},
"last_refresh": "2020-01-01T00:00:00Z",
}))
.unwrap();
codex_login::save_auth(
home.path(),
&stored,
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
)
.unwrap();
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_partial_json(
json!({"refresh_token": "refresh-before"}),
))
.respond_with(
ResponseTemplate::new(200)
.set_delay(MODELS_REFRESH_TIMEOUT + Duration::from_secs(1))
.set_body_json(json!({
"id_token": new_token, "access_token": new_token,
"refresh_token": "refresh-after",
})),
)
.up_to_n_times(1)
.with_priority(1)
.expect(1)
.mount(&server)
.await;
// Reusing the consumed refresh token must fail, as it would at the issuer.
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"error": {"code": "refresh_token_reused"},
})))
.with_priority(2)
.expect(0)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/register"))
.and(body_partial_json(
json!({"actor_auth": {"credential": new_token}}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
})))
.expect(u64::from(mode.is_some()))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/models"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
.expect(1)
.mount(&server)
.await;
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
let credentials = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::Direct,
AuthRouteConfig::from_http_client_factory(factory.clone()),
)
.await,
);
let runtime_auth = mode.map(|mode| {
(
Arc::new(RuntimeAuthManager::new(
Arc::clone(&credentials),
AgentHostAuthorization::InstallationId {
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
},
RuntimeRegistrationMetadata {
harness: None,
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/register", server.uri()).parse().unwrap(),
)),
mode,
)
});
let mut info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
info.env_http_headers = None;
let endpoint = Arc::new(
OpenAiModelsEndpoint::new(
info,
Some(Arc::clone(&credentials)),
/*gateway_auth_manager*/ None,
)
.with_runtime_auth(runtime_auth.clone()),
);
match caller {
Caller::CapturedCredential => {
let auth = credentials.auth_cached().unwrap();
assert!(
timeout(
MODELS_REFRESH_TIMEOUT,
crate::auth_provider_for_request(
&auth,
runtime_auth.as_ref(),
&http::HeaderMap::new()
)
)
.await
.is_err()
);
}
Caller::SourceGeneration => {
let generation = credentials
.auth_change_state_receiver()
.borrow()
.source_generation;
let runtime = runtime_auth
.as_ref()
.unwrap()
.0
.bind(Arc::clone(&credentials));
assert!(
timeout(
MODELS_REFRESH_TIMEOUT,
crate::select_runtime_auth_for_source(
&runtime,
generation,
&http::HeaderMap::new()
)
)
.await
.is_err()
);
}
Caller::Startup => {
let manager = OpenAiModelsManager::new_without_cache(
endpoint.clone(),
Some(Arc::clone(&credentials)),
);
manager.refresh_after_auth_change(factory.clone()).await;
}
Caller::Catalog => {
let error = endpoint
.list_models("test", factory.clone())
.await
.unwrap_err();
assert!(matches!(
error.details(),
codex_protocol::error::CodexErrorDetails::RequestTimeout
));
}
}
assert_eq!(
server
.received_requests()
.await
.unwrap()
.iter()
.filter(|request| request.url.path() == "/oauth/token")
.count(),
1,
);
// Wait through the existing refresh lock; this must reuse the completed refresh.
let current = credentials.auth().await.unwrap();
assert_eq!(current.get_token().unwrap(), new_token);
let saved = codex_login::load_auth_dot_json(
home.path(),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
)
.unwrap()
.unwrap()
.tokens
.unwrap();
assert_eq!(saved.access_token, new_token);
assert_eq!(saved.refresh_token, "refresh-after");
endpoint.list_models("test", factory).await.unwrap();
let requests = server.received_requests().await.unwrap();
let models = requests
.iter()
.find(|request| request.url.path() == "/models")
.unwrap();
if mode == Some(RuntimeAuthMode::AssertionOnly) {
assert!(
models.headers["authorization"]
.to_str()
.unwrap()
.starts_with("AgentAssertion ")
);
} else {
assert_eq!(
models.headers["authorization"],
format!("Bearer {new_token}")
);
}
assert_eq!(
models.headers.contains_key("x-openai-agent-assertion"),
mode == Some(RuntimeAuthMode::DualHeader)
);
server.verify().await;
}
}

View File

@@ -1,520 +0,0 @@
use super::*;
use base64::Engine;
use codex_features::RuntimeAuthMode;
use codex_http_client::OutboundProxyPolicy;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn provider_auth_rejects_selectors_that_do_not_match_the_registered_actor() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for selector in ["chatgpt-account-id", "openai-organization"] {
let server = MockServer::start().await;
let (auth, actor, expected) = if selector == "chatgpt-account-id" {
let claims = json!({"session_id": "session-a", "https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"}});
let token = format!(
"e30.{}.signature",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())
);
(
CodexAuth::from_external_chatgpt_tokens(
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap(),
json!({"kind":"chatgpt", "user_id":"user-a", "account_id":"workspace-a"}),
"workspace-a",
)
} else {
(
CodexAuth::from_api_key("key-a"),
json!({"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":"project-a"}),
"org-a",
)
};
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a", "actor": actor,
})))
.mount(&server)
.await;
let credentials = AuthManager::from_auth_for_testing(auth);
let context = crate::ProviderAuthContext {
runtime_auth: Some((runtime_manager(&server, Arc::clone(&credentials)), mode)),
credentials,
};
let mut info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
info.env_http_headers = None;
info.http_headers = Some(std::collections::HashMap::from([(
selector.into(),
expected.into(),
)]));
let provider = context.model_provider(info.clone());
let auth = provider.api_auth().await.unwrap();
assert!(
auth.to_auth_headers()
.unwrap()
.contains_key("authorization")
);
info.http_headers = Some(std::collections::HashMap::from([(
selector.into(),
"different".into(),
)]));
let provider = context.model_provider(info);
let error = provider
.api_auth()
.await
.err()
.expect("mismatched selector must be rejected");
assert!(matches!(
error.details(),
codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_)
));
assert!(error.to_string().contains(selector));
assert!(!server.received_requests().await.unwrap().is_empty());
}
}
}
#[tokio::test]
async fn model_requests_keep_the_selected_project_while_reusing_one_runtime() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a",
"agent_host_id": "host-a",
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":"project-a"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/models"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[]})))
.expect(4)
.mount(&server)
.await;
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
let runtime = runtime_manager(&server, Arc::clone(&credentials));
let context = crate::ProviderAuthContext {
runtime_auth: Some((Arc::clone(&runtime), mode)),
credentials: Arc::clone(&credentials),
};
let projects = [
Some("project-a"),
Some("project-b"),
None,
Some("project-a"),
];
for project in projects {
let mut info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
info.env_http_headers = None;
let mut headers =
std::collections::HashMap::from([("openai-organization".into(), "org-a".into())]);
if let Some(project) = project {
headers.insert("openai-project".into(), project.into());
}
info.http_headers = Some(headers);
let provider = context.model_provider(info.clone());
let request = crate::resolve_request(
provider.as_ref(),
/*scope*/ None,
/*routing*/ None,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await
.unwrap();
assert_eq!(request.runtime_id.as_deref(), Some("runtime-a"));
assert_eq!(
request
.api_provider
.headers
.get("openai-project")
.map(|value| value.to_str().unwrap()),
project,
);
assert!(
request
.api_auth
.to_auth_headers()
.unwrap()
.contains_key("authorization")
);
info.base_url = Some(server.uri());
let endpoint = OpenAiModelsEndpoint::new(
info,
Some(Arc::clone(&credentials)),
/*gateway_auth_manager*/ None,
)
.with_runtime_auth(Some((Arc::clone(&runtime), mode)));
endpoint
.list_models(
"test",
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await
.unwrap();
}
let requests = server.received_requests().await.unwrap();
let models: Vec<_> = requests
.iter()
.filter(|request| request.url.path() == "/models")
.collect();
assert_eq!(models.len(), projects.len());
for (request, project) in models.into_iter().zip(projects) {
assert_eq!(
request
.headers
.get("openai-project")
.map(|value| value.to_str().unwrap()),
project
);
assert_eq!(request.headers["openai-organization"], "org-a");
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(request.headers["authorization"], "Bearer key-a");
assert!(request.headers.contains_key("x-openai-agent-assertion"));
}
RuntimeAuthMode::AssertionOnly => {
assert!(
request.headers["authorization"]
.to_str()
.unwrap()
.starts_with("AgentAssertion ")
);
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
}
}
}
server.verify().await;
}
}
#[tokio::test]
async fn runtime_registration_environment_matches_inference_and_catalog() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for (registration_base, destination, matching_destination) in [
(
"https://chatgpt.com",
Some("https://api.openai-staging.com/v1"),
"https://eu.api.openai.com/v1",
),
(
"https://chatgpt-staging.com",
Some("https://api.openai.com/v1"),
"https://api.openai-staging.com/v1",
),
(
"https://chatgpt-staging.com",
None,
"https://chatgpt-staging.com/backend-api/codex",
),
] {
let home = tempfile::tempdir().unwrap();
// Keep external network access disabled even if destination validation regresses.
let controller = codex_http_client::NetworkPolicyController::default();
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(controller.policy());
let credentials = AuthManager::from_api_key(
"ambient-key",
codex_login::AuthRuntimeConfig {
codex_home: home.path().to_path_buf(),
auth_route_config: codex_login::AuthRouteConfig::from_http_client_factory(
factory.clone(),
),
},
);
let runtime = Arc::new(RuntimeAuthManager::for_chatgpt(
Arc::clone(&credentials),
"00000000-0000-0000-0000-000000000000".into(),
registration_base.into(),
RuntimeRegistrationMetadata {
harness: None,
harness_version: None,
role: RuntimeRole::Orchestrator,
},
));
crate::validate_runtime_environment(&runtime, Some(matching_destination)).unwrap();
let info = ModelProviderInfo {
experimental_bearer_token: Some("provider-key".into()),
env_http_headers: None,
..ModelProviderInfo::create_openai_provider(destination.map(str::to_owned))
};
let provider = crate::provider::create_model_provider_with_runtime(
info.clone(),
Some(Arc::clone(&credentials)),
Some((Arc::clone(&runtime), mode)),
);
let error = provider.request_auth(/*scope*/ None).await.err().unwrap();
assert!(matches!(
error.details(),
codex_protocol::error::CodexErrorDetails::InvalidRequest(_)
));
let mut catalog_info = info;
if let Some(destination) = destination {
catalog_info.base_url = Some(matching_destination.into());
catalog_info.model_catalog_url = Some(format!("{destination}/models").into());
}
let catalog = OpenAiModelsEndpoint::new(
catalog_info,
Some(credentials),
/*gateway_auth_manager*/ None,
)
.with_runtime_auth(Some((runtime, mode)));
let error = catalog.list_models("0.0.0", factory).await.unwrap_err();
assert!(matches!(
error.details(),
codex_protocol::error::CodexErrorDetails::InvalidRequest(_)
));
}
}
}
#[tokio::test]
async fn unsupported_openai_destinations_do_not_fall_back_to_bearer_auth() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
let runtime = runtime_manager(&server, Arc::clone(&credentials));
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
for destination in [
"https://unknown.api.openai.com/v1",
"http://api.openai.com/v1",
"https://api.openai.com:8443/v1",
] {
let info = ModelProviderInfo::create_openai_provider(Some(destination.into()));
let provider = crate::provider::create_model_provider_with_runtime(
info.clone(),
Some(Arc::clone(&credentials)),
Some((Arc::clone(&runtime), mode)),
);
let error = provider
.request_auth(/*scope*/ None)
.await
.err()
.expect("unsupported inference origin");
assert!(
error
.to_string()
.contains("does not support this OpenAI endpoint")
);
let mut catalog_info = info;
catalog_info.base_url = Some("https://api.openai.com/v1".into());
catalog_info.model_catalog_url = Some(format!("{destination}/models").into());
let catalog = OpenAiModelsEndpoint::new(
catalog_info,
Some(Arc::clone(&credentials)),
/*gateway_auth_manager*/ None,
)
.with_runtime_auth(Some((Arc::clone(&runtime), mode)));
let error = catalog
.list_models("0.0.0", factory.clone())
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("does not support this OpenAI endpoint")
);
}
// An explicitly configured other provider retains its existing bearer auth.
let info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
let provider = crate::provider::create_model_provider_with_runtime(
info,
Some(credentials),
Some((runtime, mode)),
);
let resolved = provider.request_auth(/*scope*/ None).await.unwrap();
let headers = resolved
.auth
.apply_auth_headers(http::HeaderMap::new())
.await
.unwrap();
assert_eq!(headers["authorization"], "Bearer key-a");
assert!(!headers.contains_key("x-openai-agent-assertion"));
assert!(server.received_requests().await.unwrap().is_empty());
}
}
#[tokio::test]
async fn catalog_timeout_keeps_registration_alive_for_the_next_request() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(6)).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a",
"agent_host_id": "host-a",
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":null},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/models"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[]})))
.expect(1)
.mount(&server)
.await;
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
let runtime = runtime_manager(&server, Arc::clone(&credentials));
let mut provider = ModelProviderInfo::create_openai_provider(Some(server.uri()));
provider.env_http_headers = None;
let endpoint = OpenAiModelsEndpoint::new(
provider,
Some(credentials),
/*gateway_auth_manager*/ None,
)
.with_runtime_auth(Some((runtime, RuntimeAuthMode::DualHeader)));
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
let result = timeout(
Duration::from_secs(10),
endpoint.list_models("0.0.0", factory.clone()),
)
.await
.expect("catalog timeout must precede the registration client's timeout");
assert!(matches!(
result.unwrap_err().details(),
codex_protocol::error::CodexErrorDetails::RequestTimeout
));
endpoint.list_models("0.0.0", factory).await.unwrap();
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests
.iter()
.filter(|request| request.url.path() == "/register")
.count(),
1
);
server.verify().await;
}
#[tokio::test]
async fn runtime_catalog_follows_redirects_without_forwarding_credentials_to_another_origin() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for policy in [
OutboundProxyPolicy::ReqwestDefault,
OutboundProxyPolicy::RespectSystemProxy,
] {
let server = MockServer::start().await;
let target = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a",
"agent_host_id": "host-a",
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":null},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/models"))
.respond_with(ResponseTemplate::new(307).insert_header("location", "/same-origin"))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/same-origin"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", format!("{}/models", target.uri())),
)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/models"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []})))
.expect(1)
.mount(&target)
.await;
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
let runtime = runtime_manager(&server, Arc::clone(&credentials));
let mut info = ModelProviderInfo::create_openai_provider(Some(server.uri()));
info.env_http_headers = None;
let endpoint = OpenAiModelsEndpoint::new(
info,
Some(credentials),
/*gateway_auth_manager*/ None,
)
.with_runtime_auth(Some((runtime, mode)));
endpoint
.list_models("test", HttpClientFactory::new(policy))
.await
.unwrap();
let requests = server.received_requests().await.unwrap();
let initial = requests
.iter()
.find(|request| request.url.path() == "/models")
.unwrap();
let same_origin = requests
.iter()
.find(|request| request.url.path() == "/same-origin")
.unwrap();
assert_eq!(
same_origin.headers.get("authorization"),
initial.headers.get("authorization")
);
assert_eq!(
same_origin.headers.get("x-openai-agent-assertion"),
initial.headers.get("x-openai-agent-assertion")
);
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(initial.headers["authorization"], "Bearer key-a");
assert!(initial.headers.contains_key("x-openai-agent-assertion"));
}
RuntimeAuthMode::AssertionOnly => {
assert!(
initial.headers["authorization"]
.to_str()
.unwrap()
.starts_with("AgentAssertion ")
);
assert!(!initial.headers.contains_key("x-openai-agent-assertion"));
}
}
let redirected = target.received_requests().await.unwrap();
assert_eq!(redirected.len(), 1);
assert!(!redirected[0].headers.contains_key("authorization"));
assert!(
!redirected[0]
.headers
.contains_key("x-openai-agent-assertion")
);
server.verify().await;
target.verify().await;
}
}
}
fn runtime_manager(server: &MockServer, credentials: Arc<AuthManager>) -> Arc<RuntimeAuthManager> {
Arc::new(RuntimeAuthManager::new(
credentials,
AgentHostAuthorization::InstallationId {
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
},
RuntimeRegistrationMetadata {
harness: None,
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/register", server.uri()).parse().unwrap(),
))
}

View File

@@ -62,56 +62,43 @@ impl ModelsTransportBuilder for CaptureModelsUrl {
}
#[tokio::test]
async fn api_key_discovery_respects_provider_routing() {
let client_version = codex_models_manager::client_version_to_whole();
for (api_key, name, base_url, models_url, inference_url) in [
(
"test-api-key",
"OpenAI",
None,
Some("https://chatgpt.com/backend-api/codex/models"),
"https://api.openai.com/v1",
),
async fn api_key_discovery_respects_provider_routing_and_never_uses_codex_backend() {
for (api_key, name, base_url, inference_url) in [
("test-api-key", "OpenAI", None, "https://api.openai.com/v1"),
(
"test-api-key",
"OpenAI",
Some("https://example.com/codex"),
None,
"https://example.com/codex",
),
(
"test-api-key",
"Azure",
Some("https://example.openai.azure.com/openai/v1"),
None,
"https://example.openai.azure.com/openai/v1",
),
(
"sk-proj-fedramp-synthetic-test-key",
"OpenAI",
None,
Some("https://gov.chatgpt.com/backend-api/codex/models"),
"https://gov.api.openai.com/v1",
),
(
"sk-svcacct-fedramp-synthetic-test-key",
"OpenAI",
None,
Some("https://gov.chatgpt.com/backend-api/codex/models"),
"https://gov.api.openai.com/v1",
),
(
"sk-proj-fedramp-synthetic-test-key",
"OpenAI",
Some("https://example.com/codex"),
None,
"https://example.com/codex",
),
(
"sk-svcacct-fedramp-synthetic-test-key",
"Azure",
None,
None,
"https://api.openai.com/v1",
),
] {
@@ -124,7 +111,6 @@ async fn api_key_discovery_respects_provider_routing() {
},
auth_manager: Some(auth.clone()),
gateway_auth_manager: None,
runtime_auth: None,
transport_builder: capture.clone(),
});
let provider = crate::provider::create_model_provider(
@@ -139,10 +125,8 @@ async fn api_key_discovery_respects_provider_routing() {
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await;
assert_eq!(
*capture.0.lock().unwrap(),
models_url.map(|url| format!("{url}?client_version={client_version}"))
);
// The default OpenAI provider never fetches a catalog from the Codex backend.
assert_eq!(*capture.0.lock().unwrap(), None);
assert_eq!(
provider.api_provider().await.unwrap().base_url,
inference_url
@@ -151,42 +135,22 @@ async fn api_key_discovery_respects_provider_routing() {
}
#[tokio::test]
async fn provider_api_key_without_endpoint_overrides_uses_codex_backend() {
for (api_key, auth, models_base_url, inference_url) in [
(
"provider-key",
None,
CHATGPT_CODEX_BASE_URL,
"https://api.openai.com/v1",
),
(
"provider-key",
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
CHATGPT_CODEX_BASE_URL,
CHATGPT_CODEX_BASE_URL,
),
async fn provider_api_key_without_endpoint_overrides_never_contacts_codex_backend() {
for (api_key, auth, inference_url) in [
("provider-key", None, "https://api.openai.com/v1"),
(
"provider-key",
Some(CodexAuth::from_api_key("sk-proj-fedramp-ambient-key")),
CHATGPT_CODEX_BASE_URL,
"https://api.openai.com/v1",
),
(
"sk-proj-fedramp-provider-key",
None,
"https://gov.chatgpt.com/backend-api/codex",
"https://gov.api.openai.com/v1",
),
(
"sk-svcacct-fedramp-provider-key",
Some(CodexAuth::from_api_key("legacy-ambient-key")),
"https://gov.chatgpt.com/backend-api/codex",
"https://gov.api.openai.com/v1",
),
(
"sk-proj-fedramp-provider-key",
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
"https://gov.chatgpt.com/backend-api/codex",
"https://gov.api.openai.com/v1",
),
] {
@@ -199,7 +163,6 @@ async fn provider_api_key_without_endpoint_overrides_uses_codex_backend() {
},
auth_manager: auth_manager.clone(),
gateway_auth_manager: None,
runtime_auth: None,
transport_builder: capture.clone(),
});
let provider = crate::provider::create_model_provider(
@@ -214,13 +177,7 @@ async fn provider_api_key_without_endpoint_overrides_uses_codex_backend() {
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await;
assert_eq!(
*capture.0.lock().unwrap(),
Some(format!(
"{models_base_url}/models?client_version={}",
codex_models_manager::client_version_to_whole(),
))
);
assert_eq!(*capture.0.lock().unwrap(), None);
assert_eq!(
provider.api_provider().await.unwrap().base_url,
inference_url
@@ -292,7 +249,6 @@ async fn model_request_uses_request_time_proxy_policy_and_exact_url() {
provider_info: ModelProviderInfo::create_openai_provider(Some(server.uri())),
auth_manager: None,
gateway_auth_manager: None,
runtime_auth: None,
transport_builder: Arc::new(RecordingTransportBuilder {
observed_request: Arc::clone(&observed_request),
}),
@@ -339,7 +295,6 @@ async fn model_discovery_enforces_managed_residency_over_provider_headers() {
provider_info,
auth_manager: None,
gateway_auth_manager: None,
runtime_auth: None,
transport_builder: Arc::new(RecordingTransportBuilder {
observed_request: Arc::new(Mutex::new(None)),
}),
@@ -484,7 +439,6 @@ async fn command_auth_refresh_fetches_a_catalog_for_the_current_credentials() {
#[tokio::test]
async fn explicit_catalog_reuses_auth_headers_and_query_parameters() {
for auth in [
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
CodexAuth::from_api_key("test-key"),
CodexAuth::from_api_key("sk-proj-fedramp-synthetic-test-key"),
CodexAuth::from_api_key("sk-svcacct-fedramp-synthetic-test-key"),

View File

@@ -1,7 +1,5 @@
//! Model catalog cache identity follows provider routing, effective auth, and gateway OAuth config.
//! Only a digest is persisted; access tokens for ChatGPT are excluded so token
//! rotation does not discard a catalog for the same account, user, and plan.
//! Header auth with an account ID uses that identity instead of opaque auth headers.
//! Only a digest is persisted, so credentials never reach the cache on disk.
use codex_login::CodexAuth;
use codex_model_provider_info::ModelProviderInfo;
@@ -50,45 +48,14 @@ pub(crate) fn identity(
field(&[u8::from(provider_info.has_command_auth())]);
field(format!("{:?}", auth.map(CodexAuth::api_auth_mode)).as_bytes());
if let Some(auth) = auth {
field(format!("{:?}", auth.get_account_id()).as_bytes());
field(format!("{:?}", auth.get_chatgpt_user_id()).as_bytes());
field(format!("{:?}", auth.get_account_email()).as_bytes());
field(format!("{:?}", auth.account_plan_type()).as_bytes());
field(
format!(
"{:?}",
auth.get_token_data()
.ok()
.and_then(|tokens| tokens.id_token.get_chatgpt_plan_type_raw())
)
.as_bytes(),
);
field(&[u8::from(auth.is_fedramp_account())]);
}
let has_stable_account = auth.is_some_and(|auth| {
auth.get_account_id().is_some()
&& if matches!(auth, CodexAuth::Headers(_)) {
!provider_info.has_command_auth()
} else {
matches!(
auth,
CodexAuth::Chatgpt(_)
| CodexAuth::ChatgptAuthTokens(_)
| CodexAuth::AgentIdentity(_)
) && (auth.get_chatgpt_user_id().is_some() || auth.get_account_email().is_some())
}
});
let explicit_bearer =
provider_info.api_key()?.is_some() || provider_info.experimental_bearer_token.is_some();
// Command auth also returns opaque API keys. A changed key may belong to a
// different account, so reuse requires stable owner metadata. Explicit provider
// keys take precedence over the header auth's account identity.
if !has_stable_account || explicit_bearer {
let headers = resolve_provider_auth(auth, provider_info)?
.to_auth_headers()
.map_err(|error| codex_api::map_api_error(error.into()))?;
api_provider.headers.extend(headers);
}
// Credentials carry no stable account identity, so the request auth headers
// themselves key the catalog. A changed key may belong to a different account.
let headers = resolve_provider_auth(auth, provider_info)?
.to_auth_headers()
.map_err(|error| codex_api::map_api_error(error.into()))?;
api_provider.headers.extend(headers);
let mut headers: Vec<_> = api_provider.headers.iter().collect();
headers.sort_by(|(a, av), (b, bv)| {
a.as_str()

View File

@@ -1,42 +1,30 @@
//! Provider and authentication dimensions that partition model catalogs.
use super::*;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use pretty_assertions::assert_eq;
fn chatgpt_auth(email: &str, user: &str, account: &str, plan: &str, signature: &str) -> CodexAuth {
let claims = serde_json::json!({
"email": email,
"https://api.openai.com/auth": {"chatgpt_user_id": user}
});
let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
CodexAuth::from_external_chatgpt_tokens(
&format!("e30.{payload}.{signature}"),
account,
Some(plan),
)
.unwrap()
}
#[test]
fn cache_identity_tracks_account_email_user_plan_and_auth_mode_but_not_token_refresh() {
fn cache_identity_tracks_credential_kind_and_value() {
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
// The endpoint residency test temporarily sets the process default to US.
provider.http_headers = Some(std::collections::HashMap::from([(
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
"us".into(),
)]));
let initial = chatgpt_auth("one@example.com", "user", "account", "team", "first");
let initial = CodexAuth::from_api_key("api-key");
let key = identity(&provider, Some(&initial)).unwrap();
let refreshed = chatgpt_auth("one@example.com", "user", "account", "team", "second");
assert_eq!(identity(&provider, Some(&refreshed)).unwrap(), key);
assert_eq!(
identity(&provider, Some(&CodexAuth::from_api_key("api-key"))).unwrap(),
key
);
for auth in [
chatgpt_auth("two@example.com", "user", "account", "team", "first"),
chatgpt_auth("one@example.com", "other", "account", "team", "first"),
chatgpt_auth("one@example.com", "user", "other", "team", "first"),
chatgpt_auth("one@example.com", "user", "account", "plus", "first"),
CodexAuth::from_api_key("api-key"),
CodexAuth::from_api_key("rotated-api-key"),
CodexAuth::Headers(codex_login::AuthHeaders::new(http::HeaderMap::from_iter([
(
http::header::AUTHORIZATION,
http::HeaderValue::from_static("Bearer api-key"),
),
]))),
] {
assert_ne!(identity(&provider, Some(&auth)).unwrap(), key);
}
@@ -77,27 +65,13 @@ fn cache_identity_tracks_provider_routing_and_effective_api_credentials() {
}
#[test]
fn cache_identity_distinguishes_auth_requirements_and_unknown_plans() {
fn cache_identity_distinguishes_auth_requirements() {
let mut provider =
ModelProviderInfo::create_openai_provider(Some("https://example.com/v1".into()));
let first = chatgpt_auth(
"one@example.com",
"user",
"account",
"future-plan-one",
"first",
);
let second = chatgpt_auth(
"one@example.com",
"user",
"account",
"future-plan-two",
"first",
);
let key = identity(&provider, Some(&first)).unwrap();
assert_ne!(key, identity(&provider, Some(&second)).unwrap());
let auth = CodexAuth::from_api_key("api-key");
let key = identity(&provider, Some(&auth)).unwrap();
provider.requires_openai_auth = false;
assert_ne!(key, identity(&provider, Some(&first)).unwrap());
assert_ne!(key, identity(&provider, Some(&auth)).unwrap());
}
#[test]
@@ -127,7 +101,7 @@ fn provider_key_catalog_identity_does_not_depend_on_unused_login() {
provider.experimental_bearer_token = Some("provider-key".into());
let identity_without_login = identity(&provider, /*auth*/ None).unwrap();
let selected_key = CodexAuth::from_api_key("provider-key");
let unused_login = chatgpt_auth("user@example.com", "user", "workspace", "team", "token");
let unused_login = CodexAuth::from_api_key("unused-login-key");
for auth in [&selected_key, &unused_login] {
assert_eq!(
identity(&provider, Some(auth)).unwrap(),

View File

@@ -98,6 +98,7 @@ async fn originator_catalogs_are_isolated_and_reused_from_disk() {
let server = MockServer::start().await;
let home = tempfile::tempdir().unwrap();
let mut provider = ModelProviderInfo::create_openai_provider(Some(server.uri()));
provider.model_catalog_url = Some(format!("{}/models", server.uri()).into());
// The managed-residency test toggles the process-wide US policy. Keep this
// provider's cache identity stable whether that policy is enabled or disabled.
provider.http_headers = Some(std::collections::HashMap::from([
@@ -134,14 +135,14 @@ async fn originator_catalogs_are_isolated_and_reused_from_disk() {
}
let client = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
for _ in 0..2 {
let auth =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
provider.clone(),
Some(Arc::clone(&auth)),
/*gateway_auth_manager*/ None,
));
let manager = OpenAiModelsManager::new(home.path().to_path_buf(), endpoint, Some(auth));
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
let work = manager.for_originator("codex_work_cca").unwrap();
let chat = manager.for_originator("chatgpt_cca").unwrap();
assert!(Arc::ptr_eq(

View File

@@ -9,11 +9,8 @@ use codex_api::ApiError;
use codex_api::Provider;
use codex_api::SharedAuthProvider;
use codex_api::TransportError;
use codex_features::RuntimeAuthMode;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::WorkspaceRoutingRequest;
use codex_login::default_client::ClientRedirectPolicy;
use codex_model_provider_info::ModelProviderInfo;
use codex_models_manager::cache::ModelsCache;
use codex_models_manager::manager::ModelCatalogSettings;
@@ -21,25 +18,19 @@ use codex_models_manager::manager::OpenAiModelsManager;
use codex_models_manager::manager::SharedModelsManager;
use codex_models_manager::manager::StaticModelsManager;
use codex_protocol::account::ProviderAccount;
use codex_protocol::auth::RefreshTokenFailedError;
use codex_protocol::error::CodexErr;
use codex_protocol::openai_models::ModelsResponse;
use codex_runtime_agent_instance::RuntimeAuthManager;
use crate::ProviderCapabilities;
use crate::ResolvedResponsesProvider;
use crate::amazon_bedrock::AmazonBedrockModelProvider;
use crate::auth::ProviderAuthScope;
use crate::auth::ResolvedProviderAuth;
use crate::auth::auth_manager_for_provider;
use crate::auth::resolve_provider_auth;
use crate::auth::resolve_provider_auth_for_scope;
use crate::auth::uses_fedramp_api_key;
use crate::combined_auth::compose_auth;
use crate::gcp::GcpModelProvider;
use crate::models_endpoint::OpenAiModelsEndpoint;
use crate::request_setup::resolve_request_auth;
use crate::workspace_routing::WorkspaceRoutingContext;
/// Current app-visible account state for a model provider.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -67,16 +58,12 @@ pub struct ProviderAuthRecoveryMessages {
/// Error returned when a provider cannot construct its app-visible account state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProviderAccountError {
MissingChatgptAccountDetails,
UnsupportedBedrockApiKeyAuth,
}
impl fmt::Display for ProviderAccountError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingChatgptAccountDetails => {
write!(f, "plan type is required for chatgpt authentication")
}
Self::UnsupportedBedrockApiKeyAuth => {
write!(
f,
@@ -113,13 +100,8 @@ pub const DEFAULT_MEMORY_CONSOLIDATION_PREFERRED_MODEL: &str = "gpt-6.1-terra";
/// `ModelProviderInfo` returned by `info` is the serialized/configured provider
/// metadata used by the default OpenAI-compatible implementation.
///
/// OpenAI-compatible catalog caches use header auth's account ID instead of auth
/// headers when available. Missing IDs and explicit provider API key, bearer, or
/// command auth retain credential-sensitive keys. Provider settings remain in the key.
/// Hosts using header auth must isolate model managers and cache storage by user and
/// catalog-varying request context, such as country: an account ID may identify a
/// workspace shared by multiple users. Request authentication, credential refresh,
/// and permission checks are unchanged.
/// OpenAI-compatible catalog caches are keyed by provider settings and the request
/// credentials, so a changed credential never reuses another principal's catalog.
pub trait ModelProvider: fmt::Debug + Send + Sync {
/// Returns the configured provider metadata.
fn info(&self) -> &ModelProviderInfo;
@@ -129,9 +111,7 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
self.info().include_internal_metadata
|| url::Url::parse(&provider.base_url).ok().is_some_and(|url| {
url.scheme() == "https"
&& url.host_str().is_some_and(|host| {
host == "api.openai.com" || codex_http_client::is_allowed_chatgpt_host(host)
})
&& url.host_str() == Some("api.openai.com")
})
}
@@ -161,11 +141,6 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
DEFAULT_MEMORY_CONSOLIDATION_PREFERRED_MODEL
}
/// Returns whether requests made through this provider should include attestation.
fn supports_attestation(&self) -> bool {
false
}
/// Returns the provider-scoped auth manager, when this provider uses one.
///
/// TODO(celia-oai): Make auth manager access internal to this crate so callers
@@ -174,11 +149,6 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
/// manager throughout the codebase; that is a larger refactor than this change.
fn auth_manager(&self) -> Option<Arc<AuthManager>>;
/// Runtime authentication selected for this provider's inference destination.
fn runtime_auth(&self) -> Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)> {
None
}
/// Returns the gateway credential manager shared with inference and model discovery.
/// Hosts use this handle for explicit login; configured setup failures remain errors.
fn gateway_auth_manager(&self) -> std::io::Result<Option<Arc<GatewayAuthManager>>> {
@@ -227,66 +197,6 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
})
}
/// Resolves routing for Responses HTTP, compaction, and WebSocket handshakes.
fn responses_api_provider<'a>(
&'a self,
routing_context: &'a WorkspaceRoutingContext,
) -> ModelProviderFuture<'a, codex_protocol::error::Result<ResolvedResponsesProvider>> {
Box::pin(async move {
let provider = self.api_provider().await?;
let auth = self.auth().await;
self.route_responses_api_provider(provider, auth.as_ref(), routing_context)
.await
})
}
/// Applies workspace routing using the credentials already selected for this request.
#[expect(
clippy::await_holding_invalid_type,
reason = "serialize discovery and the session's first successful routing transition"
)]
fn route_responses_api_provider<'a>(
&'a self,
mut provider: Provider,
auth: Option<&'a CodexAuth>,
routing_context: &'a WorkspaceRoutingContext,
) -> ModelProviderFuture<'a, codex_protocol::error::Result<ResolvedResponsesProvider>> {
Box::pin(async move {
let mut redirect_policy = ClientRedirectPolicy::Default;
if provider_uses_first_party_auth_path(self.info())
&& self.info().supports_codex_backend_routes()
&& let Some(auth) = auth.filter(|auth| auth.is_chatgpt_auth())
&& let Some(auth_manager) = self.auth_manager()
{
let mut previously_routed = routing_context.previously_routed.lock().await;
if let Some(routing) = auth_manager
.workspace_routing(
auth,
WorkspaceRoutingRequest {
provider_base_url: provider.base_url.clone(),
chatgpt_base_url: routing_context.chatgpt_base_url.clone(),
previously_routed: *previously_routed,
session: routing_context.session.clone(),
},
)
.await
.map_err(|error| match error.downcast::<RefreshTokenFailedError>() {
Ok(rejection) => CodexErr::RefreshTokenFailed(rejection),
Err(error) => error.into(),
})?
{
crate::workspace_routing::apply_workspace_routing(&mut provider, routing)?;
redirect_policy = ClientRedirectPolicy::Reject;
*previously_routed = true;
}
}
Ok(ResolvedResponsesProvider {
provider,
redirect_policy,
})
})
}
/// Adapt routing from the same frozen credential selected for the request.
fn api_provider_for_auth(
&self,
@@ -320,39 +230,19 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
Box::pin(async move { Ok(resolved) })
}
/// Returns request credentials, optionally scoped to a Codex session task.
fn api_auth_for_scope(
&self,
scope: ProviderAuthScope,
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
Box::pin(async move {
if !provider_uses_first_party_auth_path(self.info()) {
return self.api_auth().await.map(ResolvedProviderAuth::new);
}
let auth = self.auth().await;
resolve_provider_auth_for_scope(self.auth_manager(), auth.as_ref(), self.info(), scope)
.await
})
}
/// Resolve auth together with metadata needed to route and admit this request.
fn request_auth(
&self,
scope: Option<ProviderAuthScope>,
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
match scope {
Some(scope) => self.api_auth_for_scope(scope),
None => Box::pin(async { self.api_auth().await.map(ResolvedProviderAuth::new) }),
}
Box::pin(async { self.api_auth().await.map(ResolvedProviderAuth::new) })
}
/// Resolve the endpoint before headers for providers whose setup may refresh credentials.
fn request_provider_and_auth(
&self,
scope: Option<ProviderAuthScope>,
) -> ModelProviderFuture<'_, codex_protocol::error::Result<(Provider, ResolvedProviderAuth)>>
{
Box::pin(async move { Ok((self.api_provider().await?, self.request_auth(scope).await?)) })
Box::pin(async move { Ok((self.api_provider().await?, self.request_auth().await?)) })
}
/// Creates the model manager implementation appropriate for this provider.
@@ -420,14 +310,16 @@ pub fn resolve_api_provider(
info: &ModelProviderInfo,
auth: Option<&CodexAuth>,
) -> codex_protocol::error::Result<Provider> {
let mut provider = info.to_api_provider(auth.map(CodexAuth::auth_mode))?;
let mut provider = info.to_api_provider()?;
if info.base_url.is_none() && uses_fedramp_api_key(auth, info)? {
provider.base_url = FEDRAMP_API_BASE_URL.to_string();
}
Ok(provider)
}
pub fn provider_uses_first_party_auth_path(provider: &ModelProviderInfo) -> bool {
/// Whether requests use the credential stored by `codex login --with-api-key` (or supplied
/// by a host) rather than provider-owned env, bearer, command, or AWS credentials.
pub fn provider_uses_stored_auth(provider: &ModelProviderInfo) -> bool {
provider.requires_openai_auth
&& provider.env_key.is_none()
&& provider.experimental_bearer_token.is_none()
@@ -436,18 +328,9 @@ pub fn provider_uses_first_party_auth_path(provider: &ModelProviderInfo) -> bool
}
/// Creates the default model provider for configured provider metadata.
/// Harnesses with runtime identity use [`crate::ProviderAuthContext::model_provider`].
pub fn create_model_provider(
provider_info: ModelProviderInfo,
auth_manager: Option<Arc<AuthManager>>,
) -> SharedModelProvider {
create_model_provider_with_runtime(provider_info, auth_manager, /*runtime_auth*/ None)
}
pub(crate) fn create_model_provider_with_runtime(
provider_info: ModelProviderInfo,
auth_manager: Option<Arc<AuthManager>>,
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> SharedModelProvider {
if provider_info.is_amazon_bedrock() {
return Arc::new(AmazonBedrockModelProvider::new(provider_info, auth_manager));
@@ -455,11 +338,7 @@ pub(crate) fn create_model_provider_with_runtime(
if provider_info.is_gcp() {
return Arc::new(GcpModelProvider::new(provider_info, auth_manager));
}
Arc::new(ConfiguredModelProvider::new(
provider_info,
auth_manager,
runtime_auth,
))
Arc::new(ConfiguredModelProvider::new(provider_info, auth_manager))
}
/// Runtime model provider that orchestrates primary and gateway credentials.
@@ -469,16 +348,10 @@ struct ConfiguredModelProvider {
auth_manager: Option<Arc<AuthManager>>,
// Construct eagerly; report setup failures when auth is requested because the factory is infallible.
gateway_auth_manager: Option<Result<Arc<GatewayAuthManager>, String>>,
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
catalog_runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
}
impl ConfiguredModelProvider {
fn new(
info: ModelProviderInfo,
auth_manager: Option<Arc<AuthManager>>,
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> Self {
fn new(info: ModelProviderInfo, auth_manager: Option<Arc<AuthManager>>) -> Self {
let gateway_auth_manager = info.gateway_oauth.as_ref().map(|config| {
info.validate()?;
let manager = auth_manager
@@ -487,63 +360,20 @@ impl ConfiguredModelProvider {
GatewayAuthManager::new(&info, config, manager).map(Arc::new)
});
let auth_manager = auth_manager_for_provider(auth_manager, &info);
let runtime_for_destination = |destination: Option<&str>| {
runtime_auth.clone().filter(|_| {
destination.is_none_or(|url| {
codex_http_client::classify_openai_api_url(url)
!= codex_http_client::OpenAiDestination::Other
})
})
};
let inference_runtime_auth = runtime_for_destination(info.base_url.as_deref());
// Catalog overrides are absolute URLs and can have a different origin from inference.
let catalog_runtime_auth = runtime_for_destination(
info.model_catalog_url
.as_deref()
.map(String::as_str)
.or(info.base_url.as_deref()),
);
Self {
info,
auth_manager,
gateway_auth_manager,
runtime_auth: inference_runtime_auth,
catalog_runtime_auth,
}
}
async fn resolve_auth(
&self,
scope: Option<ProviderAuthScope>,
) -> codex_protocol::error::Result<ResolvedProviderAuth> {
let resolved = resolve_request_auth(
self.info.clone(),
self.auth_manager.clone(),
self.runtime_auth.clone(),
scope,
self.info.base_url.clone(),
)
.await?;
async fn resolve_auth(&self) -> codex_protocol::error::Result<ResolvedProviderAuth> {
let resolved = resolve_request_auth(self.info.clone(), self.auth_manager.clone()).await?;
self.compose_auth(resolved).await
}
}
impl ModelProvider for ConfiguredModelProvider {
fn is_recoverable_auth_error(&self, error: &TransportError) -> bool {
let TransportError::Http { status, body, .. } = error else {
return false;
};
*status == http::StatusCode::UNAUTHORIZED
&& (self.runtime_auth.is_none()
|| !codex_protocol::error::is_runtime_auth_denial(
*status,
body.as_deref().unwrap_or_default(),
codex_response_debug_context::extract_response_debug_context(error)
.auth_error_code
.as_deref(),
))
}
fn info(&self) -> &ModelProviderInfo {
&self.info
}
@@ -587,13 +417,6 @@ impl ModelProvider for ConfiguredModelProvider {
})
}
fn supports_attestation(&self) -> bool {
self.auth_manager
.as_ref()
.and_then(|auth_manager| auth_manager.auth_cached())
.is_some_and(|auth| auth.is_chatgpt_auth())
}
fn auth(&self) -> ModelProviderFuture<'_, Option<CodexAuth>> {
Box::pin(async move {
match self.auth_manager.as_ref() {
@@ -603,24 +426,18 @@ impl ModelProvider for ConfiguredModelProvider {
})
}
fn runtime_auth(&self) -> Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)> {
self.runtime_auth.as_ref()
}
fn request_auth(
&self,
scope: Option<ProviderAuthScope>,
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
Box::pin(self.resolve_auth(scope))
Box::pin(self.resolve_auth())
}
fn request_provider_and_auth(
&self,
scope: Option<ProviderAuthScope>,
) -> ModelProviderFuture<'_, codex_protocol::error::Result<(Provider, ResolvedProviderAuth)>>
{
Box::pin(async move {
let resolved = self.resolve_auth(scope).await?;
let resolved = self.resolve_auth().await?;
let provider = self.api_provider_for_auth(resolved.credential.as_ref())?;
Ok((provider, resolved))
})
@@ -630,7 +447,7 @@ impl ModelProvider for ConfiguredModelProvider {
&self,
) -> ModelProviderFuture<'_, codex_protocol::error::Result<SharedAuthProvider>> {
Box::pin(async move {
Ok(self.resolve_auth(/*scope*/ None).await?.auth)
Ok(self.resolve_auth().await?.auth)
})
}
@@ -645,13 +462,6 @@ impl ModelProvider for ConfiguredModelProvider {
))
}
fn api_auth_for_scope(
&self,
scope: ProviderAuthScope,
) -> ModelProviderFuture<'_, codex_protocol::error::Result<ResolvedProviderAuth>> {
Box::pin(self.resolve_auth(Some(scope)))
}
fn account_state(&self) -> ProviderAccountResult {
let account = if self.info.requires_openai_auth {
self.auth_manager
@@ -671,17 +481,8 @@ impl ModelProvider for ConfiguredModelProvider {
CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_) => {
Err(ProviderAccountError::UnsupportedBedrockApiKeyAuth)
}
CodexAuth::Chatgpt(_)
| CodexAuth::ChatgptAuthTokens(_)
| CodexAuth::Headers(_)
| CodexAuth::AgentIdentity(_)
| CodexAuth::PersonalAccessToken(_) => {
let email = auth.get_account_email();
let plan_type = auth.account_plan_type();
plan_type
.map(|plan_type| ProviderAccount::Chatgpt { email, plan_type })
.ok_or(ProviderAccountError::MissingChatgptAccountDetails)
CodexAuth::Headers(_) => {
unreachable!("header auth is filtered out above")
}
})
.transpose()?
@@ -718,14 +519,11 @@ impl ModelProvider for ConfiguredModelProvider {
codex_models_manager::ModelOrigin::ExplicitConfig,
));
}
let endpoint = Arc::new(
OpenAiModelsEndpoint::new(
self.info.clone(),
self.auth_manager.clone(),
self.gateway_auth_manager.clone(),
)
.with_runtime_auth(self.catalog_runtime_auth.clone()),
);
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
self.info.clone(),
self.auth_manager.clone(),
self.gateway_auth_manager.clone(),
));
let auth_manager = self.auth_manager.clone();
let manager = OpenAiModelsManager::with_settings(settings, endpoint, auth_manager);
match &self.info.model_catalog_url {
@@ -753,23 +551,6 @@ impl ModelProvider for ConfiguredModelProvider {
}
}
pub(crate) mod test_support {
use super::*;
/// Use an injected runtime with a local transport fixture. Production callers use the
/// destination-aware `ProviderAuthContext::model_provider` factory.
pub fn runtime_model_provider(
info: ModelProviderInfo,
credentials: Arc<AuthManager>,
runtime: (Arc<RuntimeAuthManager>, RuntimeAuthMode),
) -> SharedModelProvider {
let mut provider =
ConfiguredModelProvider::new(info, Some(credentials), Some(runtime.clone()));
provider.runtime_auth = Some(runtime);
Arc::new(provider)
}
}
#[cfg(test)]
#[path = "provider_tests.rs"]
mod tests;

View File

@@ -9,7 +9,6 @@ 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;
@@ -18,11 +17,9 @@ use codex_model_provider_info::WireApi;
use codex_model_provider_info::create_oss_provider_with_base_url;
use codex_models_manager::ModelsManagerConfig;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::account::PlanType;
use codex_protocol::config_types::ModelProviderAuthInfo;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::protocol::SessionSource;
use codex_utils_redacted_string::RedactedString;
use pretty_assertions::assert_eq;
use serde_json::json;
@@ -35,7 +32,6 @@ use wiremock::matchers::path;
use super::*;
use crate::RemoteCompactionSupport;
use crate::auth::AgentIdentitySessionFallback;
use crate::shared_state::process_shared_state;
fn provider_info_with_command_auth() -> ModelProviderInfo {
@@ -121,20 +117,13 @@ fn bedrock_api_key_auth() -> CodexAuth {
}
#[tokio::test]
async fn scoped_auth_ignores_scope_for_non_openai_provider() {
async fn request_auth_adds_no_headers_for_non_openai_provider() {
let provider = create_model_provider(
create_oss_provider_with_base_url("http://localhost:11434/v1", WireApi::Responses),
/*auth_manager*/ None,
);
let auth = provider
.api_auth_for_scope(ProviderAuthScope {
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
session_source: SessionSource::Cli,
agent_identity_session_fallback: AgentIdentitySessionFallback::default(),
})
.await
.expect("auth should resolve");
let auth = provider.request_auth().await.expect("auth should resolve");
assert!(auth.auth.to_auth_headers().unwrap().is_empty());
}
@@ -216,12 +205,12 @@ fn configured_provider_uses_luna_for_approval_review_with_api_key_auth() {
}
#[test]
fn configured_provider_uses_default_approval_review_model_with_chatgpt_auth() {
fn configured_provider_uses_default_approval_review_model_with_header_auth() {
let provider = create_model_provider(
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
Some(AuthManager::from_auth_for_testing(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
)),
Some(AuthManager::from_auth_for_testing(CodexAuth::Headers(
codex_login::AuthHeaders::new(http::HeaderMap::new()),
))),
);
assert_eq!(
@@ -268,7 +257,7 @@ async fn configured_provider_resolves_default_and_explicit_endpoints() {
);
assert_eq!(
provider
.request_provider_and_auth(/*scope*/ None)
.request_provider_and_auth()
.await
.unwrap()
.0
@@ -301,10 +290,7 @@ async fn configured_provider_resolves_default_and_explicit_endpoints() {
)
.unwrap();
auth.reload().await;
let (api_provider, resolved) = provider
.request_provider_and_auth(/*scope*/ None)
.await
.unwrap();
let (api_provider, resolved) = provider.request_provider_and_auth().await.unwrap();
assert_eq!(api_provider.base_url, expected_base_url);
let headers = resolved.auth.to_auth_headers().unwrap();
assert_eq!(
@@ -326,10 +312,7 @@ async fn configured_provider_resolves_default_and_explicit_endpoints() {
("commercial-key", "https://api.openai.com/v1", None),
] {
let reads_before = rotating_auth.0.load(Ordering::SeqCst);
let (api_provider, resolved) = provider
.request_provider_and_auth(/*scope*/ None)
.await
.unwrap();
let (api_provider, resolved) = provider.request_provider_and_auth().await.unwrap();
assert_eq!(rotating_auth.0.load(Ordering::SeqCst), reads_before + 1);
let headers = resolved.auth.to_auth_headers().unwrap();
let expected_authorization = format!("Bearer {api_key}");
@@ -663,21 +646,18 @@ fn openai_provider_returns_api_key_account_state() {
}
#[test]
fn openai_provider_returns_chatgpt_account_state_without_email() {
fn openai_provider_returns_no_account_state_for_header_auth() {
let provider = create_model_provider(
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
Some(AuthManager::from_auth_for_testing(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
)),
Some(AuthManager::from_auth_for_testing(CodexAuth::Headers(
codex_login::AuthHeaders::new(http::HeaderMap::new()),
))),
);
assert_eq!(
provider.account_state(),
Ok(ProviderAccountState {
account: Some(ProviderAccount::Chatgpt {
email: None,
plan_type: PlanType::Unknown,
}),
account: None,
requires_openai_auth: true,
})
);
@@ -907,10 +887,7 @@ async fn configured_provider_models_manager_uses_provider_bearer_token() {
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
"us".into(),
)]));
for auth in [
None,
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
] {
for auth in [None, Some(CodexAuth::from_api_key("unused-login-key"))] {
// Disabled discovery must ignore the catalog cached by the enabled run.
for enabled in [true, false] {
let provider = create_model_provider(

View File

@@ -1,26 +1,16 @@
use super::prepare_provider_request;
use crate::create_model_provider;
use crate::provider_uses_first_party_auth_path;
use base64::Engine;
use crate::provider_uses_stored_auth;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_model_provider_info::ModelProviderInfo;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
#[tokio::test]
async fn explicit_provider_token_survives_a_workspace_switch_during_setup() {
async fn explicit_provider_token_survives_a_stored_credential_switch_during_setup() {
let home = TempDir::new().unwrap();
let claims = json!({"https://api.openai.com/auth": {"chatgpt_user_id": "user-a"}});
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
let token = format!("header.{payload}.signature");
let initial = CodexAuth::from_external_chatgpt_tokens(
&token,
"workspace-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let initial = CodexAuth::from_api_key("stored-key-a");
let manager = AuthManager::from_auth_for_testing_with_home(initial, home.path().to_path_buf());
let mut info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
info.experimental_bearer_token = Some("provider-token".into());
@@ -29,16 +19,16 @@ async fn explicit_provider_token_survives_a_workspace_switch_during_setup() {
let mut attempts = 0;
let resolved = prepare_provider_request(
provider.as_ref(),
provider_uses_first_party_auth_path(provider.info()),
provider_uses_stored_auth(provider.info()),
|_| {
attempts += 1;
async {
let (_, resolved) = provider.request_provider_and_auth(/*scope*/ None).await?;
codex_login::auth::login_with_chatgpt_auth_tokens(
let (_, resolved) = provider.request_provider_and_auth().await?;
codex_login::login_with_api_key(
home.path(),
&token,
"workspace-b",
/*chatgpt_plan_type*/ None,
"stored-key-b",
codex_login::AuthCredentialsStoreMode::File,
codex_login::AuthKeyringBackendKind::default(),
)?;
manager.reload().await;
Ok(resolved)
@@ -49,8 +39,8 @@ async fn explicit_provider_token_survives_a_workspace_switch_during_setup() {
.unwrap();
assert_eq!(
manager.auth_cached().unwrap().get_account_id().as_deref(),
Some("workspace-b")
manager.auth_cached().unwrap().api_key(),
Some("stored-key-b")
);
assert_eq!(attempts, 1);
let mut headers = http::HeaderMap::new();

View File

@@ -1,17 +1,12 @@
//! Resolve credentials, routing, and transport policy as one request context.
//! Resolve credentials and transport policy as one request context.
use crate::ModelProvider;
use crate::ProviderAuthScope;
use crate::ResolvedProviderAuth;
use crate::WorkspaceRoutingContext;
use crate::auth::bearer_auth_for_provider;
use crate::auth::resolve_provider_auth;
use crate::auth::resolve_provider_auth_for_scope;
use codex_api::AgentIdentityTelemetry;
use codex_api::Provider;
use codex_api::ReqwestTransport;
use codex_api::SharedAuthProvider;
use codex_features::RuntimeAuthMode;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
@@ -22,8 +17,6 @@ use codex_login::default_client::create_client_for_route;
use codex_model_provider_info::GatewayOAuthConfig;
use codex_model_provider_info::ModelProviderInfo;
use codex_protocol::error::Result;
use codex_runtime_agent_instance::RuntimeAuth;
use codex_runtime_agent_instance::RuntimeAuthManager;
use std::sync::Arc;
/// Select auth for inference and discovery, letting rotating credentials finish saving
@@ -31,55 +24,23 @@ use std::sync::Arc;
pub(crate) async fn resolve_request_auth(
info: ModelProviderInfo,
manager: Option<Arc<AuthManager>>,
runtime: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
scope: Option<ProviderAuthScope>,
destination: Option<String>,
) -> codex_protocol::error::Result<ResolvedProviderAuth> {
tokio::spawn(async move {
crate::auth::observe_auth_selection(
runtime.as_ref().map(|(_, mode)| *mode),
"model",
async move {
if let Some((runtime, mode)) = runtime {
crate::validate_runtime_destination(destination.as_deref())?;
crate::validate_runtime_environment(&runtime, destination.as_deref())?;
let runtime =
crate::select_runtime_provider(&info, manager.as_ref(), &runtime)?;
let headers = info.build_header_map()?;
let selected =
crate::runtime_auth::select_runtime_auth(&runtime, &headers).await?;
let resolved = ResolvedProviderAuth::for_runtime(selected, mode);
resolved.validate_headers(&headers)?;
tracing::debug!(runtime_auth_mode = ?mode, "selected runtime authentication");
return Ok(resolved);
}
if let Some(bearer) = bearer_auth_for_provider(&info)? {
let credential = bearer.token.as_deref().map(CodexAuth::from_api_key);
let mut resolved = ResolvedProviderAuth::new(Arc::new(bearer));
resolved.credential = credential;
return Ok(resolved);
}
if let Some(bearer) = bearer_auth_for_provider(&info)? {
let credential = bearer.token.as_deref().map(CodexAuth::from_api_key);
let mut resolved = ResolvedProviderAuth::new(Arc::new(bearer));
resolved.credential = credential;
return Ok(resolved);
}
let credential = match &manager {
Some(manager) => manager.auth().await,
None => None,
};
let mut resolved = match scope {
Some(scope) if crate::provider_uses_first_party_auth_path(&info) => {
resolve_provider_auth_for_scope(manager, credential.as_ref(), &info, scope)
.await?
}
_ => ResolvedProviderAuth::new(resolve_provider_auth(
credential.as_ref(),
&info,
)?),
};
resolved.credential = credential;
Ok(resolved)
},
)
.await
let credential = match &manager {
Some(manager) => manager.auth().await,
None => None,
};
let mut resolved =
ResolvedProviderAuth::new(resolve_provider_auth(credential.as_ref(), &info)?);
resolved.credential = credential;
Ok(resolved)
})
.await?
}
@@ -87,15 +48,9 @@ pub(crate) async fn resolve_request_auth(
/// Capture the selected source's owner before starting work such as a turn or classification.
/// Request preparation returns the owner it actually used so callers can detect a source change.
pub fn request_auth_owner(provider: &dyn ModelProvider) -> Option<AuthOwner> {
let credentials = provider.auth_manager();
match provider.runtime_auth() {
Some((runtime, _)) => {
crate::select_runtime_provider(provider.info(), credentials.as_ref(), runtime)
.ok()
.map(|binding| binding.auth_owner())
}
None => credentials.map(|manager| manager.auth_owner()),
}
provider
.auth_manager()
.map(|manager| manager.auth_owner())
}
pub struct ResolvedProviderRequest {
@@ -105,22 +60,12 @@ pub struct ResolvedProviderRequest {
pub api_provider: Provider,
pub redirect_policy: ClientRedirectPolicy,
pub api_auth: SharedAuthProvider,
pub agent_identity_telemetry: Option<AgentIdentityTelemetry>,
pub runtime_id: Option<String>,
pub http_client_factory: HttpClientFactory,
}
impl ResolvedProviderRequest {
pub fn http_transport(&self, endpoint: &str) -> Result<ReqwestTransport> {
let redirect_policy = if self
.api_provider
.headers
.contains_key(crate::ACCOUNT_ROUTING_HEADER)
{
ClientRedirectPolicy::Reject
} else {
self.redirect_policy
};
let redirect_policy = self.redirect_policy;
let request_url = self.api_provider.url_for_path(endpoint);
let client = create_client_for_route(
&self.http_client_factory,
@@ -133,60 +78,28 @@ impl ResolvedProviderRequest {
}
}
/// Resolve one attempt, including any workspace route, without mixing credential revisions.
/// The supplied factory retains the caller's proxy/TLS settings; runtime requests bind its
/// application policy to the same selected account used to sign the request.
/// Resolve one attempt without mixing credential revisions.
/// The supplied factory retains the caller's proxy/TLS settings.
pub async fn resolve_request(
provider: &dyn ModelProvider,
scope: Option<ProviderAuthScope>,
routing: Option<&WorkspaceRoutingContext>,
http_client_factory: HttpClientFactory,
) -> Result<ResolvedProviderRequest> {
let check_auth = provider.runtime_auth().is_none()
&& crate::provider_uses_first_party_auth_path(provider.info());
let check_auth = crate::provider_uses_stored_auth(provider.info());
crate::prepare_provider_request(provider, check_auth, |state| {
let scope = scope.clone();
let http_client_factory = http_client_factory.clone();
let owner = state
.and_then(|_| provider.auth_manager())
.map(|manager| manager.auth_owner());
async move {
let (api_provider, resolved_auth) = provider.request_provider_and_auth(scope).await?;
let (api_provider, resolved_auth) = provider.request_provider_and_auth().await?;
let auth = match &resolved_auth.credential {
Some(auth) => Some(auth.clone()),
None => provider.auth().await,
};
let (api_provider, redirect_policy) = match routing {
Some(routing) => {
let resolved = provider
.route_responses_api_provider(api_provider, auth.as_ref(), routing)
.await?;
(resolved.provider, resolved.redirect_policy)
}
None => (api_provider, ClientRedirectPolicy::Default),
};
resolved_auth.validate_headers(&api_provider.headers)?;
let runtime_state = resolved_auth
.runtime
.as_ref()
.map(RuntimeAuth::change_state);
let http_client_factory = resolved_auth
.bind_http_client_factory(http_client_factory)
.map_err(|error| provider.map_api_error(error.into()))?;
let runtime_id = resolved_auth
.runtime
.as_ref()
.map(|selected| selected.runtime().id().to_owned());
Ok(ResolvedProviderRequest {
auth,
auth_owner: resolved_auth
.runtime
.as_ref()
.map(|selected| selected.auth_owner().clone())
.or(owner),
auth_revision: runtime_state
.map(|state| state.generation)
.or(state.map(|state| state.generation)),
auth_owner: owner,
auth_revision: state.map(|state| state.generation),
api_provider,
redirect_policy: if provider
.info()
@@ -196,11 +109,9 @@ pub async fn resolve_request(
{
ClientRedirectPolicy::Reject
} else {
redirect_policy
ClientRedirectPolicy::Default
},
api_auth: resolved_auth.auth,
agent_identity_telemetry: resolved_auth.agent_identity_telemetry,
runtime_id,
http_client_factory,
})
}

View File

@@ -1,221 +0,0 @@
//! Keep model requests and catalog refreshes bound to the same registered actor.
use codex_api::AuthError;
use codex_features::RuntimeAuthMode;
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
use codex_http_client::OPENAI_ORGANIZATION_HEADER;
use codex_http_client::OPENAI_PROJECT_HEADER;
use codex_http_client::OpenAiDestination;
use codex_http_client::classify_openai_api_url;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_model_provider_info::ModelProviderInfo;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_runtime_agent_instance::ActorInfo;
use codex_runtime_agent_instance::PlatformResourceSelection;
use codex_runtime_agent_instance::RuntimeAuth;
use codex_runtime_agent_instance::RuntimeAuthBinding;
use codex_runtime_agent_instance::RuntimeAuthError;
use codex_runtime_agent_instance::RuntimeAuthManager;
use http::HeaderMap;
use std::sync::Arc;
/// Select the runtime for the resource scope carried by the model request.
pub(crate) async fn select_runtime_auth(
manager: &Arc<RuntimeAuthBinding>,
headers: &HeaderMap,
) -> CodexResult<RuntimeAuth> {
let selection = resource_selection(headers).map_err(map_runtime_auth_error)?;
manager
.auth_with_selection(&selection)
.await
.map_err(map_runtime_auth_error)
}
/// Select the request's resource scope while preserving captured credential ownership.
pub async fn select_runtime_auth_for(
binding: &Arc<RuntimeAuthBinding>,
auth: &CodexAuth,
headers: &HeaderMap,
) -> CodexResult<RuntimeAuth> {
let selection = resource_selection(headers).map_err(map_runtime_auth_error)?;
binding
.auth_for(auth, &selection)
.await
.map_err(map_runtime_auth_error)
}
fn map_runtime_auth_error(error: RuntimeAuthError) -> CodexErr {
match error {
RuntimeAuthError::RefreshTokenFailed(error) => CodexErr::RefreshTokenFailed(error),
error => codex_api::map_api_error(AuthError::from(error).into()),
}
}
/// Select fresh request auth without allowing a reusable client's source to change.
pub(crate) async fn select_runtime_auth_for_source(
manager: &Arc<RuntimeAuthBinding>,
source_generation: u64,
headers: &HeaderMap,
) -> Result<RuntimeAuth, AuthError> {
let manager = Arc::clone(manager);
let selection = resource_selection(headers)?;
finish_runtime_selection(
async move { manager.auth_for_source(source_generation, &selection).await },
)
.await
.map_err(AuthError::from)
}
// Once token rotation begins, let it finish persisting even if the request is cancelled.
pub(crate) async fn finish_runtime_selection(
selection: impl Future<Output = Result<RuntimeAuth, RuntimeAuthError>> + Send + 'static,
) -> Result<RuntimeAuth, RuntimeAuthError> {
tokio::spawn(selection).await?
}
pub(crate) fn resource_selection(
headers: &HeaderMap,
) -> Result<PlatformResourceSelection, RuntimeAuthError> {
let selector = |name| {
headers
.get(name)
.map(|value| {
value
.to_str()
.map(str::to_owned)
.map_err(|_| RuntimeAuthError::InvalidResourceSelection(name))
})
.transpose()
};
Ok(PlatformResourceSelection {
organization_id: selector(OPENAI_ORGANIZATION_HEADER)?,
project_id: selector(OPENAI_PROJECT_HEADER)?,
})
}
/// Use the credential selected by provider configuration, never an ambient actor's proof.
pub fn select_runtime_provider(
info: &ModelProviderInfo,
credentials: Option<&Arc<AuthManager>>,
runtime: &Arc<RuntimeAuthManager>,
) -> CodexResult<Arc<RuntimeAuthBinding>> {
let unsupported = || {
CodexErr::UnsupportedOperation(
"runtime auth requires the model provider's selected OpenAI credential".to_string(),
)
};
if info.aws.is_some() {
return Err(unsupported());
}
let credentials = credentials.ok_or_else(unsupported)?;
if let Some(bearer) = crate::auth::bearer_auth_for_provider(info)? {
let token = bearer.token.ok_or_else(unsupported)?;
return Ok(runtime.bind_api_key(&token, &credentials.runtime_config()));
}
if !info.requires_openai_auth && info.auth.is_none() {
return Err(unsupported());
}
Ok(runtime.bind(Arc::clone(credentials)))
}
/// An unrecognized OpenAI origin must not silently fall back to legacy auth.
pub fn validate_runtime_destination(destination: Option<&str>) -> CodexResult<()> {
if destination.is_some_and(|url| classify_openai_api_url(url) == OpenAiDestination::Unsupported)
{
return Err(CodexErr::UnsupportedOperation(
"runtime auth does not support this OpenAI endpoint".to_string(),
));
}
Ok(())
}
/// Do not send a provider's credentials to registration in another OpenAI environment.
pub fn validate_runtime_environment(
runtime: &RuntimeAuthManager,
destination: Option<&str>,
) -> CodexResult<()> {
let registration_url = runtime
.registration_url()
.map_err(|err| CodexErr::InvalidRequest(err.to_string()))?;
let registration_is_staging = match registration_url
.host_str()
.map(|host| host.trim_end_matches('.'))
{
Some("auth.openai.com") => false,
Some("auth.api.openai.org") => true,
// Explicit registration targets also support local test servers.
_ => return Ok(()),
};
let destination_is_staging = match destination {
Some(destination) => {
let destination = url::Url::parse(destination)
.map_err(|_| CodexErr::InvalidRequest("invalid runtime auth destination".into()))?;
let host = destination
.host_str()
.unwrap_or_default()
.trim_end_matches('.');
matches!(
host,
"api.openai.org" | "api.openai-staging.com" | "chatgpt-staging.com"
) || host.ends_with(".chatgpt-staging.com")
}
// Both implicit model-provider defaults use production.
None => false,
};
if registration_is_staging != destination_is_staging {
return Err(CodexErr::InvalidRequest(
"Requests must use the same production or staging environment as runtime registration"
.into(),
));
}
Ok(())
}
/// Select runtime auth for supported OpenAI URLs; reject unsupported OpenAI URLs.
pub fn runtime_auth_for_url<'a>(
runtime: Option<&'a (Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
url: &str,
) -> CodexResult<Option<&'a (Arc<RuntimeAuthManager>, RuntimeAuthMode)>> {
if runtime.is_some() {
validate_runtime_destination(Some(url))?;
}
let runtime = runtime.filter(|_| classify_openai_api_url(url) == OpenAiDestination::Supported);
if let Some((manager, _)) = runtime {
validate_runtime_environment(manager, Some(url))?;
}
Ok(runtime)
}
/// Account and organization selectors must agree with the registered actor.
/// API project access is authorized by the backend for each request.
pub fn validate_runtime_selectors(headers: &HeaderMap, actor: &ActorInfo) -> CodexResult<()> {
let validate = |name: &str, expected: Option<&str>| {
if let Some(value) = headers.get(name)
&& value.to_str().ok() != expected
{
return Err(CodexErr::UnsupportedOperation(format!(
"configured {name} does not match the registered runtime"
)));
}
Ok(())
};
match actor {
ActorInfo::Chatgpt { account_id, .. } => {
validate(CHATGPT_ACCOUNT_ID_HEADER, Some(account_id))?;
validate(OPENAI_ORGANIZATION_HEADER, None)?;
validate(OPENAI_PROJECT_HEADER, None)
}
ActorInfo::Platform {
organization_id, ..
} => {
validate(CHATGPT_ACCOUNT_ID_HEADER, None)?;
validate(OPENAI_ORGANIZATION_HEADER, Some(organization_id))
}
}
}
#[cfg(test)]
#[path = "runtime_auth_tests.rs"]
mod tests;

View File

@@ -1,386 +0,0 @@
use super::*;
use crate::ProviderAuthContext;
use base64::Engine;
use codex_features::RuntimeAuthMode;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::CodexAuth;
use codex_login::auth::BedrockApiKeyAuth;
use codex_login::auth::RefreshTokenFailedReason;
use codex_protocol::config_types::ModelProviderAuthInfo;
use codex_protocol::error::CodexErrorDetails;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::num::NonZeroU64;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
async fn context(
server: &MockServer,
credentials: Arc<AuthManager>,
mode: RuntimeAuthMode,
) -> ProviderAuthContext {
Mock::given(method("POST"))
.respond_with(|request: &wiremock::Request| ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": request.headers["idempotency-key"].to_str().unwrap(),
"agent_host_id": "host-a",
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null},
})))
.mount(server).await;
let runtime = RuntimeAuthManager::new(
Arc::clone(&credentials),
AgentHostAuthorization::InstallationId {
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
},
RuntimeRegistrationMetadata {
harness: None,
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", server.uri()).parse().unwrap(),
);
ProviderAuthContext {
credentials,
runtime_auth: Some((Arc::new(runtime), mode)),
}
}
#[tokio::test]
async fn explicit_keys_and_commands_use_their_own_shared_runtime() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let home = tempfile::tempdir().unwrap();
let credentials = AuthManager::from_auth_for_testing_with_home(
CodexAuth::from_api_key("ambient-key"),
home.path().to_path_buf(),
);
let context = context(&server, credentials, mode).await;
let literal = ModelProviderInfo {
experimental_bearer_token: Some("literal-key".into()),
requires_openai_auth: false,
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
};
#[cfg(unix)]
let (command, args) = ("sh", vec!["-c".into(), "printf command-key".into()]);
#[cfg(windows)]
let (command, args) = (
"cmd.exe",
vec![
"/D".into(),
"/Q".into(),
"/C".into(),
"echo command-key".into(),
],
);
let commanded = ModelProviderInfo {
auth: Some(ModelProviderAuthInfo {
command: command.into(),
args,
timeout_ms: NonZeroU64::new(5000).unwrap(),
refresh_interval_ms: 300_000,
cwd: home.path().to_path_buf().try_into().unwrap(),
}),
requires_openai_auth: false,
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
};
for (info, key) in [(literal.clone(), "literal-key"), (commanded, "command-key")] {
let mut runtime_id = None;
for _ in 0..2 {
let provider = context.model_provider(info.clone());
let selected = provider.request_auth(/*scope*/ None).await.unwrap();
let runtime = selected.runtime.as_ref().unwrap();
assert_eq!(runtime.auth().api_key(), Some(key));
match &runtime_id {
Some(id) => assert_eq!(runtime.runtime().id(), id),
None => runtime_id = Some(runtime.runtime().id().to_string()),
}
let headers = selected
.auth
.apply_auth_headers(Default::default())
.await
.unwrap();
match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(headers["authorization"], format!("Bearer {key}"));
assert!(headers.contains_key("x-openai-agent-assertion"));
}
RuntimeAuthMode::AssertionOnly => {
assert!(
headers["authorization"]
.to_str()
.unwrap()
.starts_with("AgentAssertion ")
);
assert!(!headers.contains_key("x-openai-agent-assertion"));
}
}
}
}
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 2);
for (request, key) in requests.iter().zip(["literal-key", "command-key"]) {
assert_eq!(
request.body_json::<serde_json::Value>().unwrap()["actor_auth"]["credential"],
key
);
}
let custom = context.model_provider(ModelProviderInfo {
base_url: Some("https://provider.example/v1".into()),
..literal
});
let auth = custom.request_auth(/*scope*/ None).await.unwrap();
assert!(auth.runtime.is_none());
let headers = auth
.auth
.apply_auth_headers(Default::default())
.await
.unwrap();
assert_eq!(headers["authorization"], "Bearer literal-key");
assert!(!headers.contains_key("x-openai-agent-assertion"));
assert_eq!(server.received_requests().await.unwrap().len(), 2);
}
}
#[tokio::test]
async fn explicit_provider_key_keeps_the_requested_project_scope() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let credentials =
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("ambient-key"));
let context = context(&server, credentials, mode).await;
server.reset().await;
Mock::given(method("POST"))
.and(wiremock::matchers::body_partial_json(json!({
"actor_auth": {
"type": "platform_api_key",
"credential": "selected-key",
"project_id": "proj-selected",
},
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "rai-selected",
"agent_host_id": "host-a",
"actor": {
"kind": "platform",
"user_id": "user-a",
"organization_id": "org-a",
"project_id": "proj-selected",
},
})))
.mount(&server)
.await;
let provider = context.model_provider(ModelProviderInfo {
experimental_bearer_token: Some("selected-key".into()),
http_headers: Some(std::collections::HashMap::from([(
OPENAI_PROJECT_HEADER.into(),
"proj-selected".into(),
)])),
requires_openai_auth: false,
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
});
let selected = provider.request_auth(/*scope*/ None).await.unwrap();
let runtime = selected.runtime.as_ref().unwrap();
assert_eq!(runtime.auth().api_key(), Some("selected-key"));
assert!(matches!(
runtime.runtime().actor().info(),
ActorInfo::Platform { project_id: Some(project), .. } if project == "proj-selected"
));
}
}
#[tokio::test]
async fn bedrock_auth_stays_independent_when_openai_runtime_auth_is_enabled() {
let server = MockServer::start().await;
let credentials =
AuthManager::from_auth_for_testing(CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
api_key: "bedrock-key".into(),
region: "us-east-1".into(),
}));
let context = context(&server, credentials, RuntimeAuthMode::DualHeader).await;
let bedrock = context.model_provider(ModelProviderInfo::create_amazon_bedrock_provider(
/*aws*/ None,
));
let headers = bedrock
.api_auth()
.await
.unwrap()
.apply_auth_headers(Default::default())
.await
.unwrap();
assert_eq!(headers["authorization"], "Bearer bedrock-key");
assert!(!headers.contains_key("x-openai-agent-assertion"));
assert!(server.received_requests().await.unwrap().is_empty());
let openai = context.model_provider(ModelProviderInfo {
experimental_bearer_token: Some("openai-key".into()),
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
});
let headers = openai
.api_auth()
.await
.unwrap()
.apply_auth_headers(Default::default())
.await
.unwrap();
assert_eq!(headers["authorization"], "Bearer openai-key");
assert!(headers.contains_key("x-openai-agent-assertion"));
let headers = bedrock
.api_auth()
.await
.unwrap()
.apply_auth_headers(Default::default())
.await
.unwrap();
assert_eq!(headers["authorization"], "Bearer bedrock-key");
assert!(!headers.contains_key("x-openai-agent-assertion"));
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
assert_eq!(
requests[0].body_json::<serde_json::Value>().unwrap()["actor_auth"]["credential"],
"openai-key"
);
}
#[tokio::test]
async fn runtime_denial_recovery_is_scoped_to_openai() {
let server = MockServer::start().await;
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("actor-key"));
let context = context(&server, credentials, RuntimeAuthMode::AssertionOnly).await;
for (url, has_runtime) in [
("https://api.openai.com/v1", true),
("https://provider.example/v1", false),
] {
let provider = context.model_provider(ModelProviderInfo::create_openai_provider(Some(
url.to_string(),
)));
for code in ["invalid_agent_instance_assertion", "token_expired"] {
let error = codex_api::TransportError::Http {
status: http::StatusCode::UNAUTHORIZED,
retry_after: None,
url: Some(format!("{url}/responses")),
headers: None,
body: Some(json!({"error": {"code": code}}).to_string()),
};
assert_eq!(
provider.is_recoverable_auth_error(&error),
!has_runtime || code == "token_expired"
);
}
}
}
#[tokio::test]
async fn permanent_runtime_refresh_failure_preserves_sign_in_error() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
// Exercise proactive refresh and registration's existing 401 recovery.
for last_refresh in ["2000-01-01T00:00:00Z", "2099-01-01T00:00:00Z"] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"error": {"code": "refresh_token_invalidated"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(ResponseTemplate::new(401))
.mount(&server)
.await;
let home = tempfile::tempdir().expect("create auth home");
let claims = json!({
"https://api.openai.com/auth": {
"chatgpt_user_id": "user-a",
"chatgpt_account_id": "workspace-a",
},
});
let token = format!(
"e30.{}.signature",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())
);
let stored = serde_json::from_value(json!({
"auth_mode": "chatgpt",
"tokens": {
"id_token": token, "access_token": "initial-token",
"refresh_token": "revoked-refresh-token", "account_id": "workspace-a",
"oauth_provenance": {
"issuer": server.uri(), "client_id": "runtime-refresh-test",
},
},
"last_refresh": last_refresh,
}))
.expect("construct stored OAuth credentials");
codex_login::save_auth(
home.path(),
&stored,
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
)
.expect("save OAuth credentials");
let credentials = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::Direct,
codex_login::test_support::transport_default_auth_route_config(),
)
.await,
);
let original = credentials.auth_cached().expect("load OAuth credentials");
let runtime = Arc::new(RuntimeAuthManager::new(
Arc::clone(&credentials),
AgentHostAuthorization::InstallationId {
installation_id: "00000000-0000-0000-0000-000000000000"
.parse()
.expect("parse installation ID"),
},
RuntimeRegistrationMetadata {
harness: None,
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/register", server.uri())
.parse()
.expect("parse registration URL"),
));
let provider = ProviderAuthContext {
credentials: Arc::clone(&credentials),
runtime_auth: Some((Arc::clone(&runtime), mode)),
}
.model_provider(ModelProviderInfo::create_openai_provider(
/*base_url*/ None,
));
// A later request must preserve the cached rejection, not retry it as a stream error.
for _ in 0..2 {
let error = provider
.request_auth(/*scope*/ None)
.await
.err()
.expect("revoked refresh must reject request preparation");
let failure = credentials
.refresh_failure_for_auth(&original)
.expect("permanent refresh rejection is cached");
assert_eq!(failure.reason, RefreshTokenFailedReason::Revoked);
let CodexErrorDetails::RefreshTokenFailed(actual) = error.details() else {
panic!("expected sign-in error for {mode:?}/{last_refresh}, got {error:?}");
};
assert_eq!(actual, &failure);
assert_eq!(error.retry_delay(/*retry_count*/ 1), None);
}
server.verify().await;
}
}
}

View File

@@ -2,8 +2,6 @@
//! Discovery and inference must preserve primary auth and reject requests when gateway auth fails.
use super::*;
use crate::AgentIdentitySessionFallback;
use crate::ProviderAuthScope;
use crate::create_model_provider;
use crate::test_support::seed_gateway_auth;
use codex_api::Compression;
@@ -12,10 +10,8 @@ use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::ReqwestTransport;
use codex_login::AuthHeaders;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::auth::AgentIdentityAuthPolicy;
use codex_login::default_client::ClientRedirectPolicy;
use codex_login::default_client::create_client_for_route;
use codex_model_provider_info::GatewayOAuthConfig;
@@ -26,7 +22,6 @@ use codex_model_provider_info::OAuthCredentialsStore;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::SessionSource;
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
@@ -84,16 +79,11 @@ async fn gateway_credentials_accompany_primary_auth_in_models_and_responses() {
};
let info = ModelProviderInfo {
gateway_oauth: Some(GatewayOAuthConfig::OAuth(config)),
model_catalog_url: Some(format!("{}/models", server.uri()).into()),
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
};
let mut primary_headers = HeaderMap::new();
primary_headers.insert(
"authorization",
HeaderValue::from_static("Bearer primary-token"),
);
primary_headers.insert("chatgpt-account-id", HeaderValue::from_static("account"));
let primary = AuthManager::from_auth_for_testing_with_home(
CodexAuth::Headers(AuthHeaders::new(primary_headers)),
CodexAuth::from_api_key("primary-token"),
home.path().to_path_buf(),
);
let manager = seed_gateway_auth(
@@ -116,29 +106,13 @@ async fn gateway_credentials_accompany_primary_auth_in_models_and_responses() {
models
.raw_model_catalog(RefreshStrategy::Online, factory.clone())
.await;
let (api, resolved) = provider
.request_provider_and_auth(/*scope*/ None)
.await
.unwrap();
let (api, resolved) = provider.request_provider_and_auth().await.unwrap();
let auth = resolved.auth;
let scoped = provider
.api_auth_for_scope(ProviderAuthScope {
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
session_source: SessionSource::Cli,
agent_identity_session_fallback: AgentIdentitySessionFallback::default(),
})
.await
.unwrap();
let mut expected = HeaderMap::from_iter([
(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer primary-token"),
),
(
HeaderName::from_static("chatgpt-account-id"),
HeaderValue::from_static("account"),
),
]);
let scoped = provider.request_auth().await.unwrap();
let mut expected = HeaderMap::from_iter([(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer primary-token"),
)]);
let (name, value) = match delivery {
GatewayOAuthDelivery::Header { .. } => ("x-gateway-auth", "Bearer gateway-token"),
GatewayOAuthDelivery::Cookie { .. } => ("cookie", "gateway_session=gateway-token"),
@@ -193,122 +167,66 @@ async fn gateway_credentials_accompany_primary_auth_in_models_and_responses() {
}
#[tokio::test]
async fn gateway_preserves_runtime_auth_and_rejects_header_collisions() {
use codex_features::RuntimeAuthMode;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let home = tempfile::tempdir().unwrap();
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a",
"agent_host_id": "host-a",
"actor": {"kind":"platform", "user_id":"user-a", "organization_id":"org-a", "project_id":null},
})))
.expect(1)
.mount(&server)
.await;
let primary = AuthManager::from_auth_for_testing_with_home(
CodexAuth::from_api_key("primary-token"),
home.path().to_path_buf(),
);
let info = ModelProviderInfo {
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
authorization_url: format!("{}/authorize", server.uri()),
device_authorization_url: None,
token_url: format!("{}/token", server.uri()),
client_id: "client".into(),
resource: None,
scopes: vec![],
redirect_port: None,
credentials_store: Default::default(),
delivery: GatewayOAuthDelivery::Header {
name: "x-gateway-auth".into(),
scheme: "Bearer".into(),
},
})),
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
};
let _gateway = seed_gateway_auth(
&info,
&primary,
json!({"access_token": "gateway-token", "expires_at": i64::MAX}),
);
let runtime = Arc::new(RuntimeAuthManager::new(
Arc::clone(&primary),
AgentHostAuthorization::InstallationId {
installation_id: "00000000-0000-0000-0000-000000000000".parse().unwrap(),
async fn gateway_preserves_primary_auth_and_rejects_header_collisions() {
let server = MockServer::start().await;
let home = tempfile::tempdir().unwrap();
let primary = AuthManager::from_auth_for_testing_with_home(
CodexAuth::from_api_key("primary-token"),
home.path().to_path_buf(),
);
let info = ModelProviderInfo {
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
authorization_url: format!("{}/authorize", server.uri()),
device_authorization_url: None,
token_url: format!("{}/token", server.uri()),
client_id: "client".into(),
resource: None,
scopes: vec![],
redirect_port: None,
credentials_store: Default::default(),
delivery: GatewayOAuthDelivery::Header {
name: "x-gateway-auth".into(),
scheme: "Bearer".into(),
},
RuntimeRegistrationMetadata {
harness: None,
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/register", server.uri()).parse().unwrap(),
));
let provider = crate::test_support::runtime_model_provider(info, primary, (runtime, mode));
let auth = provider.api_auth().await.unwrap();
let stale_headers = HeaderMap::from_iter([
(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer stale"),
),
(
HeaderName::from_static("x-openai-agent-assertion"),
HeaderValue::from_static("stale"),
),
(
HeaderName::from_static("chatgpt-account-id"),
HeaderValue::from_static("stale"),
),
(
HeaderName::from_static("x-caller"),
HeaderValue::from_static("retained"),
),
]);
let headers = auth
.apply_auth_headers(stale_headers.clone())
.await
.unwrap();
assert_eq!(headers["x-gateway-auth"], "Bearer gateway-token");
assert_eq!(headers["x-caller"], "retained");
assert!(!headers.contains_key("chatgpt-account-id"));
let proof_header = match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(headers["authorization"], "Bearer primary-token");
"x-openai-agent-assertion"
}
RuntimeAuthMode::AssertionOnly => {
assert!(!headers.contains_key("x-openai-agent-assertion"));
assert!(
headers["authorization"]
.to_str()
.unwrap()
.starts_with("AgentAssertion 1.")
);
"authorization"
}
};
let mut request = codex_http_client::Request::new(http::Method::POST, server.uri());
request.headers = stale_headers.clone();
let signed = auth.apply_auth(request).await.unwrap();
assert_eq!(signed.headers["x-gateway-auth"], "Bearer gateway-token");
assert_ne!(headers[proof_header], signed.headers[proof_header]);
})),
..ModelProviderInfo::create_openai_provider(Some(server.uri()))
};
let _gateway = seed_gateway_auth(
&info,
&primary,
json!({"access_token": "gateway-token", "expires_at": i64::MAX}),
);
let provider = create_model_provider(info, Some(primary));
let auth = provider.api_auth().await.unwrap();
let caller_headers = HeaderMap::from_iter([
(
http::header::AUTHORIZATION,
HeaderValue::from_static("Bearer stale"),
),
(
HeaderName::from_static("x-caller"),
HeaderValue::from_static("retained"),
),
]);
let headers = auth
.apply_auth_headers(caller_headers.clone())
.await
.unwrap();
assert_eq!(headers["x-gateway-auth"], "Bearer gateway-token");
assert_eq!(headers["x-caller"], "retained");
assert_eq!(headers["authorization"], "Bearer primary-token");
let mut request = codex_http_client::Request::new(http::Method::POST, server.uri());
request.headers = caller_headers.clone();
let signed = auth.apply_auth(request).await.unwrap();
assert_eq!(signed.headers["x-gateway-auth"], "Bearer gateway-token");
assert_eq!(signed.headers["authorization"], "Bearer primary-token");
let mut collision = stale_headers;
collision.insert("x-gateway-auth", HeaderValue::from_static("caller-token"));
assert!(auth.apply_auth_headers(collision.clone()).await.is_err());
let mut request = codex_http_client::Request::new(http::Method::POST, server.uri());
request.headers = collision;
assert!(auth.apply_auth(request).await.is_err());
assert_eq!(server.received_requests().await.unwrap().len(), 1);
server.verify().await;
}
let mut collision = caller_headers;
collision.insert("x-gateway-auth", HeaderValue::from_static("caller-token"));
assert!(auth.apply_auth_headers(collision.clone()).await.is_err());
let mut request = codex_http_client::Request::new(http::Method::POST, server.uri());
request.headers = collision;
assert!(auth.apply_auth(request).await.is_err());
}
#[tokio::test]

View File

@@ -21,5 +21,3 @@ pub fn models_cache_entry(
}
pub use crate::shared_state::test_support::seed_gateway_auth;
pub use crate::provider::test_support::runtime_model_provider;

View File

@@ -1,107 +0,0 @@
//! Applies discovered routing and keeps requests within the selected ChatGPT backend.
use codex_login::WorkspaceRouting;
use codex_login::WorkspaceRoutingSession;
use codex_login::default_client::ClientRedirectPolicy;
use http::HeaderValue;
use std::io;
use std::sync::Arc;
use tokio::sync::Mutex;
use url::Url;
pub const ACCOUNT_ROUTING_HEADER: &str = "x-openai-account-routing-override";
/// Routing scope for one session's provider. Once routed, it cannot become
/// independent merely because the account owner's bootstrap configuration changes.
/// Clones serialize discovery and share the first successful routing transition.
#[derive(Clone, Debug)]
pub struct WorkspaceRoutingContext {
pub(crate) chatgpt_base_url: String,
pub(crate) previously_routed: Arc<Mutex<bool>>,
pub(crate) session: Option<Arc<WorkspaceRoutingSession>>,
}
impl WorkspaceRoutingContext {
pub fn new(chatgpt_base_url: String) -> Self {
Self {
chatgpt_base_url,
previously_routed: Arc::new(Mutex::new(/*t*/ false)),
session: None,
}
}
pub fn with_session(mut self, session: WorkspaceRoutingSession) -> Self {
self.session = Some(Arc::new(session));
self
}
}
/// Changes only the origin of requests to the selected ChatGPT backend.
pub(crate) fn apply_workspace_routing(
provider: &mut codex_api::Provider,
routing: WorkspaceRouting,
) -> io::Result<()> {
let base_url = &mut provider.base_url;
let headers = &mut provider.headers;
let parse = |value: &str| Url::parse(value).map_err(io::Error::other);
let mut url = parse(base_url)?;
let backend = parse(&routing.backend_origin)?;
if backend.scheme() != "https"
|| backend.host_str().is_none()
|| !backend.username().is_empty()
|| backend.password().is_some()
|| backend.path() != "/"
|| backend.query().is_some()
|| backend.fragment().is_some()
{
return Err(io::Error::other("invalid workspace backend origin"));
}
let header = match routing.account_routing_override.as_str() {
"NO_CONSTRAINT" => None,
"us" | "us_cr" => Some(
HeaderValue::from_str(&routing.account_routing_override).map_err(io::Error::other)?,
),
_ => return Err(io::Error::other("invalid workspace routing override")),
};
url.set_scheme(backend.scheme())
.map_err(|()| io::Error::other("invalid backend scheme"))?;
url.set_host(backend.host_str()).map_err(io::Error::other)?;
url.set_port(backend.port())
.map_err(|()| io::Error::other("invalid backend port"))?;
*base_url = url.into();
headers.remove(ACCOUNT_ROUTING_HEADER);
if let Some(header) = header {
headers.insert(ACCOUNT_ROUTING_HEADER, header);
}
Ok(())
}
/// API deployment and redirect policy resolved for one Responses request.
/// Workspace routes reject redirects even when their routing override supplies no header.
#[derive(Debug)]
pub struct ResolvedResponsesProvider {
pub provider: codex_api::Provider,
pub redirect_policy: ClientRedirectPolicy,
}
/// Effective destination and credentials that permit reusing a Responses socket.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResponsesConnectionKey {
base_url: String,
routing_header: Option<HeaderValue>,
auth_revision: Option<u64>,
}
impl ResponsesConnectionKey {
pub fn new(provider: &codex_api::Provider, auth_revision: Option<u64>) -> Self {
Self {
base_url: provider.base_url.clone(),
routing_header: provider.headers.get(ACCOUNT_ROUTING_HEADER).cloned(),
auth_revision,
}
}
}
#[cfg(test)]
#[path = "workspace_routing_tests.rs"]
mod workspace_routing_tests;

View File

@@ -1,200 +0,0 @@
//! Routing is limited to the selected ChatGPT backend and successful discovery.
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use crate::ACCOUNT_ROUTING_HEADER;
use crate::WorkspaceRoutingContext;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::WorkspaceRouting;
use codex_login::WorkspaceRoutingRequest;
use codex_login::WorkspaceRoutingResolver;
use codex_login::default_client::ClientRedirectPolicy;
use codex_model_provider_info::ModelProviderInfo;
use pretty_assertions::assert_eq;
use crate::create_model_provider;
struct Routing(WorkspaceRouting);
struct ChangedBootstrap {
first_lookup: std::sync::atomic::AtomicBool,
release_first: tokio::sync::Notify,
}
impl WorkspaceRoutingResolver for ChangedBootstrap {
fn resolve(
&self,
request: WorkspaceRoutingRequest,
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
Box::pin(async move {
if self
.first_lookup
.swap(false, std::sync::atomic::Ordering::Relaxed)
{
self.release_first.notified().await;
Ok(Some(WorkspaceRouting {
chatgpt_account_id: "account_id".into(),
backend_origin: "https://gov.chatgpt.com".into(),
account_routing_override: "us_cr".into(),
}))
} else if request.previously_routed {
Err(io::Error::other("bootstrap changed"))
} else {
Ok(None)
}
})
}
}
#[tokio::test]
async fn concurrent_discovery_cannot_forget_established_routing() {
let context = WorkspaceRoutingContext::new("https://chatgpt.com/backend-api".into());
let auth =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let resolver = Arc::new(ChangedBootstrap {
first_lookup: std::sync::atomic::AtomicBool::new(true),
release_first: tokio::sync::Notify::new(),
});
auth.set_workspace_routing_resolver(Arc::downgrade(
&(resolver.clone() as Arc<dyn WorkspaceRoutingResolver>),
));
let provider = create_model_provider(
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
Some(auth),
);
let mut first = provider.responses_api_provider(&context);
let classifier_context = context.clone();
let mut second = provider.responses_api_provider(&classifier_context);
let early_second = std::future::poll_fn(|cx| {
assert!(first.as_mut().poll(cx).is_pending());
std::task::Poll::Ready(second.as_mut().poll(cx))
})
.await;
resolver.release_first.notify_one();
assert_eq!(
first.await.unwrap().provider.base_url,
"https://gov.chatgpt.com/backend-api/codex"
);
let second = match early_second {
std::task::Poll::Ready(result) => result,
std::task::Poll::Pending => second.await,
};
assert!(
second.is_err(),
"a concurrent lookup must retain the first lookup's routing scope"
);
}
impl WorkspaceRoutingResolver for Routing {
fn resolve(
&self,
request: WorkspaceRoutingRequest,
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
Box::pin(async move {
let origin = url::Url::parse(&request.provider_base_url)
.unwrap()
.origin();
let bootstrap = url::Url::parse(&request.chatgpt_base_url).unwrap().origin();
Ok((origin == bootstrap).then(|| self.0.clone()))
})
}
}
#[tokio::test]
async fn workspace_routing_preserves_paths_and_excludes_other_providers() {
let routing_context = WorkspaceRoutingContext::new("https://chatgpt.com/backend-api".into());
let auth =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let resolver: Arc<dyn WorkspaceRoutingResolver> = Arc::new(Routing(WorkspaceRouting {
chatgpt_account_id: "account_id".into(),
backend_origin: "https://gov.chatgpt.com:8443".into(),
account_routing_override: "us_cr".into(),
}));
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
let info = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
let provider = create_model_provider(info.clone(), Some(auth.clone()));
let routed = provider
.responses_api_provider(&routing_context)
.await
.unwrap();
assert_eq!(
(
routed.provider.base_url.as_str(),
routed.provider.headers[ACCOUNT_ROUTING_HEADER]
.to_str()
.unwrap(),
routed.redirect_policy,
),
(
"https://gov.chatgpt.com:8443/backend-api/codex",
"us_cr",
ClientRedirectPolicy::Reject
)
);
let mut custom_auth = info.clone();
custom_auth.experimental_bearer_token = Some("custom-token".into());
let mut unrelated_path = info.clone();
unrelated_path.base_url = Some("https://chatgpt.com/v1".into());
for info in [custom_auth, unrelated_path] {
let provider = create_model_provider(info, Some(auth.clone()));
let ordinary = provider.api_provider().await.unwrap();
let responses = provider
.responses_api_provider(&routing_context)
.await
.unwrap();
assert_eq!(
(
responses.provider.base_url,
responses.provider.headers,
responses.redirect_policy
),
(
ordinary.base_url,
ordinary.headers,
ClientRedirectPolicy::Default
)
);
}
let api_auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("api-key"));
api_auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
let api = create_model_provider(info, Some(api_auth))
.responses_api_provider(&routing_context)
.await
.unwrap();
assert_eq!(api.provider.base_url, "https://api.openai.com/v1");
assert!(!api.provider.headers.contains_key(ACCOUNT_ROUTING_HEADER));
}
#[tokio::test]
async fn missing_routing_owner_and_wrong_workspace_fail_closed() {
let routing_context = WorkspaceRoutingContext::new("https://chatgpt.com/backend-api".into());
let auth =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let resolver: Arc<dyn WorkspaceRoutingResolver> = Arc::new(Routing(WorkspaceRouting {
chatgpt_account_id: "other-account".into(),
backend_origin: "https://chatgpt.com".into(),
account_routing_override: "NO_CONSTRAINT".into(),
}));
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
let provider = create_model_provider(
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
Some(auth),
);
assert!(
provider
.responses_api_provider(&routing_context)
.await
.is_err()
);
drop(resolver);
assert!(
provider
.responses_api_provider(&routing_context)
.await
.is_err()
);
}