mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Preserve primary authentication for OAuth gateways (#65117)
## Why When runtime authentication is enabled, a gateway endpoint outside the supported OpenAI runtime endpoints can fail runtime URL validation before Codex can use the configured gateway credentials. ## What changed For valid HTTPS gateway destinations on port 443 with a usable gateway OAuth configuration, preserve the primary API key or ChatGPT token alongside the gateway token and skip runtime authentication. Evaluate inference and model catalog URLs independently so supported OpenAI endpoints still use runtime authentication and invalid endpoints still fail validation. ## Testing Add regression coverage for model discovery and Responses requests in both runtime authentication modes. The tests check that gateway requests carry both credentials, omit the runtime assertion, and skip runtime registration. They also cover mixed inference and catalog destinations and rejection of invalid URLs. GitOrigin-RevId: d36d12412495c50c6643d615be8a7d72046c4d1c
This commit is contained in:
@@ -0,0 +1,271 @@
|
||||
//! Gateway runtime eligibility preserves primary authentication without leaking assertions.
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use base64::Engine;
|
||||
use codex_api::Compression;
|
||||
use codex_api::ResponsesClient;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::GatewayOAuthConfig;
|
||||
use codex_model_provider_info::GatewayOAuthDelivery;
|
||||
use codex_model_provider_info::GatewayOAuthSettings;
|
||||
use codex_model_provider_info::OAuthCredentialsStore;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::model_info::model_info_from_slug;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::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;
|
||||
|
||||
fn gateway_info(base: &str, catalog: &str) -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
name: "Custom gateway".into(),
|
||||
model_catalog_url: Some(catalog.to_string().into()),
|
||||
env_http_headers: None,
|
||||
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
|
||||
authorization_url: "https://login.example.test/authorize".into(),
|
||||
device_authorization_url: None,
|
||||
token_url: "https://login.example.test/token".into(),
|
||||
client_id: "test-client".into(),
|
||||
resource: None,
|
||||
scopes: Vec::new(),
|
||||
redirect_port: None,
|
||||
credentials_store: OAuthCredentialsStore::File,
|
||||
delivery: GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
},
|
||||
})),
|
||||
..ModelProviderInfo::create_openai_provider(Some(base.into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime(server: &MockServer, credentials: &Arc<AuthManager>) -> Arc<RuntimeAuthManager> {
|
||||
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!("{}/agent/register", server.uri()).parse().unwrap(),
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dual_header_gateway_keeps_primary_and_gateway_auth_without_registration() {
|
||||
gateway_keeps_primary_and_gateway_auth_without_registration(RuntimeAuthMode::DualHeader).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assertion_only_gateway_keeps_primary_and_gateway_auth_without_registration() {
|
||||
gateway_keeps_primary_and_gateway_auth_without_registration(RuntimeAuthMode::AssertionOnly)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn gateway_keeps_primary_and_gateway_auth_without_registration(mode: RuntimeAuthMode) {
|
||||
let claims = json!({"session_id":"session-a","https://api.openai.com/auth":{"user_id":"user-a","chatgpt_account_id":"workspace-a"}});
|
||||
let access_token = format!(
|
||||
"e30.{}.signature",
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())
|
||||
);
|
||||
for primary in [
|
||||
CodexAuth::from_api_key("test-api-key"),
|
||||
CodexAuth::from_external_chatgpt_tokens(
|
||||
&access_token,
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap(),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let expected_primary = if primary.is_api_key_auth() {
|
||||
"Bearer test-api-key".to_owned()
|
||||
} else {
|
||||
format!("Bearer {access_token}")
|
||||
};
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing_with_home(primary, home.path().to_path_buf());
|
||||
let info = gateway_info(
|
||||
"https://gateway.internal.api.openai.org/v1",
|
||||
"https://gateway.internal.api.openai.org/v1/models?format=codex",
|
||||
);
|
||||
crate::test_support::seed_gateway_auth(
|
||||
&info,
|
||||
&credentials,
|
||||
json!({"access_token":"gateway-token","refresh_token":"gateway-refresh","expires_at":i64::MAX}),
|
||||
);
|
||||
let mut provider = ConfiguredModelProvider::new(
|
||||
info.clone(),
|
||||
Some(Arc::clone(&credentials)),
|
||||
Some((runtime(&server, &credentials), mode)),
|
||||
);
|
||||
let mut prepared = crate::resolve_request(
|
||||
&provider,
|
||||
/*scope*/ None,
|
||||
/*routing*/ None,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(prepared.runtime_id, None);
|
||||
let inference_headers = prepared
|
||||
.api_auth
|
||||
.apply_auth_headers(prepared.api_provider.headers.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(inference_headers["authorization"], expected_primary);
|
||||
assert_eq!(inference_headers["x-gateway-auth"], "Bearer gateway-token");
|
||||
assert!(!inference_headers.contains_key("x-openai-agent-assertion"));
|
||||
|
||||
let model = model_info_from_slug("gateway-sentinel-model");
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(ModelsResponse {
|
||||
models: vec![model.clone()],
|
||||
}))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/responses"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "text/event-stream")
|
||||
.set_body_string(
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r\"}}\n\n",
|
||||
),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
// Eligibility was selected from the real HTTPS gateway URLs. Substitute only
|
||||
// transport destinations so production catalog/Responses clients reach the fixture.
|
||||
provider.info.base_url = Some(server.uri());
|
||||
provider.info.model_catalog_url = Some(format!("{}/models", server.uri()).into());
|
||||
let models = provider.models_manager_without_cache(/*config_model_catalog*/ None);
|
||||
models.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let catalog = models
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::Online,
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
catalog
|
||||
.models
|
||||
.iter()
|
||||
.find(|candidate| candidate.slug == model.slug),
|
||||
Some(&model)
|
||||
);
|
||||
|
||||
prepared.api_provider.base_url = server.uri();
|
||||
let transport = prepared.http_transport("responses").unwrap();
|
||||
let client = ResponsesClient::new(transport, prepared.api_provider, prepared.api_auth);
|
||||
let _stream = client
|
||||
.stream(
|
||||
json!({"model": "test", "input": []}),
|
||||
http::HeaderMap::new(),
|
||||
Compression::None,
|
||||
/*turn_state*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
server.verify().await;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for request in requests {
|
||||
assert_eq!(request.headers["authorization"], expected_primary);
|
||||
assert_eq!(request.headers["x-gateway-auth"], "Bearer gateway-token");
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
assert_ne!(request.url.path(), "/agent/register");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_runtime_eligibility_is_destination_specific_and_fail_closed() {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let credentials = AuthManager::from_auth_for_testing_with_home(
|
||||
CodexAuth::from_api_key("test-api-key"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let runtime = runtime(&server, &credentials);
|
||||
let gateway = "https://gateway.internal.api.openai.org/v1";
|
||||
let supported = "https://api.openai.com/v1";
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for (base, catalog, expected) in [
|
||||
(gateway, gateway, (None, None)),
|
||||
(gateway, supported, (None, Some(mode))),
|
||||
(supported, gateway, (Some(mode), None)),
|
||||
(supported, supported, (Some(mode), Some(mode))),
|
||||
] {
|
||||
let provider = ConfiguredModelProvider::new(
|
||||
gateway_info(base, catalog),
|
||||
Some(Arc::clone(&credentials)),
|
||||
Some((Arc::clone(&runtime), mode)),
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
provider.runtime_auth.as_ref().map(|(_, mode)| *mode),
|
||||
provider
|
||||
.catalog_runtime_auth
|
||||
.as_ref()
|
||||
.map(|(_, mode)| *mode),
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
for destination in [
|
||||
"http://api.openai.com/v1",
|
||||
"https://api.openai.com:8443/v1",
|
||||
"https://user@api.openai.com/v1",
|
||||
"https://api.openai.com../v1",
|
||||
"https://gateway.internal.api.openai.org:8443/v1",
|
||||
"https://gateway.internal.api.openai.org/v1#fragment",
|
||||
] {
|
||||
let provider = ConfiguredModelProvider::new(
|
||||
gateway_info(destination, destination),
|
||||
Some(Arc::clone(&credentials)),
|
||||
Some((Arc::clone(&runtime), mode)),
|
||||
);
|
||||
assert!(provider.runtime_auth.is_some(), "{mode:?} {destination}");
|
||||
assert!(
|
||||
provider.request_auth(/*scope*/ None).await.is_err(),
|
||||
"{mode:?} {destination}"
|
||||
);
|
||||
}
|
||||
let mut without_gateway_auth = gateway_info(gateway, gateway);
|
||||
without_gateway_auth.gateway_oauth = None;
|
||||
let provider = ConfiguredModelProvider::new(
|
||||
without_gateway_auth,
|
||||
Some(Arc::clone(&credentials)),
|
||||
Some((Arc::clone(&runtime), mode)),
|
||||
);
|
||||
assert!(
|
||||
provider
|
||||
.request_auth(/*scope*/ None)
|
||||
.await
|
||||
.err()
|
||||
.expect("unsupported destination must fail")
|
||||
.to_string()
|
||||
.contains("runtime auth does not support this OpenAI endpoint"),
|
||||
"{mode:?}"
|
||||
);
|
||||
}
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
@@ -505,9 +505,26 @@ impl ConfiguredModelProvider {
|
||||
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
|
||||
destination.is_none_or(|destination| {
|
||||
match codex_http_client::classify_openai_api_url(destination) {
|
||||
codex_http_client::OpenAiDestination::Supported => true,
|
||||
codex_http_client::OpenAiDestination::Other => false,
|
||||
codex_http_client::OpenAiDestination::Unsupported => {
|
||||
// Configured gateways use their own authentication in either runtime
|
||||
// mode. Other unsupported OpenAI origins still reach URL validation.
|
||||
!(gateway_auth_manager.as_ref().is_some_and(Result::is_ok)
|
||||
&& codex_http_client::validate_https_endpoint_url(
|
||||
destination,
|
||||
"model provider destination",
|
||||
)
|
||||
.is_ok_and(|url| {
|
||||
url.port_or_known_default() == Some(443)
|
||||
&& url.host_str().is_some_and(|host| {
|
||||
host.split('.').all(|label| !label.is_empty())
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
@@ -789,3 +806,7 @@ pub(crate) mod test_support {
|
||||
#[cfg(test)]
|
||||
#[path = "provider_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gateway_runtime_tests.rs"]
|
||||
mod gateway_runtime_tests;
|
||||
|
||||
Reference in New Issue
Block a user