Extend OAuth configuration for managed gateways (#65188)

## Why

Setting custom OAuth scopes or a client ID for a managed gateway required
hard-coding the authorization and token URLs, even when the server
published them through discovery.

## What changed

Omit both `authorization_url` and `token_url` in `[gateway.auth]` or
`[config_server.oauth]` to discover the endpoints while configuring
`client_id`, `scopes`, `resource`, `redirect_port`, or
`device_authorization_url`. An OAuth block that relies on discovery
produces an error if metadata is unavailable.

Managed gateways can also set `gateway.requires_openai_auth` and
`gateway.auth.delivery` for inference. For example, a gateway can use
`Authorization` for the OpenAI credential and receive its OAuth token
in `X-Gateway-Authorization`. Enrollment rejects configurations that
would send both credentials in `Authorization`.

## Testing

Add coverage for discovery overrides, missing discovery metadata,
invalid OAuth settings, and gateway token delivery.

GitOrigin-RevId: 84e0c219c9eb78d4be538e9131e15ab39fd597b9
This commit is contained in:
arnavpatidar-OAI
2026-12-02 07:13:07 +00:00
committed by copyberry
parent 7f7a1aa16d
commit 283fca1c98
8 changed files with 259 additions and 53 deletions
+8 -5
View File
@@ -240,7 +240,7 @@ pub async fn config_server_auth_manager(
let resolution = resolve_config_server(service_config, routes, previous).await?;
let factory = config_server_http_client_factory(&resolution.resolved, routes);
let manager =
oauth_session_manager(resolution.resolved.oauth.as_deref(), codex_home, &factory)?;
oauth_session_manager(resolution.resolved.explicit_oauth(), codex_home, &factory)?;
Ok((resolution, manager))
}
@@ -255,11 +255,14 @@ fn config_server_http_client_factory(
let endpoints = endpoint
.as_deref()
.into_iter()
.chain(config.oauth.as_ref().map(|oauth| oauth.token_url.as_str()))
.chain(
config
.oauth
.as_ref()
.explicit_oauth()
.map(|oauth| oauth.token_url.as_str()),
)
.chain(
config
.explicit_oauth()
.and_then(|oauth| oauth.device_authorization_url.as_deref()),
)
.filter_map(|endpoint| endpoint.parse().ok());
@@ -305,7 +308,7 @@ impl ConfigServerSource {
})?;
Self::new(
base_url,
config.oauth.map(|oauth| *oauth),
config.explicit_oauth().cloned(),
codex_home,
factory,
)
@@ -8,6 +8,7 @@ use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT;
use crate::service::CloudConfigBundleService;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigServer;
use codex_config::ConfigServerOAuth;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_keyring_store::tests::MockKeyringStore;
use codex_login::test_support::transport_default_auth_route_config;
@@ -138,7 +139,9 @@ async fn a_supplied_chatgpt_token_does_not_replace_config_server_sign_in() {
let requirements = codex_config::ConfigRequirementsToml {
config_server: Some(ConfigServer {
base_url: format!("{endpoint}/settings"),
oauth: Some(Box::new(oauth_config(&endpoint))),
oauth: Some(Box::new(ConfigServerOAuth::Explicit(oauth_config(
&endpoint,
)))),
}),
..Default::default()
};
@@ -215,7 +218,9 @@ async fn policy_reload_reuses_discovery_only_for_the_same_config_server() {
config_server: Some(server(base_url)),
..Default::default()
};
let oauth = Box::new(oauth_config("https://login.example"));
let oauth = Box::new(ConfigServerOAuth::Explicit(oauth_config(
"https://login.example",
)));
let system = HttpClientFactory::new(codex_http_client::OutboundProxyPolicy::RespectSystemProxy);
let fallback = default.clone().with_system_proxy_fallback();
for (previous_url, discovered_oauth, factory, reuse) in [
+35 -21
View File
@@ -2,6 +2,7 @@
//! Explicit OAuth settings take precedence, and discovered settings stay in memory.
use codex_config::ConfigServer;
use codex_config::ConfigServerOAuth;
use codex_config::ConfigServerResolution;
use codex_exec_server::RouteAwareHttpClient;
use codex_login::AuthRouteConfig;
@@ -34,14 +35,13 @@ pub(crate) async fn resolve_config_server(
.map_err(io::Error::other)?;
return Ok(previous.clone());
}
let mut resolved = config.clone();
if config.oauth.is_none()
&& let Some(oauth) = discover_oauth(&config.base_url, routes).await?
{
resolved.oauth = Some(Box::new(oauth));
resolved.validated_base_url().map_err(io::Error::other)?;
}
let resolved = ConfigServer {
base_url: config.base_url.clone(),
oauth: resolve_oauth(&config.base_url, routes, config.oauth.as_deref())
.await?
.map(|oauth| Box::new(ConfigServerOAuth::Explicit(oauth))),
};
resolved.validated_base_url().map_err(io::Error::other)?;
Ok(ConfigServerResolution {
outbound_proxy_policy,
@@ -51,10 +51,16 @@ pub(crate) async fn resolve_config_server(
})
}
async fn discover_oauth(
async fn resolve_oauth(
issuer: &str,
routes: &AuthRouteConfig,
configured: Option<&ConfigServerOAuth>,
) -> io::Result<Option<OAuthSessionConfig>> {
let overrides = match configured {
Some(ConfigServerOAuth::Explicit(session)) => return Ok(Some(session.clone())),
Some(ConfigServerOAuth::Discover(overrides)) => Some(overrides),
None => None,
};
let client = Arc::new(RouteAwareHttpClient::new(
routes.bootstrap_http_client_factory().clone(),
));
@@ -66,25 +72,33 @@ async fn discover_oauth(
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "OAuth discovery timed out"))?
.map_err(|_| io::Error::other("OAuth discovery failed"))?;
let Some(metadata) = metadata else {
if overrides.is_some() {
return Err(io::Error::other(
"OAuth metadata unavailable; publish discovery metadata or set authorization_url and token_url",
));
}
return Ok(None);
};
let device_authorization_url = metadata
.additional_fields
.get("device_authorization_endpoint")
.map(Option::<String>::deserialize)
.transpose()
.map_err(|_| io::Error::other("OAuth discovery device endpoint is invalid"))?
.flatten();
let overrides = overrides.cloned().unwrap_or_default();
let device_authorization_url = match overrides.device_authorization_url {
Some(url) => Some(url),
None => metadata
.additional_fields
.get("device_authorization_endpoint")
.map(Option::<String>::deserialize)
.transpose()
.map_err(|_| io::Error::other("OAuth discovery device endpoint is invalid"))?
.flatten(),
};
Ok(Some(OAuthSessionConfig {
authorization_url: metadata.authorization_endpoint,
token_url: metadata.token_endpoint,
device_authorization_url,
client_id: String::from("codex"),
resource: None,
scopes: Vec::new(),
redirect_port: None,
client_id: overrides.client_id.unwrap_or_else(|| String::from("codex")),
resource: overrides.resource,
scopes: overrides.scopes,
redirect_port: overrides.redirect_port,
credentials_store: Default::default(),
}))
}
+87 -13
View File
@@ -3,9 +3,11 @@
//! Tests config-server OAuth defaults, discovery activation, and routing.
use super::DISCOVERY_TIMEOUT;
use super::discover_oauth;
use super::resolve_config_server;
use super::resolve_oauth;
use codex_config::ConfigServer;
use codex_config::ConfigServerOAuth;
use codex_config::OAuthDiscoveryOverrides;
use codex_login::AuthRouteConfig;
use codex_login::OAuthSessionConfig;
use codex_login::test_support::transport_default_auth_route_config;
@@ -34,6 +36,13 @@ async fn applies_company_defaults_and_optional_device_endpoint() {
let server = MockServer::start().await;
for device_url in [None, Some("https://login.example/device")] {
server.reset().await;
Mock::given(path("/"))
.respond_with(
ResponseTemplate::new(401)
.insert_header("WWW-Authenticate", "Bearer scope=\"read\""),
)
.mount(&server)
.await;
let mut metadata = metadata(&server.uri());
if let Some(device_url) = device_url {
metadata["device_authorization_endpoint"] = json!(device_url);
@@ -44,9 +53,13 @@ async fn applies_company_defaults_and_optional_device_endpoint() {
.mount(&server)
.await;
assert_eq!(
discover_oauth(&server.uri(), &transport_default_auth_route_config())
.await
.unwrap(),
resolve_oauth(
&server.uri(),
&transport_default_auth_route_config(),
/*configured*/ None
)
.await
.unwrap(),
Some(OAuthSessionConfig {
authorization_url: "https://login.example/authorize".into(),
token_url: "https://login.example/token".into(),
@@ -61,6 +74,55 @@ async fn applies_company_defaults_and_optional_device_endpoint() {
}
}
#[tokio::test]
async fn discovers_endpoints_and_uses_configured_scopes() {
let server = MockServer::start().await;
let routes = transport_default_auth_route_config();
let overrides = OAuthDiscoveryOverrides {
client_id: Some("company-client".into()),
scopes: vec!["read".into(), "offline_access".into()],
redirect_port: Some(14567),
resource: Some("api://gateway".into()),
..Default::default()
};
let configured = ConfigServerOAuth::Discover(overrides.clone());
// Configured OAuth never silently becomes anonymous.
let error = resolve_oauth(&server.uri(), &routes, Some(&configured))
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("authorization_url and token_url")
);
Mock::given(path("/.well-known/oauth-protected-resource"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": server.uri(),
"authorization_servers": [server.uri()],
"scopes_supported": ["read", "admin"],
})))
.mount(&server)
.await;
Mock::given(path("/.well-known/oauth-authorization-server"))
.respond_with(ResponseTemplate::new(200).set_body_json(metadata(&server.uri())))
.mount(&server)
.await;
let default_session = resolve_oauth(&server.uri(), &routes, /*configured*/ None)
.await
.unwrap()
.unwrap();
assert!(default_session.scopes.is_empty());
let session = resolve_oauth(&server.uri(), &routes, Some(&configured))
.await
.unwrap()
.unwrap();
assert_eq!(session.client_id, overrides.client_id.unwrap());
assert_eq!(session.scopes, overrides.scopes);
assert_eq!(session.redirect_port, overrides.redirect_port);
assert_eq!(session.resource, overrides.resource);
}
#[tokio::test]
async fn rejects_invalid_device_endpoint() {
let server = MockServer::start().await;
@@ -71,9 +133,13 @@ async fn rejects_invalid_device_endpoint() {
.expect(1)
.mount(&server)
.await;
let error = discover_oauth(&server.uri(), &transport_default_auth_route_config())
.await
.unwrap_err();
let error = resolve_oauth(
&server.uri(),
&transport_default_auth_route_config(),
/*configured*/ None,
)
.await
.unwrap_err();
assert_eq!(
error.to_string(),
"OAuth discovery device endpoint is invalid"
@@ -92,9 +158,13 @@ async fn bounds_company_discovery_duration() {
.expect(1)
.mount(&server)
.await;
let error = discover_oauth(&server.uri(), &transport_default_auth_route_config())
.await
.unwrap_err();
let error = resolve_oauth(
&server.uri(),
&transport_default_auth_route_config(),
/*configured*/ None,
)
.await
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
@@ -117,7 +187,7 @@ async fn preserves_explicit_oauth_without_discovery() {
let config = ConfigServer {
base_url: format!("https://{address}"),
oauth: Some(Box::new(explicit_oauth)),
oauth: Some(Box::new(ConfigServerOAuth::Explicit(explicit_oauth))),
};
assert_eq!(
resolve_config_server(&config, &routes, /*previous*/ None)
@@ -156,7 +226,7 @@ async fn discovery_obeys_local_network_policy_without_requiring_fetched_policy()
.mount(&server)
.await;
assert!(
discover_oauth(&server.uri(), &routes)
resolve_oauth(&server.uri(), &routes, /*configured*/ None)
.await
.unwrap()
.is_some()
@@ -165,6 +235,10 @@ async fn discovery_obeys_local_network_policy_without_requiring_fetched_policy()
server.reset().await;
let routes =
AuthRouteConfig::from_http_client_factory(allowed).with_local_bootstrap_factory(blocked);
assert!(discover_oauth(&server.uri(), &routes).await.is_err());
assert!(
resolve_oauth(&server.uri(), &routes, /*configured*/ None)
.await
.is_err()
);
assert!(server.received_requests().await.unwrap().is_empty());
}
+54 -6
View File
@@ -1,11 +1,38 @@
//! Trusted enrollment settings for a customer-hosted configuration server.
//!
use codex_model_provider_info::OAuthSessionConfig;
use serde::Deserialize;
use serde::Serialize;
use std::fmt;
pub use codex_model_provider_info::OAuthSessionConfig as ConfigServerOAuth;
/// Either supply both endpoints or let the config server publish them.
#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(
untagged,
expecting = "OAuth settings with both authorization_url and token_url (and client_id), or neither endpoint for discovery"
)]
pub enum ConfigServerOAuth {
Explicit(OAuthSessionConfig),
Discover(OAuthDiscoveryOverrides),
}
#[derive(Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct OAuthDiscoveryOverrides {
pub client_id: Option<String>,
#[serde(default)]
pub scopes: Vec<String>,
pub resource: Option<String>,
pub redirect_port: Option<u16>,
pub device_authorization_url: Option<String>,
}
impl fmt::Debug for ConfigServerOAuth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConfigServerOAuth").finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(try_from = "ConfigServerInput")]
@@ -45,6 +72,13 @@ impl TryFrom<ConfigServerInput> for ConfigServer {
}
impl ConfigServer {
pub fn explicit_oauth(&self) -> Option<&OAuthSessionConfig> {
match self.oauth.as_deref()? {
ConfigServerOAuth::Explicit(oauth) => Some(oauth),
ConfigServerOAuth::Discover(_) => None,
}
}
/// Validates the trusted settings and returns the normalized base URL.
pub fn validated_base_url(&self) -> Result<String, String> {
let validate_https_url = |value: &str| {
@@ -57,13 +91,27 @@ impl ConfigServer {
if endpoint.query().is_some() {
return Err("config_server.base_url must not contain a query".into());
}
if let Some(oauth) = &self.oauth {
validate_https_url(&oauth.authorization_url)?;
validate_https_url(&oauth.token_url)?;
if let Some(url) = &oauth.device_authorization_url {
if let Some(oauth) = self.oauth.as_deref() {
let (client_id, port, device_url) = match oauth {
ConfigServerOAuth::Explicit(oauth) => {
validate_https_url(&oauth.authorization_url)?;
validate_https_url(&oauth.token_url)?;
(
Some(oauth.client_id.as_str()),
oauth.redirect_port,
&oauth.device_authorization_url,
)
}
ConfigServerOAuth::Discover(oauth) => (
oauth.client_id.as_deref(),
oauth.redirect_port,
&oauth.device_authorization_url,
),
};
if let Some(url) = device_url {
validate_https_url(url)?;
}
if oauth.client_id.trim().is_empty() || oauth.redirect_port == Some(0) {
if client_id.is_some_and(|id| id.trim().is_empty()) || port == Some(0) {
return Err("config_server OAuth requires a client ID and a nonzero redirect port when specified".into());
}
}
+1
View File
@@ -158,6 +158,7 @@ pub use config_requirements::sandbox_mode_requirement_for_permission_profile;
pub use config_server::ConfigServer;
pub use config_server::ConfigServerOAuth;
pub use config_server::ConfigServerResolution;
pub use config_server::OAuthDiscoveryOverrides;
pub use config_toml::effective_sandbox_mode;
pub use constraint::Constrained;
pub use constraint::ConstraintError;
@@ -7,6 +7,7 @@ use crate::ConfigServer;
use crate::ConfigServerOAuth;
use crate::ConfigServerResolution;
use codex_model_provider_info::GatewayOAuthConfig;
use codex_model_provider_info::GatewayOAuthDelivery;
use codex_model_provider_info::GatewayOAuthSettings;
use codex_model_provider_info::ModelProviderInfo;
use codex_model_provider_info::WireApi;
@@ -22,7 +23,17 @@ use toml::Value;
pub struct GatewayRequirementsToml {
name: Option<String>,
base_url: RedactedString,
auth: Option<Box<ConfigServerOAuth>>,
#[serde(default)]
requires_openai_auth: bool,
auth: Option<Box<GatewayAuth>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
struct GatewayAuth {
#[serde(default)]
delivery: GatewayOAuthDelivery,
#[serde(flatten)]
oauth: ConfigServerOAuth,
}
impl GatewayRequirementsToml {
@@ -30,9 +41,13 @@ impl GatewayRequirementsToml {
self,
resolution: Option<&ConfigServerResolution>,
) -> Result<toml::Table, String> {
let (oauth, delivery) = match self.auth {
Some(auth) => (Some(Box::new(auth.oauth)), auth.delivery),
None => (None, GatewayOAuthDelivery::default()),
};
let mut server = ConfigServer {
base_url: self.base_url.into_inner(),
oauth: self.auth,
oauth,
};
let root = server
.validated_base_url()
@@ -48,17 +63,17 @@ impl GatewayRequirementsToml {
// Keep the enrolled server unchanged for policy matching. Inference uses the same
// OAuth settings that fetched the policy, once discovery has run for this enrollment.
let auth = server.oauth.as_deref().or_else(|| {
let auth = server.explicit_oauth().or_else(|| {
resolution
.filter(|resolution| resolution.configured == server)
.and_then(|resolution| resolution.resolved.oauth.as_deref())
.and_then(|resolution| resolution.resolved.explicit_oauth())
});
let provider = ModelProviderInfo {
name: name.to_owned(),
base_url: Some(format!("{root}/v1")),
model_catalog_url: Some(format!("{root}/v1/models").into()),
wire_api: WireApi::Responses,
requires_openai_auth: false,
requires_openai_auth: self.requires_openai_auth,
gateway_oauth: auth.cloned().map(|auth| {
GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
authorization_url: auth.authorization_url,
@@ -69,12 +84,14 @@ impl GatewayRequirementsToml {
scopes: auth.scopes,
redirect_port: auth.redirect_port,
credentials_store: auth.credentials_store,
delivery: Default::default(),
delivery,
})
}),
..Default::default()
};
provider.validate()?;
let server = Value::try_from(server).map_err(|err| err.to_string())?;
let provider = Value::try_from(provider).map_err(|err| err.to_string())?;
Ok(toml::toml! {
@@ -2298,6 +2298,42 @@ requires_openai_auth = false
);
}
#[test]
fn gateway_keeps_provider_auth_out_of_config_server_oauth() {
let expected = expected_requirements(format!(
"[config_server]\nbase_url = 'https://gateway.example'\n[config_server.oauth]\n{GATEWAY_AUTH}"
));
for (opt_in, requires_openai_auth) in [("", false), ("requires_openai_auth = true", true)] {
let entry = RequirementsLayerEntry::from_toml(
mdm_gateway().source,
format!(
r#"
[gateway]
base_url = "https://gateway.example"
{opt_in}
[gateway.auth]
{GATEWAY_AUTH}
[gateway.auth.delivery]
kind = "header"
name = "X-Gateway-Authorization"
"#
),
);
let requirements = compose(vec![entry]).unwrap().unwrap();
assert_eq!(requirements.config_server, expected.config_server);
let providers = requirements.model_providers.unwrap();
let provider = &providers["gateway"];
assert_eq!(provider.requires_openai_auth, requires_openai_auth);
assert_eq!(
provider.gateway_oauth.as_ref().unwrap().delivery(),
&codex_model_provider_info::GatewayOAuthDelivery::Header {
name: "X-Gateway-Authorization".into(),
scheme: "Bearer".into(),
}
);
}
}
#[test]
fn remote_requirements_cannot_enroll_or_reroute_gateway() {
for (contents, field) in [
@@ -2325,6 +2361,14 @@ fn gateway_rejects_invalid_enrollment() {
};
for (contents, error) in [
(named_gateway(" "), "gateway.name"),
("[gateway]\nbase_url = 'https://gateway.example'\n[gateway.auth]\nauthorization_url = 'https://login.example/authorize'".to_string(), "token_url"),
("[gateway]\nbase_url = 'https://gateway.example'\n[gateway.auth]\nclient_di = 'typo'".to_string(), "gateway"),
(
format!(
"[gateway]\nbase_url = 'https://gateway.example'\nrequires_openai_auth = true\n[gateway.auth]\n{GATEWAY_AUTH}"
),
"Header conflict",
),
(named_gateway("OpenAI"), "gateway.name"),
(named_gateway("Azure"), "gateway.name"),
(