mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Route FedRAMP API keys to government endpoints by default (#57178)
## Why API keys with FedRAMP issuance markers previously used commercial endpoint defaults without a FedRAMP request header. ## What changed - Recognize `sk-proj-fedramp-` and `sk-svcacct-fedramp-` prefixes as routing hints and send `X-OpenAI-Fedramp: true`, preserving the complete key for authentication. - Select `https://gov.api.openai.com/v1` for default OpenAI API routing and `https://gov.chatgpt.com/backend-api/` for default ChatGPT backend requests, including model discovery and analytics. - Preserve explicit endpoint overrides, including an explicitly configured commercial default URL. - Resolve provider routing and authentication from the same credential snapshot, and apply key-dependent routing to realtime WebSocket startup. ## Testing Add regression coverage for prefix recognition, unchanged key storage and authorization, provider credential precedence, endpoint overrides, credential rotation, model discovery, analytics routing, and realtime request preparation. GitOrigin-RevId: a62576ce205c34e067532b8e6c0e431f87a157e2
This commit is contained in:
@@ -65,6 +65,7 @@ use codex_app_server_protocol::TurnStatus;
|
||||
use codex_app_server_protocol::item_event_to_server_notification;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ChatgptBaseUrl;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginTelemetryMetadata;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -116,7 +117,7 @@ pub struct AnalyticsEventsClient {
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
enum AnalyticsEventsDestination {
|
||||
Http {
|
||||
url: String,
|
||||
base_url: ChatgptBaseUrl,
|
||||
},
|
||||
#[cfg(debug_assertions)]
|
||||
CaptureFile {
|
||||
@@ -125,12 +126,15 @@ enum AnalyticsEventsDestination {
|
||||
}
|
||||
|
||||
impl AnalyticsEventsDestination {
|
||||
fn from_base_url(base_url: String) -> Self {
|
||||
fn from_base_url(base_url: ChatgptBaseUrl) -> Self {
|
||||
let capture_file = analytics_capture_file_from_env();
|
||||
Self::from_base_url_and_capture_file(base_url, capture_file)
|
||||
}
|
||||
|
||||
fn from_base_url_and_capture_file(base_url: String, capture_file: Option<PathBuf>) -> Self {
|
||||
fn from_base_url_and_capture_file(
|
||||
base_url: ChatgptBaseUrl,
|
||||
capture_file: Option<PathBuf>,
|
||||
) -> Self {
|
||||
#[cfg(debug_assertions)]
|
||||
if let Some(path) = capture_file {
|
||||
if let Err(err) = crate::analytics_capture::initialize(&path) {
|
||||
@@ -149,9 +153,17 @@ impl AnalyticsEventsDestination {
|
||||
#[cfg(not(debug_assertions))]
|
||||
let _ = capture_file;
|
||||
|
||||
let base_url = base_url.trim_end_matches('/');
|
||||
Self::Http {
|
||||
url: format!("{base_url}/codex/analytics-events/events"),
|
||||
Self::Http { base_url }
|
||||
}
|
||||
|
||||
fn url_for_auth(&self, auth: &CodexAuth) -> Option<String> {
|
||||
match self {
|
||||
Self::Http { base_url } => {
|
||||
let base_url = base_url.resolve(auth).trim_end_matches('/');
|
||||
Some(format!("{base_url}/codex/analytics-events/events"))
|
||||
}
|
||||
#[cfg(debug_assertions)]
|
||||
Self::CaptureFile { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,10 +325,10 @@ impl AnalyticsEventsClient {
|
||||
|
||||
pub fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
base_url: String,
|
||||
base_url: impl Into<ChatgptBaseUrl>,
|
||||
analytics_enabled: Option<bool>,
|
||||
) -> Self {
|
||||
let destination = AnalyticsEventsDestination::from_base_url(base_url);
|
||||
let destination = AnalyticsEventsDestination::from_base_url(base_url.into());
|
||||
Self {
|
||||
queue: (analytics_enabled != Some(false))
|
||||
.then(|| AnalyticsEventsQueue::new(Arc::clone(&auth_manager), destination)),
|
||||
@@ -1057,10 +1069,8 @@ async fn send_track_events_request(
|
||||
return;
|
||||
}
|
||||
|
||||
let url = match destination {
|
||||
AnalyticsEventsDestination::Http { url } => url,
|
||||
#[cfg(debug_assertions)]
|
||||
AnalyticsEventsDestination::CaptureFile { .. } => return,
|
||||
let Some(url) = destination.url_for_auth(auth) else {
|
||||
return;
|
||||
};
|
||||
let headers = match codex_model_provider::auth_provider_from_auth(auth).to_auth_headers() {
|
||||
Ok(headers) => headers,
|
||||
@@ -1084,7 +1094,7 @@ async fn send_track_events_request(
|
||||
}
|
||||
};
|
||||
let mut request = client
|
||||
.post(url)
|
||||
.post(&url)
|
||||
.timeout(ANALYTICS_EVENTS_TIMEOUT)
|
||||
.headers(headers)
|
||||
.header("Content-Type", "application/json")
|
||||
|
||||
@@ -89,7 +89,7 @@ async fn capture_requests(
|
||||
) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let destination = AnalyticsEventsDestination::Http {
|
||||
url: format!("http://{}/events", listener.local_addr().unwrap()),
|
||||
base_url: format!("http://{}", listener.local_addr().unwrap()).into(),
|
||||
};
|
||||
let (paused_tx, paused_rx) = tokio::sync::oneshot::channel();
|
||||
let (resume_tx, resume_rx) = tokio::sync::oneshot::channel();
|
||||
|
||||
@@ -95,6 +95,7 @@ use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
#[cfg(debug_assertions)]
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider::ChatgptBaseUrl;
|
||||
use codex_protocol::protocol::RealtimeConversationVersion;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
@@ -308,7 +309,7 @@ fn client_with_receiver() -> (
|
||||
fn analytics_destination_uses_explicit_capture_file() {
|
||||
let capture_path = unique_capture_path("destination");
|
||||
let destination = AnalyticsEventsDestination::from_base_url_and_capture_file(
|
||||
"https://chatgpt.com/backend-api/".to_string(),
|
||||
"https://chatgpt.com/backend-api/".into(),
|
||||
Some(capture_path.clone()),
|
||||
);
|
||||
|
||||
@@ -337,31 +338,53 @@ fn analytics_destination_uses_explicit_capture_file() {
|
||||
|
||||
#[test]
|
||||
fn analytics_destination_uses_http_without_capture_file() {
|
||||
let destination = AnalyticsEventsDestination::from_base_url_and_capture_file(
|
||||
"https://chatgpt.com/backend-api/".to_string(),
|
||||
/*capture_file*/ None,
|
||||
);
|
||||
let commercial_url = "https://chatgpt.com/backend-api/codex/analytics-events/events";
|
||||
let gov_url = "https://gov.chatgpt.com/backend-api/codex/analytics-events/events";
|
||||
for (base_url, expected_urls) in [
|
||||
(
|
||||
ChatgptBaseUrl::Default,
|
||||
[commercial_url, gov_url, commercial_url],
|
||||
),
|
||||
(
|
||||
ChatgptBaseUrl::from("https://chatgpt.com/backend-api/"),
|
||||
[commercial_url; 3],
|
||||
),
|
||||
(
|
||||
ChatgptBaseUrl::from("https://proxy.example/backend-api/"),
|
||||
["https://proxy.example/backend-api/codex/analytics-events/events"; 3],
|
||||
),
|
||||
] {
|
||||
let destination = AnalyticsEventsDestination::from_base_url_and_capture_file(
|
||||
base_url.clone(),
|
||||
/*capture_file*/ None,
|
||||
);
|
||||
assert_eq!(destination, AnalyticsEventsDestination::Http { base_url });
|
||||
|
||||
assert_eq!(
|
||||
destination,
|
||||
AnalyticsEventsDestination::Http {
|
||||
url: "https://chatgpt.com/backend-api/codex/analytics-events/events".to_string()
|
||||
for (api_key, expected_url) in ["sk-test", "sk-proj-fedramp-test", "sk-test"]
|
||||
.into_iter()
|
||||
.zip(expected_urls)
|
||||
{
|
||||
let auth = codex_login::CodexAuth::from_api_key(api_key);
|
||||
assert_eq!(
|
||||
destination.url_for_auth(&auth).as_deref(),
|
||||
Some(expected_url)
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(debug_assertions))]
|
||||
fn analytics_destination_ignores_capture_file_in_release() {
|
||||
let destination = AnalyticsEventsDestination::from_base_url_and_capture_file(
|
||||
"https://chatgpt.com/backend-api/".to_string(),
|
||||
"https://chatgpt.com/backend-api/".into(),
|
||||
Some(std::path::PathBuf::from("ignored.jsonl")),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
destination,
|
||||
AnalyticsEventsDestination::Http {
|
||||
url: "https://chatgpt.com/backend-api/codex/analytics-events/events".to_string()
|
||||
base_url: "https://chatgpt.com/backend-api/".into()
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1172,7 +1195,7 @@ async fn account_switch_between_batches_does_not_send_old_credentials() {
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let destination = AnalyticsEventsDestination::Http {
|
||||
url: format!("http://{}/events", listener.local_addr().unwrap()),
|
||||
base_url: format!("http://{}", listener.local_addr().unwrap()).into(),
|
||||
};
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let captured = Arc::clone(&requests);
|
||||
|
||||
@@ -10,7 +10,7 @@ pub(crate) fn analytics_events_client_from_config(
|
||||
) -> AnalyticsEventsClient {
|
||||
AnalyticsEventsClient::new(
|
||||
auth_manager,
|
||||
config.chatgpt_base_url.trim_end_matches('/').to_string(),
|
||||
config.chatgpt_backend_url(),
|
||||
config.analytics_enabled,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -159,6 +159,7 @@ pub(super) async fn configure(
|
||||
};
|
||||
let config = Arc::make_mut(config);
|
||||
config.chatgpt_base_url = policy_config.chatgpt_base_url;
|
||||
config.chatgpt_base_url_is_explicit = policy_config.chatgpt_base_url_is_explicit;
|
||||
config.enforce_residency = policy_config.enforce_residency;
|
||||
config.application_network_policy = policy_config.application_network_policy;
|
||||
config.application_auth_route_config = policy_config.application_auth_route_config;
|
||||
|
||||
@@ -23,6 +23,7 @@ use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_model_provider::DEFAULT_CHATGPT_BASE_URL;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
@@ -157,7 +158,7 @@ async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> {
|
||||
let user_config = home.join("config.toml");
|
||||
let trust = std::fs::read_to_string(&user_config)?;
|
||||
std::fs::write(
|
||||
user_config,
|
||||
&user_config,
|
||||
format!("chatgpt_base_url = '{selected_url}'\n{trust}"),
|
||||
)?;
|
||||
let project_config = selected.join(".codex/config.toml");
|
||||
@@ -197,6 +198,24 @@ async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> {
|
||||
);
|
||||
assert_eq!(config.chatgpt_base_url, selected_url);
|
||||
|
||||
let marked = CodexAuth::from_api_key("sk-proj-fedramp-test-key");
|
||||
for (configured_url, expected_url) in [
|
||||
(None, "https://gov.chatgpt.com/backend-api/"),
|
||||
(Some(DEFAULT_CHATGPT_BASE_URL), DEFAULT_CHATGPT_BASE_URL),
|
||||
] {
|
||||
let setting = configured_url
|
||||
.map(|url| format!("chatgpt_base_url = '{url}'\n"))
|
||||
.unwrap_or_default();
|
||||
std::fs::write(&user_config, format!("{setting}{trust}"))?;
|
||||
let _auth = configure(
|
||||
&manager,
|
||||
&mut config,
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(config.chatgpt_backend_url().resolve(&marked), expected_url);
|
||||
}
|
||||
|
||||
std::fs::write(&project_config, "[malformed")?;
|
||||
let error = configure(
|
||||
&manager,
|
||||
|
||||
@@ -424,7 +424,7 @@ impl WorkerRuntime {
|
||||
.to_api_provider(Some(AuthMode::ApiKey))
|
||||
.map_err(|error| RequestError::Other(error.into()))?;
|
||||
let client = BackendClient::from_auth(
|
||||
self.config.chatgpt_base_url.clone(),
|
||||
self.config.chatgpt_backend_url().resolve(&auth),
|
||||
&auth,
|
||||
http_client_factory,
|
||||
);
|
||||
@@ -448,12 +448,8 @@ impl WorkerRuntime {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let provider = model_provider
|
||||
.api_provider()
|
||||
.await
|
||||
.map_err(|error| RequestError::Other(error.into()))?;
|
||||
let auth = model_provider
|
||||
.api_auth()
|
||||
let (provider, auth) = model_provider
|
||||
.api_provider_and_auth()
|
||||
.await
|
||||
.map_err(|error| RequestError::Other(error.into()))?;
|
||||
let endpoint = provider.url_for_path("analytics/codex/turn-costs");
|
||||
|
||||
@@ -2318,8 +2318,8 @@ async fn websocket_reachability_check(
|
||||
auth.as_ref().map(auth_mode_name).unwrap_or("none")
|
||||
));
|
||||
|
||||
let api_provider = match runtime_provider.api_provider().await {
|
||||
Ok(api_provider) => api_provider,
|
||||
let (api_provider, api_auth) = match runtime_provider.api_provider_and_auth().await {
|
||||
Ok(setup) => setup,
|
||||
Err(err) => {
|
||||
return websocket_probe_warning(
|
||||
"Responses WebSocket provider setup failed",
|
||||
@@ -2346,17 +2346,6 @@ async fn websocket_reachability_check(
|
||||
}
|
||||
}
|
||||
|
||||
let api_auth = match runtime_provider.api_auth().await {
|
||||
Ok(api_auth) => api_auth,
|
||||
Err(err) => {
|
||||
return websocket_probe_warning(
|
||||
"Responses WebSocket auth could not be resolved",
|
||||
details,
|
||||
format!("auth resolution failed: {err}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let mut extra_headers = HeaderMap::new();
|
||||
extra_headers.insert(
|
||||
OPENAI_BETA_HEADER,
|
||||
|
||||
@@ -74,6 +74,7 @@ use codex_config::types::WindowsToml;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_features::Feature;
|
||||
use codex_features::FeaturesToml;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::RESIDENCY_HEADER_NAME;
|
||||
use codex_login::test_support::auth_manager_from_optional_auth;
|
||||
use codex_model_provider::ProviderCapabilities;
|
||||
@@ -6547,11 +6548,14 @@ async fn config_resolves_explicit_keyring_auth_store_mode() -> std::io::Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case::test_case("https://managed.example/backend-api/"; "custom")]
|
||||
#[test_case::test_case(DEFAULT_CHATGPT_BASE_URL; "explicit_default")]
|
||||
#[tokio::test]
|
||||
async fn config_applies_managed_auth_store_and_chatgpt_base_url() -> std::io::Result<()> {
|
||||
async fn config_applies_managed_auth_store_and_chatgpt_base_url(
|
||||
managed_url: &str,
|
||||
) -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let managed_store = AuthCredentialsStoreMode::Keyring;
|
||||
let managed_url = "https://managed.example/backend-api/";
|
||||
let requirements = codex_config::ConfigRequirements {
|
||||
cli_auth_credentials_store: Some(Sourced::new(managed_store, RequirementSource::Unknown)),
|
||||
chatgpt_base_url: Some(Sourced::new(
|
||||
@@ -6584,6 +6588,13 @@ async fn config_applies_managed_auth_store_and_chatgpt_base_url() -> std::io::Re
|
||||
|
||||
assert_eq!(config.cli_auth_credentials_store_mode, managed_store);
|
||||
assert_eq!(config.chatgpt_base_url, managed_url);
|
||||
assert!(config.chatgpt_base_url_is_explicit);
|
||||
assert_eq!(
|
||||
config
|
||||
.chatgpt_backend_url()
|
||||
.resolve(&CodexAuth::from_api_key("sk-proj-fedramp-test-key")),
|
||||
managed_url
|
||||
);
|
||||
assert!(config.startup_warnings.iter().any(|warning| {
|
||||
warning.contains("Configured value for `cli_auth_credentials_store` is overridden")
|
||||
}));
|
||||
@@ -6594,6 +6605,50 @@ async fn config_applies_managed_auth_store_and_chatgpt_base_url() -> std::io::Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chatgpt_backend_url_defaults_follow_captured_auth() -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let legacy = CodexAuth::from_api_key("legacy-key");
|
||||
let marked = CodexAuth::from_api_key("sk-proj-fedramp-test-key");
|
||||
let custom_url = "https://custom.example/backend-api/";
|
||||
for configured_url in [None, Some(custom_url), Some(DEFAULT_CHATGPT_BASE_URL)] {
|
||||
std::fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
configured_url
|
||||
.map(|url| format!("chatgpt_base_url = '{url}'\n"))
|
||||
.unwrap_or_default(),
|
||||
)?;
|
||||
let mut config = ConfigBuilder::without_managed_config_for_tests()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
let raw_url = configured_url.unwrap_or(DEFAULT_CHATGPT_BASE_URL);
|
||||
let raw_auth_config = config.auth_config();
|
||||
assert_eq!(
|
||||
config.chatgpt_base_url_is_explicit,
|
||||
configured_url.is_some()
|
||||
);
|
||||
for (auth, default_url) in [
|
||||
(&legacy, DEFAULT_CHATGPT_BASE_URL),
|
||||
(&marked, "https://gov.chatgpt.com/backend-api/"),
|
||||
(&legacy, DEFAULT_CHATGPT_BASE_URL),
|
||||
] {
|
||||
assert_eq!(
|
||||
config.chatgpt_backend_url().resolve(auth),
|
||||
configured_url.unwrap_or(default_url)
|
||||
);
|
||||
assert_eq!(config.chatgpt_base_url, raw_url);
|
||||
assert_eq!(config.auth_config(), raw_auth_config);
|
||||
}
|
||||
if configured_url.is_none() {
|
||||
config.chatgpt_base_url = custom_url.to_owned();
|
||||
assert_eq!(config.chatgpt_backend_url().resolve(&marked), custom_url);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn project_cannot_be_the_only_xaa_opt_in_source() -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
@@ -89,6 +89,8 @@ use codex_mcp::McpPluginAttribution;
|
||||
use codex_mcp::McpProtocolMode;
|
||||
use codex_mcp::McpServerRegistration;
|
||||
use codex_mcp::ResolvedMcpCatalog;
|
||||
use codex_model_provider::ChatgptBaseUrl;
|
||||
use codex_model_provider::DEFAULT_CHATGPT_BASE_URL;
|
||||
use codex_model_provider::ProviderCapabilities;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID;
|
||||
@@ -1066,6 +1068,9 @@ pub struct Config {
|
||||
/// Base URL for requests to ChatGPT (as opposed to the OpenAI API).
|
||||
pub chatgpt_base_url: String,
|
||||
|
||||
/// Whether configuration or managed requirements explicitly selected the ChatGPT base URL.
|
||||
pub chatgpt_base_url_is_explicit: bool,
|
||||
|
||||
/// Whether Codex-owned clients should respect host system proxy settings.
|
||||
pub respect_system_proxy: bool,
|
||||
|
||||
@@ -1758,6 +1763,15 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns backend routing that can resolve defaults against the request's auth snapshot.
|
||||
pub fn chatgpt_backend_url(&self) -> ChatgptBaseUrl {
|
||||
if !self.chatgpt_base_url_is_explicit && self.chatgpt_base_url == DEFAULT_CHATGPT_BASE_URL {
|
||||
ChatgptBaseUrl::Default
|
||||
} else {
|
||||
ChatgptBaseUrl::Configured(self.chatgpt_base_url.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns auth routing resolved from the effective feature configuration.
|
||||
pub fn auth_route_config(&self) -> AuthRouteConfig {
|
||||
self.application_auth_route_config
|
||||
@@ -3395,6 +3409,15 @@ impl Config {
|
||||
config_layer_stack.requirements(),
|
||||
&mut startup_warnings,
|
||||
);
|
||||
// Packaged defaults supply a URL even when no override was configured.
|
||||
let chatgpt_base_url_is_explicit =
|
||||
config_layer_stack.requirements().chatgpt_base_url.is_some()
|
||||
|| config_layer_stack
|
||||
.layers_high_to_low()
|
||||
.find(|layer| layer.config.get("chatgpt_base_url").is_some())
|
||||
.map_or(cfg.chatgpt_base_url.is_some(), |layer| {
|
||||
!matches!(layer.name, ConfigLayerSource::PackagedDefaults { .. })
|
||||
});
|
||||
// Destructure every field to ensure ConfigRequirements additions are
|
||||
// either applied above or handled while constructing the final Config.
|
||||
let ConfigRequirements {
|
||||
@@ -4631,9 +4654,10 @@ impl Config {
|
||||
model_reasoning_summary: cfg.model_reasoning_summary,
|
||||
model_catalog,
|
||||
model_verbosity: cfg.model_verbosity,
|
||||
chatgpt_base_url_is_explicit,
|
||||
chatgpt_base_url: cfg
|
||||
.chatgpt_base_url
|
||||
.unwrap_or("https://chatgpt.com/backend-api/".to_string()),
|
||||
.unwrap_or_else(|| DEFAULT_CHATGPT_BASE_URL.to_string()),
|
||||
respect_system_proxy,
|
||||
apps_mcp_product_sku: cfg.apps_mcp_product_sku.clone(),
|
||||
responses_api_metadata: cfg.responses_api_metadata.unwrap_or_default(),
|
||||
|
||||
@@ -33,9 +33,11 @@ use codex_config::config_toml::RealtimeWsMode;
|
||||
use codex_config::config_toml::RealtimeWsVersion;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::auth::is_fedramp_api_key;
|
||||
use codex_login::default_client::add_originator_header;
|
||||
use codex_login::default_client::default_headers;
|
||||
use codex_login::read_openai_api_key_from_env;
|
||||
use codex_model_provider::resolve_api_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::error::CodexErr;
|
||||
@@ -1442,6 +1444,12 @@ async fn prepare_realtime_start(
|
||||
let mut extra_headers = match transport {
|
||||
ConversationStartTransport::Websocket => {
|
||||
let realtime_api_key = realtime_api_key(auth.as_ref(), &provider)?;
|
||||
if realtime_sideband_base_url.is_none() {
|
||||
api_provider = resolve_api_provider(
|
||||
&provider,
|
||||
Some(&CodexAuth::from_api_key(&realtime_api_key)),
|
||||
)?;
|
||||
}
|
||||
realtime_request_headers(
|
||||
requested_realtime_session_id.as_deref(),
|
||||
params.voice_session_id.as_deref(),
|
||||
@@ -1990,6 +1998,9 @@ fn realtime_request_headers(
|
||||
CodexErr::InvalidRequest(format!("invalid realtime api key header: {err}"))
|
||||
})?;
|
||||
headers.insert(AUTHORIZATION, auth_value);
|
||||
if is_fedramp_api_key(api_key) {
|
||||
headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
||||
}
|
||||
}
|
||||
|
||||
add_originator_header(&mut headers, originator);
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::RealtimeSessionKind;
|
||||
use super::RealtimeStreamedItem;
|
||||
use super::classify_realtime_input_error;
|
||||
use super::classify_realtime_input_error_with_pending;
|
||||
use super::prepare_realtime_start;
|
||||
use super::realtime_delegation_from_handoff;
|
||||
use super::realtime_request_headers;
|
||||
use super::realtime_text_from_handoff_request;
|
||||
@@ -16,11 +17,16 @@ use crate::context::RealtimeDelegationSource;
|
||||
use async_channel::bounded;
|
||||
use codex_api::ApiError;
|
||||
use codex_api::RealtimeEventParser;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::models::MessagePhase;
|
||||
use codex_protocol::protocol::CodexResponseHandoffMode;
|
||||
use codex_protocol::protocol::ConversationStartParams;
|
||||
use codex_protocol::protocol::ConversationTextParams;
|
||||
use codex_protocol::protocol::ConversationTextRole;
|
||||
use codex_protocol::protocol::RealtimeConversationVersion;
|
||||
use codex_protocol::protocol::RealtimeHandoffRequested;
|
||||
use codex_protocol::protocol::RealtimeOutputModality;
|
||||
use codex_protocol::protocol::RealtimeTranscriptEntry;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -29,6 +35,97 @@ use std::time::Instant;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[tokio::test]
|
||||
async fn prepared_realtime_routing_follows_selected_api_key_and_explicit_overrides() {
|
||||
for (api_key, base_url, realtime_base_url, expected_url, expected_fedramp_header) in [
|
||||
("legacy-key", None, None, "https://api.openai.com/v1", None),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
None,
|
||||
None,
|
||||
"https://gov.api.openai.com/v1",
|
||||
Some("true"),
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
None,
|
||||
None,
|
||||
"https://gov.api.openai.com/v1",
|
||||
Some("true"),
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
Some("https://proxy.example/v1"),
|
||||
None,
|
||||
"https://proxy.example/v1",
|
||||
Some("true"),
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
Some("https://proxy.example/v1"),
|
||||
Some("wss://realtime.example/v1"),
|
||||
"wss://realtime.example/v1",
|
||||
Some("true"),
|
||||
),
|
||||
] {
|
||||
let (sess, _turn, _events) =
|
||||
crate::session::tests::make_session_and_context_with_auth_and_config_and_rx(
|
||||
CodexAuth::from_api_key("sk-proj-fedramp-ambient-test-key"),
|
||||
Vec::new(),
|
||||
|config| {
|
||||
config.model_provider = ModelProviderInfo {
|
||||
experimental_bearer_token: Some(api_key.into()),
|
||||
..ModelProviderInfo::create_openai_provider(base_url.map(str::to_string))
|
||||
};
|
||||
config.experimental_realtime_ws_base_url =
|
||||
realtime_base_url.map(str::to_string);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let prepared = prepare_realtime_start(
|
||||
&sess,
|
||||
ConversationStartParams {
|
||||
client_managed_handoffs: false,
|
||||
delegation_ack_filler: None,
|
||||
flush_transcript_tail_on_session_end: false,
|
||||
codex_responses_as_items: false,
|
||||
codex_response_item_prefix: None,
|
||||
codex_response_handoff_mode: CodexResponseHandoffMode::Thinking,
|
||||
backend_reasoning_status: false,
|
||||
codex_response_handoff_channel_prefixes: None,
|
||||
model: None,
|
||||
output_modality: RealtimeOutputModality::Audio,
|
||||
include_startup_context: false,
|
||||
initial_items: Vec::new(),
|
||||
realtime_start_instructions: None,
|
||||
realtime_end_instructions: None,
|
||||
prompt: None,
|
||||
realtime_session_id: None,
|
||||
voice_session_id: None,
|
||||
transport: None,
|
||||
version: Some(RealtimeConversationVersion::V1),
|
||||
voice: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("realtime startup should prepare without connecting");
|
||||
assert_eq!(prepared.api_provider.base_url, expected_url);
|
||||
let headers = prepared.extra_headers.expect("realtime request headers");
|
||||
assert_eq!(
|
||||
headers[http::header::AUTHORIZATION]
|
||||
.to_str()
|
||||
.expect("authorization should be ASCII"),
|
||||
format!("Bearer {api_key}")
|
||||
);
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("X-OpenAI-Fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
expected_fedramp_header
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hold old input cleanup open while a successor tries to claim the connection.
|
||||
#[tokio::test]
|
||||
async fn natural_close_finishes_before_successor_and_ignores_old_identity() {
|
||||
@@ -508,6 +605,8 @@ fn realtime_headers_keep_realtime_and_voice_session_ids_distinct() {
|
||||
.expect("headers")
|
||||
.expect("headers");
|
||||
|
||||
assert!(!headers.contains_key(http::header::AUTHORIZATION));
|
||||
assert!(!headers.contains_key("X-OpenAI-Fedramp"));
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("x-session-id")
|
||||
|
||||
@@ -1691,7 +1691,7 @@ impl Session {
|
||||
analytics_events_client.unwrap_or_else(|| {
|
||||
AnalyticsEventsClient::new(
|
||||
Arc::clone(&auth_manager),
|
||||
config.chatgpt_base_url.trim_end_matches('/').to_string(),
|
||||
config.chatgpt_backend_url(),
|
||||
config.analytics_enabled,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1483,8 +1483,14 @@ async fn resume_replays_image_tool_outputs_with_detail() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test_case::test_case("Test API Key", None; "legacy_key")]
|
||||
#[test_case::test_case("sk-proj-fedramp-synthetic-test-key", Some("true"); "fedramp_project_key")]
|
||||
#[test_case::test_case("sk-svcacct-fedramp-synthetic-test-key", Some("true"); "fedramp_service_account_key")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn includes_session_id_thread_id_and_model_headers_in_request() {
|
||||
async fn includes_session_id_thread_id_and_model_headers_in_request(
|
||||
api_key: &str,
|
||||
expected_fedramp_header: Option<&str>,
|
||||
) {
|
||||
skip_if_no_network!();
|
||||
|
||||
// Mock server
|
||||
@@ -1496,7 +1502,7 @@ async fn includes_session_id_thread_id_and_model_headers_in_request() {
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut builder = test_codex().with_auth(CodexAuth::from_api_key("Test API Key"));
|
||||
let mut builder = test_codex().with_auth(CodexAuth::from_api_key(api_key));
|
||||
let test = builder
|
||||
.build(&server)
|
||||
.await
|
||||
@@ -1511,7 +1517,7 @@ async fn includes_session_id_thread_id_and_model_headers_in_request() {
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await
|
||||
.unwrap();
|
||||
.expect("start test turn");
|
||||
|
||||
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
|
||||
|
||||
@@ -1534,7 +1540,11 @@ async fn includes_session_id_thread_id_and_model_headers_in_request() {
|
||||
assert_eq!(request_session_id, session_id_string.as_str());
|
||||
assert_eq!(request_thread_id, thread_id_string.as_str());
|
||||
assert_eq!(request_originator, originator().value);
|
||||
assert_eq!(request_authorization, "Bearer Test API Key");
|
||||
assert_eq!(request_authorization, format!("Bearer {api_key}"));
|
||||
assert_eq!(
|
||||
request.header("x-openai-fedramp").as_deref(),
|
||||
expected_fedramp_header
|
||||
);
|
||||
assert_eq!(
|
||||
request_body["prompt_cache_key"].as_str(),
|
||||
Some(session_id_string.as_str())
|
||||
|
||||
@@ -53,11 +53,8 @@ impl HistoryNotesBackend {
|
||||
}),
|
||||
);
|
||||
|
||||
let provider = self.provider.api_provider().await.map_err(|_| {
|
||||
format!("{OPERATION_ERROR_PREFIX} Could not resolve the backend provider.")
|
||||
})?;
|
||||
let auth = self.provider.api_auth().await.map_err(|_| {
|
||||
format!("{OPERATION_ERROR_PREFIX} Could not resolve backend authentication.")
|
||||
let (provider, auth) = self.provider.api_provider_and_auth().await.map_err(|_| {
|
||||
format!("{OPERATION_ERROR_PREFIX} Could not prepare the backend request.")
|
||||
})?;
|
||||
|
||||
let mut request = provider.build_request(Method::POST, path);
|
||||
|
||||
@@ -78,14 +78,9 @@ impl CodexImagesBackend {
|
||||
|
||||
/// Resolves the provider and auth required for the current image API request.
|
||||
async fn client(&self) -> Result<ImagesClient<ReqwestTransport>, ImageBackendError> {
|
||||
let provider = self
|
||||
let (provider, auth) = self
|
||||
.provider
|
||||
.api_provider()
|
||||
.await
|
||||
.map_err(|err| ImageBackendError::from_message(err.to_string()))?;
|
||||
let auth = self
|
||||
.provider
|
||||
.api_auth()
|
||||
.api_provider_and_auth()
|
||||
.await
|
||||
.map_err(|err| ImageBackendError::from_message(err.to_string()))?;
|
||||
let transport = create_transport_for_routes_async(
|
||||
|
||||
@@ -100,14 +100,9 @@ impl WebSearchTool {
|
||||
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
||||
let commands = parse_commands(&call)?;
|
||||
let command_action = command_action(&commands);
|
||||
let provider = self
|
||||
let (provider, auth) = self
|
||||
.provider
|
||||
.api_provider()
|
||||
.await
|
||||
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
|
||||
let auth = self
|
||||
.provider
|
||||
.api_auth()
|
||||
.api_provider_and_auth()
|
||||
.await
|
||||
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
|
||||
let transport = create_transport_for_routes_async(
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
//! API-key routing hints. Prefixes do not validate credentials or grant access.
|
||||
|
||||
/// Whether the key carries a FedRAMP issuance marker.
|
||||
///
|
||||
/// Unmarked keys may predate the marker, so `false` does not establish that a key
|
||||
/// is commercial. Authentication must still use the complete, unchanged key.
|
||||
pub fn is_fedramp_api_key(api_key: &str) -> bool {
|
||||
api_key.starts_with("sk-proj-fedramp-") || api_key.starts_with("sk-svcacct-fedramp-")
|
||||
}
|
||||
@@ -147,26 +147,32 @@ fn login_with_api_key_overwrites_existing_auth_json() {
|
||||
"account_id": "stale-acc"
|
||||
}
|
||||
});
|
||||
std::fs::write(
|
||||
&auth_path,
|
||||
serde_json::to_string_pretty(&stale_auth).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
super::login_with_api_key(
|
||||
dir.path(),
|
||||
for api_key in [
|
||||
"sk-new",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("login_with_api_key should succeed");
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
] {
|
||||
std::fs::write(
|
||||
&auth_path,
|
||||
serde_json::to_string_pretty(&stale_auth).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let storage = FileAuthStorage::new(dir.path().to_path_buf());
|
||||
let auth = storage
|
||||
.try_read_auth_json(&auth_path)
|
||||
.expect("auth.json should parse");
|
||||
assert_eq!(auth.openai_api_key.as_deref(), Some("sk-new"));
|
||||
assert!(auth.tokens.is_none(), "tokens should be cleared");
|
||||
super::login_with_api_key(
|
||||
dir.path(),
|
||||
api_key,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("login_with_api_key should succeed");
|
||||
|
||||
let storage = FileAuthStorage::new(dir.path().to_path_buf());
|
||||
let auth = storage
|
||||
.try_read_auth_json(&auth_path)
|
||||
.expect("auth.json should parse");
|
||||
assert_eq!(auth.openai_api_key.as_deref(), Some(api_key));
|
||||
assert!(auth.tokens.is_none(), "tokens should be cleared");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1138,30 +1144,47 @@ async fn loads_api_key_from_auth_json() {
|
||||
let dir = tempdir().unwrap();
|
||||
let _access_token_guard = remove_access_token_env_var();
|
||||
let auth_file = dir.path().join("auth.json");
|
||||
std::fs::write(
|
||||
auth_file,
|
||||
r#"{"OPENAI_API_KEY":"sk-test-key","tokens":null,"last_refresh":null}"#,
|
||||
)
|
||||
.unwrap();
|
||||
for (api_key, expected_fedramp) in [
|
||||
("sk-test-key", false),
|
||||
("sk-proj-fedramp-synthetic-test-key", true),
|
||||
("sk-svcacct-fedramp-synthetic-test-key", true),
|
||||
("sk-proj-synthetic-test-key", false),
|
||||
("sk-svcacct-synthetic-test-key", false),
|
||||
("sk-proj-fedramp", false),
|
||||
("sk-svcacct-fedrampish-test-key", false),
|
||||
("sk-proj-FEDRAMP-test-key", false),
|
||||
("sk-admin-fedramp-test-key", false),
|
||||
("other-sk-proj-fedramp-test-key", false),
|
||||
] {
|
||||
std::fs::write(
|
||||
&auth_file,
|
||||
json!({"OPENAI_API_KEY": api_key, "tokens": null, "last_refresh": null}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let auth = super::load_auth(
|
||||
dir.path(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*allowed_login_methods*/ None,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
/*agent_identity_authapi_base_url*/ None,
|
||||
&crate::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(auth.auth_mode(), AuthMode::ApiKey);
|
||||
assert_eq!(auth.api_key(), Some("sk-test-key"));
|
||||
let auth = super::load_auth(
|
||||
dir.path(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*allowed_login_methods*/ None,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
/*agent_identity_authapi_base_url*/ None,
|
||||
&crate::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(auth.auth_mode(), AuthMode::ApiKey);
|
||||
assert_eq!(auth.api_key(), Some(api_key));
|
||||
assert_eq!(
|
||||
(auth.get_token().unwrap(), auth.is_fedramp_account()),
|
||||
(api_key.to_string(), expected_fedramp)
|
||||
);
|
||||
|
||||
assert!(auth.get_token_data().is_err());
|
||||
assert!(auth.get_token_data().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -47,6 +47,7 @@ use super::agent_identity::record_needs_task_registration;
|
||||
use super::agent_identity::register_managed_chatgpt_agent_identity;
|
||||
use super::agent_identity::require_agent_identity_authapi_base_url;
|
||||
use super::agent_identity::verified_record_from_jwt;
|
||||
use super::api_key::is_fedramp_api_key;
|
||||
use super::change_state::AuthChangeState;
|
||||
use super::change_state::same_login;
|
||||
use super::change_state::same_owner;
|
||||
@@ -642,9 +643,10 @@ impl CodexAuth {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns false if Codex backend auth omits the FedRAMP claim.
|
||||
/// Returns whether auth carries a FedRAMP routing hint from a claim or API-key prefix.
|
||||
pub fn is_fedramp_account(&self) -> bool {
|
||||
match self {
|
||||
Self::ApiKey(auth) => is_fedramp_api_key(&auth.api_key),
|
||||
Self::Headers(_) => false,
|
||||
Self::AgentIdentity(auth) => auth.is_fedramp_account(),
|
||||
Self::PersonalAccessToken(auth) => auth.is_fedramp_account(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod access_token;
|
||||
mod agent_identity;
|
||||
mod api_key;
|
||||
mod auth_headers;
|
||||
mod bedrock_access_keys;
|
||||
mod bedrock_api_key;
|
||||
@@ -16,6 +17,7 @@ mod external_bearer;
|
||||
mod manager;
|
||||
mod revoke;
|
||||
|
||||
pub use api_key::is_fedramp_api_key;
|
||||
pub use auth_headers::AuthHeaders;
|
||||
pub use bedrock_access_keys::BedrockAccessKeysAuth;
|
||||
pub use bedrock_access_keys::login_with_bedrock_access_keys;
|
||||
|
||||
@@ -353,6 +353,23 @@ fn bearer_auth_for_provider(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Whether the selected API key enables OpenAI's default FedRAMP endpoints.
|
||||
/// Command-backed providers retain their configured routing across token refreshes.
|
||||
pub(crate) fn uses_fedramp_api_key(
|
||||
auth: Option<&CodexAuth>,
|
||||
provider: &ModelProviderInfo,
|
||||
) -> codex_protocol::error::Result<bool> {
|
||||
if !provider.is_openai() || provider.has_command_auth() {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(auth) = bearer_auth_for_provider(provider)? {
|
||||
return Ok(auth.is_fedramp_account);
|
||||
}
|
||||
Ok(provider.requires_openai_auth
|
||||
&& matches!(auth, Some(CodexAuth::ApiKey(_)))
|
||||
&& auth.is_some_and(CodexAuth::is_fedramp_account))
|
||||
}
|
||||
|
||||
/// Builds request-header auth for a first-party Codex auth snapshot.
|
||||
pub fn auth_provider_from_auth(auth: &CodexAuth) -> SharedAuthProvider {
|
||||
match auth {
|
||||
@@ -544,12 +561,14 @@ mod tests {
|
||||
"ChatGPT-Account-ID",
|
||||
HeaderValue::from_static("account-123"),
|
||||
);
|
||||
let ambient_auth = CodexAuth::Headers(AuthHeaders::new(ambient_headers));
|
||||
|
||||
let auth =
|
||||
resolve_provider_auth(Some(&ambient_auth), &provider).expect("auth should resolve");
|
||||
|
||||
assert!(auth.to_auth_headers().unwrap().is_empty());
|
||||
for ambient_auth in [
|
||||
CodexAuth::Headers(AuthHeaders::new(ambient_headers)),
|
||||
CodexAuth::from_api_key("sk-proj-fedramp-synthetic-test-key"),
|
||||
] {
|
||||
let auth =
|
||||
resolve_provider_auth(Some(&ambient_auth), &provider).expect("auth should resolve");
|
||||
assert!(auth.to_auth_headers().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -589,6 +608,41 @@ mod tests {
|
||||
assert_eq!(headers.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_fedramp_routing_follows_the_selected_provider_credential() {
|
||||
let project_key = "sk-proj-fedramp-synthetic-test-key";
|
||||
let service_account_key = "sk-svcacct-fedramp-synthetic-test-key";
|
||||
let legacy_key = "sk-proj-synthetic-test-key";
|
||||
|
||||
for (ambient_key, provider_key, expected_fedramp) in [
|
||||
(project_key, None, true),
|
||||
(service_account_key, None, true),
|
||||
(legacy_key, None, false),
|
||||
(project_key, Some(legacy_key), false),
|
||||
(legacy_key, Some(project_key), true),
|
||||
(legacy_key, Some(service_account_key), true),
|
||||
] {
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
provider.experimental_bearer_token = provider_key.map(Into::into);
|
||||
let ambient_auth = CodexAuth::from_api_key(ambient_key);
|
||||
|
||||
let headers = resolve_provider_auth(Some(&ambient_auth), &provider)
|
||||
.expect("auth should resolve")
|
||||
.to_auth_headers()
|
||||
.unwrap();
|
||||
|
||||
let key = provider_key.unwrap_or(ambient_key);
|
||||
let mut expected_headers = HeaderMap::from_iter([(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&format!("Bearer {key}")).unwrap(),
|
||||
)]);
|
||||
if expected_fedramp {
|
||||
expected_headers.insert("X-OpenAI-Fedramp", HeaderValue::from_static("true"));
|
||||
}
|
||||
assert_eq!(headers, expected_headers);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_uses_command_resolved_auth() {
|
||||
let mut provider =
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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;
|
||||
|
||||
@@ -13,10 +14,11 @@ pub struct BearerAuthProvider {
|
||||
|
||||
impl BearerAuthProvider {
|
||||
pub fn new(token: String) -> Self {
|
||||
let is_fedramp_account = is_fedramp_api_key(&token);
|
||||
Self {
|
||||
token: Some(token),
|
||||
account_id: None,
|
||||
is_fedramp_account: false,
|
||||
is_fedramp_account,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Resolves ChatGPT backend defaults from the credentials used for a request.
|
||||
//! Explicit endpoints remain authoritative across credential changes.
|
||||
|
||||
use codex_login::CodexAuth;
|
||||
|
||||
pub const DEFAULT_CHATGPT_BASE_URL: &str = "https://chatgpt.com/backend-api/";
|
||||
const FEDRAMP_CHATGPT_BASE_URL: &str = "https://gov.chatgpt.com/backend-api/";
|
||||
|
||||
/// A backend endpoint that retains whether configuration supplied an override.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ChatgptBaseUrl {
|
||||
#[default]
|
||||
Default,
|
||||
Configured(String),
|
||||
}
|
||||
|
||||
impl ChatgptBaseUrl {
|
||||
/// Resolve with the same captured credentials that will authenticate the request.
|
||||
pub fn resolve(&self, auth: &CodexAuth) -> &str {
|
||||
match self {
|
||||
Self::Configured(url) => url,
|
||||
Self::Default if auth.is_api_key_auth() && auth.is_fedramp_account() => {
|
||||
FEDRAMP_CHATGPT_BASE_URL
|
||||
}
|
||||
Self::Default => DEFAULT_CHATGPT_BASE_URL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ChatgptBaseUrl {
|
||||
fn from(url: String) -> Self {
|
||||
Self::Configured(url)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for ChatgptBaseUrl {
|
||||
fn from(url: &str) -> Self {
|
||||
Self::Configured(url.to_owned())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ mod amazon_bedrock;
|
||||
mod auth;
|
||||
mod bearer_auth_provider;
|
||||
mod capabilities;
|
||||
mod chatgpt_base_url;
|
||||
mod combined_auth;
|
||||
mod gcp;
|
||||
mod models_endpoint;
|
||||
@@ -27,6 +28,8 @@ pub use auth::unauthenticated_auth_provider;
|
||||
pub use bearer_auth_provider::BearerAuthProvider;
|
||||
pub use bearer_auth_provider::BearerAuthProvider as CoreAuthProvider;
|
||||
pub use capabilities::ProviderCapabilities;
|
||||
pub use chatgpt_base_url::ChatgptBaseUrl;
|
||||
pub use chatgpt_base_url::DEFAULT_CHATGPT_BASE_URL;
|
||||
pub use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
pub use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
pub use codex_model_provider_info::CHATGPT_CODEX_BASE_URL;
|
||||
@@ -43,6 +46,7 @@ pub use provider::ProviderUnauthorizedRecovery;
|
||||
pub use provider::SharedModelProvider;
|
||||
pub use provider::create_model_provider;
|
||||
pub use provider::provider_uses_first_party_auth_path;
|
||||
pub use provider::resolve_api_provider;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "workspace_routing_tests.rs"]
|
||||
|
||||
@@ -40,10 +40,13 @@ use tokio::time::timeout;
|
||||
use crate::auth::ResolvedProviderAuth;
|
||||
use crate::auth::agent_identity_telemetry;
|
||||
use crate::auth::resolve_provider_auth;
|
||||
use crate::auth::uses_fedramp_api_key;
|
||||
use crate::combined_auth::compose_auth;
|
||||
use crate::provider::resolve_api_provider;
|
||||
|
||||
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)]
|
||||
@@ -108,14 +111,19 @@ 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 = self.provider_info.to_api_provider(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 = CHATGPT_CODEX_BASE_URL.to_string();
|
||||
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 resolved = compose_auth(
|
||||
&self.provider_info,
|
||||
@@ -432,7 +440,6 @@ mod tests {
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::model_info::model_info_from_slug;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_protocol::openai_models::ModelVisibility;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
@@ -484,28 +491,59 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn api_key_discovery_respects_provider_routing() {
|
||||
let client_version = codex_models_manager::client_version_to_whole();
|
||||
for (name, base_url, models_url, inference_url) in [
|
||||
for (api_key, name, base_url, models_url, inference_url) in [
|
||||
(
|
||||
"test-api-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
Some("https://chatgpt.com/backend-api/codex/models"),
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"test-api-key",
|
||||
"OpenAI",
|
||||
Some("https://example.com/codex"),
|
||||
None,
|
||||
"https://example.com/codex",
|
||||
),
|
||||
(
|
||||
"test-api-key",
|
||||
"Azure",
|
||||
Some("https://example.openai.azure.com/openai/v1"),
|
||||
None,
|
||||
"https://example.openai.azure.com/openai/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
Some("https://gov.chatgpt.com/backend-api/codex/models"),
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
None,
|
||||
Some("https://gov.chatgpt.com/backend-api/codex/models"),
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"OpenAI",
|
||||
Some("https://example.com/codex"),
|
||||
None,
|
||||
"https://example.com/codex",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-synthetic-test-key",
|
||||
"Azure",
|
||||
None,
|
||||
None,
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
] {
|
||||
let capture = Arc::new(CaptureModelsUrl(Mutex::new(/*t*/ None)));
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key(api_key));
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo {
|
||||
name: name.to_string(),
|
||||
@@ -515,7 +553,11 @@ mod tests {
|
||||
gateway_auth_manager: None,
|
||||
transport_builder: capture.clone(),
|
||||
});
|
||||
let manager = OpenAiModelsManager::new_without_cache(endpoint.clone(), Some(auth));
|
||||
let provider = crate::provider::create_model_provider(
|
||||
endpoint.provider_info.clone(),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
let manager = OpenAiModelsManager::new_without_cache(endpoint, Some(auth));
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
manager
|
||||
.raw_model_catalog(
|
||||
@@ -528,11 +570,7 @@ mod tests {
|
||||
models_url.map(|url| format!("{url}?client_version={client_version}"))
|
||||
);
|
||||
assert_eq!(
|
||||
endpoint
|
||||
.provider_info
|
||||
.to_api_provider(Some(AuthMode::ApiKey))
|
||||
.unwrap()
|
||||
.base_url,
|
||||
provider.api_provider().await.unwrap().base_url,
|
||||
inference_url
|
||||
);
|
||||
}
|
||||
@@ -540,21 +578,59 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_api_key_without_endpoint_overrides_uses_codex_backend() {
|
||||
for auth in [
|
||||
None,
|
||||
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
for (api_key, auth, models_base_url, inference_url) in [
|
||||
(
|
||||
"provider-key",
|
||||
None,
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"provider-key",
|
||||
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
),
|
||||
(
|
||||
"provider-key",
|
||||
Some(CodexAuth::from_api_key("sk-proj-fedramp-ambient-key")),
|
||||
CHATGPT_CODEX_BASE_URL,
|
||||
"https://api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-provider-key",
|
||||
None,
|
||||
"https://gov.chatgpt.com/backend-api/codex",
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-svcacct-fedramp-provider-key",
|
||||
Some(CodexAuth::from_api_key("legacy-ambient-key")),
|
||||
"https://gov.chatgpt.com/backend-api/codex",
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
(
|
||||
"sk-proj-fedramp-provider-key",
|
||||
Some(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
"https://gov.chatgpt.com/backend-api/codex",
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
] {
|
||||
let capture = Arc::new(CaptureModelsUrl(Mutex::new(/*t*/ None)));
|
||||
let auth_manager = auth.map(AuthManager::from_auth_for_testing);
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint {
|
||||
provider_info: ModelProviderInfo {
|
||||
experimental_bearer_token: Some("provider-key".into()),
|
||||
experimental_bearer_token: Some(api_key.into()),
|
||||
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
|
||||
},
|
||||
auth_manager: auth_manager.clone(),
|
||||
gateway_auth_manager: None,
|
||||
transport_builder: capture.clone(),
|
||||
});
|
||||
let provider = crate::provider::create_model_provider(
|
||||
endpoint.provider_info.clone(),
|
||||
auth_manager.clone(),
|
||||
);
|
||||
let manager = OpenAiModelsManager::new_without_cache(endpoint, auth_manager);
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
manager
|
||||
@@ -566,10 +642,14 @@ mod tests {
|
||||
assert_eq!(
|
||||
*capture.0.lock().unwrap(),
|
||||
Some(format!(
|
||||
"{CHATGPT_CODEX_BASE_URL}/models?client_version={}",
|
||||
"{models_base_url}/models?client_version={}",
|
||||
codex_models_manager::client_version_to_whole(),
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
provider.api_provider().await.unwrap().base_url,
|
||||
inference_url
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,6 +679,13 @@ mod tests {
|
||||
);
|
||||
|
||||
assert!(endpoint.has_command_auth());
|
||||
let auth = CodexAuth::from_api_key("sk-proj-fedramp-command-key");
|
||||
assert_eq!(
|
||||
resolve_api_provider(&endpoint.provider_info, Some(&auth))
|
||||
.unwrap()
|
||||
.base_url,
|
||||
"https://api.openai.com/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -822,6 +909,8 @@ mod tests {
|
||||
for auth in [
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
CodexAuth::from_api_key("test-key"),
|
||||
CodexAuth::from_api_key("sk-proj-fedramp-synthetic-test-key"),
|
||||
CodexAuth::from_api_key("sk-svcacct-fedramp-synthetic-test-key"),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let mut model = model_info_from_slug("provider-model");
|
||||
|
||||
@@ -10,12 +10,13 @@ use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::auth::resolve_provider_auth;
|
||||
use crate::provider::resolve_api_provider;
|
||||
|
||||
pub(crate) fn identity(
|
||||
provider_info: &ModelProviderInfo,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> CoreResult<String> {
|
||||
let mut api_provider = provider_info.to_api_provider(auth.map(CodexAuth::auth_mode))?;
|
||||
let mut api_provider = resolve_api_provider(provider_info, auth)?;
|
||||
let mut digest = Sha256::new();
|
||||
// Length-prefix every field to avoid ambiguity between adjacent values.
|
||||
let mut field = |value: &[u8]| {
|
||||
|
||||
@@ -45,10 +45,10 @@ fn cache_identity_tracks_account_email_user_plan_and_auth_mode_but_not_token_ref
|
||||
|
||||
#[test]
|
||||
fn cache_identity_tracks_provider_routing_and_effective_api_credentials() {
|
||||
let auth = CodexAuth::from_api_key("first-key");
|
||||
let auth = CodexAuth::from_api_key("sk-proj-fedramp-synthetic-test-key");
|
||||
let provider = ModelProviderInfo::create_openai_provider(Some("https://one.example/v1".into()));
|
||||
let key = identity(&provider, Some(&auth)).unwrap();
|
||||
let other_key = CodexAuth::from_api_key("second-key");
|
||||
let other_key = CodexAuth::from_api_key("sk-proj-fedramp-rotated-test-key");
|
||||
assert_ne!(identity(&provider, Some(&other_key)).unwrap(), key);
|
||||
let mut other_provider = provider.clone();
|
||||
other_provider.base_url = Some("https://two.example/v1".into());
|
||||
@@ -62,6 +62,18 @@ fn cache_identity_tracks_provider_routing_and_effective_api_credentials() {
|
||||
"another-project".into(),
|
||||
)]));
|
||||
assert_ne!(identity(&other_provider, Some(&auth)).unwrap(), key);
|
||||
|
||||
let mut provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
// Keep identities stable while the endpoint residency test runs in parallel.
|
||||
provider.http_headers = Some(std::collections::HashMap::from([(
|
||||
codex_login::default_client::RESIDENCY_HEADER_NAME.to_string(),
|
||||
"us".into(),
|
||||
)]));
|
||||
let key = identity(&provider, Some(&auth)).unwrap();
|
||||
provider.base_url = Some("https://gov.api.openai.com/v1".into());
|
||||
assert_eq!(identity(&provider, Some(&auth)).unwrap(), key);
|
||||
provider.base_url = Some("https://api.openai.com/v1".into());
|
||||
assert_ne!(identity(&provider, Some(&auth)).unwrap(), key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -32,6 +32,7 @@ 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;
|
||||
@@ -93,6 +94,8 @@ pub const DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL: &str = "codex-auto-review";
|
||||
|
||||
const API_KEY_APPROVAL_REVIEW_PREFERRED_MODEL: &str = "gpt-5.6-luna";
|
||||
|
||||
const FEDRAMP_API_BASE_URL: &str = "https://gov.api.openai.com/v1";
|
||||
|
||||
/// Default model used for memory extraction when a provider does not require a
|
||||
/// backend-specific model ID.
|
||||
pub const DEFAULT_MEMORY_EXTRACTION_PREFERRED_MODEL: &str = "gpt-5.6-luna";
|
||||
@@ -216,6 +219,15 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the endpoint and authentication for one API client.
|
||||
/// Providers with credential-dependent routing should resolve both from the same auth read.
|
||||
fn api_provider_and_auth(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<(Provider, SharedAuthProvider)>>
|
||||
{
|
||||
Box::pin(async move { Ok((self.api_provider().await?, self.api_auth().await?)) })
|
||||
}
|
||||
|
||||
/// Resolves routing for Responses HTTP, compaction, and WebSocket handshakes.
|
||||
fn responses_api_provider<'a>(
|
||||
&'a self,
|
||||
@@ -277,7 +289,7 @@ pub trait ModelProvider: fmt::Debug + Send + Sync {
|
||||
&self,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> codex_protocol::error::Result<Provider> {
|
||||
self.info().to_api_provider(auth.map(CodexAuth::auth_mode))
|
||||
resolve_api_provider(self.info(), auth)
|
||||
}
|
||||
|
||||
/// Returns the provider base URL that will be used at request time.
|
||||
@@ -362,6 +374,18 @@ pub type ModelProviderFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a
|
||||
/// Shared runtime model provider handle.
|
||||
pub type SharedModelProvider = Arc<dyn ModelProvider>;
|
||||
|
||||
/// Resolve credential-dependent defaults without changing configured endpoints.
|
||||
pub fn resolve_api_provider(
|
||||
info: &ModelProviderInfo,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> codex_protocol::error::Result<Provider> {
|
||||
let mut provider = info.to_api_provider(auth.map(CodexAuth::auth_mode))?;
|
||||
if info.base_url.is_none() && uses_fedramp_api_key(auth, info)? {
|
||||
provider.base_url = FEDRAMP_API_BASE_URL.to_string();
|
||||
}
|
||||
Ok(provider)
|
||||
}
|
||||
|
||||
pub fn provider_uses_first_party_auth_path(provider: &ModelProviderInfo) -> bool {
|
||||
provider.requires_openai_auth
|
||||
&& provider.env_key.is_none()
|
||||
@@ -523,6 +547,22 @@ impl ModelProvider for ConfiguredModelProvider {
|
||||
})
|
||||
}
|
||||
|
||||
fn api_provider_and_auth(
|
||||
&self,
|
||||
) -> ModelProviderFuture<'_, codex_protocol::error::Result<(Provider, SharedAuthProvider)>>
|
||||
{
|
||||
Box::pin(async move {
|
||||
let auth = self.auth().await;
|
||||
let provider = self.api_provider_for_auth(auth.as_ref())?;
|
||||
let primary = resolve_provider_auth(auth.as_ref(), &self.info)?;
|
||||
let auth = self
|
||||
.compose_auth(ResolvedProviderAuth::new(primary))
|
||||
.await?
|
||||
.auth;
|
||||
Ok((provider, auth))
|
||||
})
|
||||
}
|
||||
|
||||
fn compose_auth(
|
||||
&self,
|
||||
resolved: ResolvedProviderAuth,
|
||||
@@ -627,6 +667,8 @@ impl ModelProvider for ConfiguredModelProvider {
|
||||
mod tests {
|
||||
use std::future::Future;
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::task::Context;
|
||||
use std::task::Waker;
|
||||
|
||||
@@ -851,8 +893,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
struct RotatingAuth(AtomicUsize);
|
||||
|
||||
impl codex_login::ExternalAuth for RotatingAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async move {
|
||||
let key = if self.0.fetch_add(1, Ordering::SeqCst).is_multiple_of(2) {
|
||||
"sk-proj-fedramp-synthetic-test-key"
|
||||
} else {
|
||||
"commercial-key"
|
||||
};
|
||||
Ok(CodexAuth::from_api_key(key))
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_context: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_provider_runtime_base_url_uses_configured_base_url() {
|
||||
async fn configured_provider_resolves_default_and_explicit_endpoints() {
|
||||
let provider = create_model_provider(
|
||||
provider_for("https://example.test/v1".to_string()),
|
||||
/*auth_manager*/ None,
|
||||
@@ -865,6 +929,79 @@ mod tests {
|
||||
.expect("runtime base URL should resolve"),
|
||||
Some("https://example.test/v1".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
provider.api_provider_and_auth().await.unwrap().0.base_url,
|
||||
"https://example.test/v1"
|
||||
);
|
||||
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let auth = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("initial-key"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
for (api_key, expected_base_url) in [
|
||||
("legacy-key", "https://api.openai.com/v1"),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"https://gov.api.openai.com/v1",
|
||||
),
|
||||
("commercial-key", "https://api.openai.com/v1"),
|
||||
] {
|
||||
codex_login::login_with_api_key(
|
||||
home.path(),
|
||||
api_key,
|
||||
codex_login::AuthCredentialsStoreMode::File,
|
||||
codex_login::AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.unwrap();
|
||||
auth.reload().await;
|
||||
let (api_provider, api_auth) = provider.api_provider_and_auth().await.unwrap();
|
||||
assert_eq!(api_provider.base_url, expected_base_url);
|
||||
let headers = api_auth.to_auth_headers().unwrap();
|
||||
assert_eq!(
|
||||
headers[http::header::AUTHORIZATION].to_str().unwrap(),
|
||||
format!("Bearer {api_key}")
|
||||
);
|
||||
}
|
||||
assert_eq!(provider.info().base_url, None);
|
||||
|
||||
let rotating_auth = Arc::new(RotatingAuth(AtomicUsize::new(0)));
|
||||
auth.set_external_auth(rotating_auth.clone()).await.unwrap();
|
||||
for (api_key, expected_base_url, expected_fedramp_header) in [
|
||||
("commercial-key", "https://api.openai.com/v1", None),
|
||||
(
|
||||
"sk-proj-fedramp-synthetic-test-key",
|
||||
"https://gov.api.openai.com/v1",
|
||||
Some("true"),
|
||||
),
|
||||
("commercial-key", "https://api.openai.com/v1", None),
|
||||
] {
|
||||
let reads_before = rotating_auth.0.load(Ordering::SeqCst);
|
||||
let (api_provider, api_auth) = provider.api_provider_and_auth().await.unwrap();
|
||||
assert_eq!(rotating_auth.0.load(Ordering::SeqCst), reads_before + 1);
|
||||
let headers = api_auth.to_auth_headers().unwrap();
|
||||
let expected_authorization = format!("Bearer {api_key}");
|
||||
assert_eq!(
|
||||
(
|
||||
api_provider.base_url.as_str(),
|
||||
headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
headers
|
||||
.get("X-OpenAI-Fedramp")
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
),
|
||||
(
|
||||
expected_base_url,
|
||||
Some(expected_authorization.as_str()),
|
||||
expected_fedramp_header,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -105,7 +105,7 @@ async fn gateway_credentials_accompany_primary_auth_in_models_and_responses() {
|
||||
models
|
||||
.raw_model_catalog(RefreshStrategy::Online, factory.clone())
|
||||
.await;
|
||||
let auth = provider.api_auth().await.unwrap();
|
||||
let (api, auth) = provider.api_provider_and_auth().await.unwrap();
|
||||
let scoped = provider
|
||||
.api_auth_for_scope(ProviderAuthScope {
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
@@ -137,7 +137,6 @@ async fn gateway_credentials_accompany_primary_auth_in_models_and_responses() {
|
||||
assert_eq!(auth.resolve_auth_headers().await.unwrap(), expected);
|
||||
assert_eq!(scoped.auth.to_auth_headers().unwrap(), expected);
|
||||
assert!(auth.to_auth_headers().unwrap()[name].is_sensitive());
|
||||
let api = info.to_api_provider(/*auth_mode*/ None).unwrap();
|
||||
let transport = ReqwestTransport::from_http_client(
|
||||
create_client_for_route(
|
||||
&factory,
|
||||
|
||||
@@ -358,6 +358,7 @@ async fn new_config(
|
||||
.chatgpt_base_url
|
||||
.clone()
|
||||
.unwrap_or_else(|| "https://chatgpt.com/backend-api/".to_string()),
|
||||
chatgpt_base_url_is_explicit: auth_config.chatgpt_base_url.is_some(),
|
||||
respect_system_proxy,
|
||||
apps_mcp_product_sku: None,
|
||||
responses_api_metadata: BTreeMap::new(),
|
||||
|
||||
Reference in New Issue
Block a user