Reuse discovered OAuth for managed gateway inference (#65157)

## Why

Gateway enrollment required an explicit `[gateway.auth]` block even when
Codex could discover the OAuth settings while loading managed policy.
Frozen policy snapshots also dropped the discovered settings before
Codex configured the inference provider.

## What changed

Make `[gateway.auth]` optional. When it is omitted, use the OAuth
settings retained in the policy snapshot to configure the inference
provider, provided the snapshot matches the configured gateway enrollment.

## Testing

Add a regression test that compares the provider built from a frozen
snapshot with the provider built from explicit OAuth settings. The test
also verifies that changing the gateway root leaves the new provider
without the previous gateway's OAuth settings and fails the managed
policy check.

GitOrigin-RevId: a8734b3c98f50c9c9ef1917eb8c1d12548cbc271
This commit is contained in:
arnavpatidar-OAI
2026-12-02 03:47:01 +00:00
committed by copyberry
parent 9f33c83cb6
commit ed3678a2a9
10 changed files with 180 additions and 53 deletions
+2 -2
View File
@@ -197,7 +197,7 @@ fn config_server_loader_after_failure(
None => {
initialized
.get_or_try_init(|| async move {
let (mut service, _) = create_config_server_service(
let (mut service, resolution) = create_config_server_service(
&config,
&codex_home,
&routes,
@@ -206,7 +206,7 @@ fn config_server_loader_after_failure(
.await?;
service.policy = policy;
let (loader, _) = managed_config_bundle_loader_for_service(service);
Ok(loader)
Ok(loader.with_config_server_resolution(resolution))
})
.await
}
@@ -51,6 +51,78 @@ fn oauth_config(base_url: &str) -> OAuthSessionConfig {
}
}
#[tokio::test]
async fn gateway_policy_snapshot_preserves_provider_auth_only_for_the_enrolled_root() {
let home = tempdir().unwrap();
let path = home.path().join("requirements.toml");
let gateway = "[gateway]\nbase_url = 'https://gateway.example/team/'";
let config = || {
codex_core::config::ConfigBuilder::default()
.codex_home(home.path().into())
.loader_overrides(
codex_config::LoaderOverrides::with_managed_config_path_for_tests(
home.path().join("managed_config.toml"),
),
)
};
std::fs::write(
&path,
format!(
r#"{gateway}
[gateway.auth]
authorization_url = "https://login.example/authorize"
token_url = "https://login.example/token"
client_id = "codex"
"#
),
)
.unwrap();
let explicit = config().build().await.unwrap();
let resolved = explicit
.config_layer_stack
.requirements_toml()
.config_server
.clone()
.unwrap();
std::fs::write(&path, gateway).unwrap();
let mut configured = resolved.clone();
configured.oauth = None;
let factory = transport_default_auth_route_config();
let loader = CloudConfigBundleLoader::new(async { Ok(Some(Default::default())) })
.with_config_server_resolution(ConfigServerResolution {
outbound_proxy_policy: factory.http_client_factory().outbound_proxy_policy(),
system_proxy_fallback: false,
resolved,
configured,
});
let frozen = CloudConfigBundleLoader::from_snapshot(loader.get_snapshot().await);
let loaded = config()
.cloud_config_bundle(frozen.clone())
.build()
.await
.unwrap();
loaded
.config_layer_stack
.ensure_config_server_applied()
.unwrap();
assert_eq!(loaded.model_provider, explicit.model_provider);
std::fs::write(
path,
"[gateway]\nbase_url = 'https://gateway.example/other'",
)
.unwrap();
let changed = config().cloud_config_bundle(frozen).build().await.unwrap();
assert!(changed.model_provider.gateway_oauth.is_none());
assert!(
changed
.config_layer_stack
.ensure_config_server_applied()
.is_err()
);
}
#[tokio::test]
async fn a_supplied_chatgpt_token_does_not_replace_config_server_sign_in() {
let server = MockServer::start().await;
+32 -11
View File
@@ -412,11 +412,34 @@ impl CloudConfigBundlePolicyChanges {
}
}
/// Keep runtime discovery with the policy it authenticated, even in frozen snapshots.
#[derive(Clone)]
pub enum BundleConfigServer {
Configured(crate::ConfigServer),
Resolved(Arc<crate::ConfigServerResolution>),
}
impl BundleConfigServer {
pub fn configured(&self) -> &crate::ConfigServer {
match self {
Self::Configured(server) => server,
Self::Resolved(resolution) => &resolution.configured,
}
}
pub fn resolution(&self) -> Option<&crate::ConfigServerResolution> {
match self {
Self::Configured(_) => None,
Self::Resolved(resolution) => Some(resolution),
}
}
}
#[derive(Clone)]
pub struct CloudConfigBundleSnapshot {
pub bundle: Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError>,
pub binding: Option<CloudConfigBundleBinding>,
pub config_server: Option<crate::ConfigServer>,
pub config_server: Option<BundleConfigServer>,
}
type CloudConfigBundleSnapshotGetter =
@@ -427,8 +450,7 @@ pub struct CloudConfigBundleLoader {
getter: Arc<CloudConfigBundleGetter>,
snapshot_getter: Option<Arc<CloudConfigBundleSnapshotGetter>>,
ema_policy: Option<CloudConfigBundlePolicy>,
config_server: Option<crate::ConfigServer>,
config_server_resolution: Option<Arc<crate::ConfigServerResolution>>,
config_server: Option<BundleConfigServer>,
}
impl CloudConfigBundleLoader {
@@ -455,7 +477,6 @@ impl CloudConfigBundleLoader {
snapshot_getter: None,
ema_policy: None,
config_server: None,
config_server_resolution: None,
}
}
@@ -497,15 +518,14 @@ impl CloudConfigBundleLoader {
config_server: None,
},
};
if snapshot.bundle.is_ok() && self.config_server.is_some() {
if snapshot.bundle.is_ok() && snapshot.config_server.is_none() {
snapshot.config_server = self.config_server.clone();
}
snapshot
}
pub fn with_config_server(mut self, service_config: crate::ConfigServer) -> Self {
self.config_server = Some(service_config);
self.config_server_resolution = None;
self.config_server = Some(BundleConfigServer::Configured(service_config));
self
}
@@ -513,18 +533,19 @@ impl CloudConfigBundleLoader {
mut self,
resolution: crate::ConfigServerResolution,
) -> Self {
self.config_server = Some(resolution.configured.clone());
self.config_server_resolution = Some(Arc::new(resolution));
self.config_server = Some(BundleConfigServer::Resolved(Arc::new(resolution)));
self
}
/// Successful discovery, including anonymous configuration, for the retained loader.
pub fn config_server_resolution(&self) -> Option<&crate::ConfigServerResolution> {
self.config_server_resolution.as_deref()
self.config_server.as_ref()?.resolution()
}
pub fn config_server(&self) -> Option<&crate::ConfigServer> {
self.config_server.as_ref()
self.config_server
.as_ref()
.map(BundleConfigServer::configured)
}
pub fn ema_policy_changes(&self) -> Option<CloudConfigBundlePolicyChanges> {
+1
View File
@@ -76,6 +76,7 @@ pub use browser_computer_use_requirements::ComputerUseWindowsRequirementsToml;
pub use browser_computer_use_requirements::RequestHeaderToml;
pub use browser_use::BrowserUseConfigToml;
pub use browser_use::BrowserUseOriginPolicyConfigToml;
pub use cloud_config_bundle::BundleConfigServer;
pub use cloud_config_bundle::CloudConfigBundle;
pub use cloud_config_bundle::CloudConfigBundleBinding;
pub use cloud_config_bundle::CloudConfigBundleBindingGuard;
@@ -43,7 +43,8 @@ pub async fn load_managed_requirements_state(
}
let mut bundle_requirements = Vec::new();
if let Some(bundle) = cloud_config_bundle.get().await.map_err(io::Error::other)? {
let snapshot = cloud_config_bundle.get_snapshot().await;
if let Some(bundle) = snapshot.bundle.map_err(io::Error::other)? {
let base_dir = AbsolutePathBuf::from_absolute_path(codex_home)?;
bundle_requirements = bundle
.requirements_toml
@@ -58,6 +59,7 @@ pub async fn load_managed_requirements_state(
&overrides,
strict_config,
bundle_requirements,
snapshot.config_server.as_ref(),
)
.await?;
let _: ConfigRequirements = requirements.clone().try_into()?;
@@ -165,7 +167,12 @@ pub async fn load_guardian_policy_snapshot(
})
.collect::<io::Result<Vec<_>>>()?;
let mut requirements = compose_requirements(requirements_layers)?.unwrap_or_default();
if requirements.config_server.take().map(|source| source.value) != snapshot.config_server {
let required = requirements.config_server.take().map(|source| source.value);
let applied = snapshot
.config_server
.as_ref()
.map(crate::BundleConfigServer::configured);
if required.as_ref() != applied {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Required managed configuration has not been loaded",
@@ -187,6 +194,7 @@ pub(super) async fn load_requirements_from_sources(
overrides: &LoaderOverrides,
strict_config: bool,
bundle_requirements: Vec<RequirementsLayerEntry>,
applied: Option<&crate::BundleConfigServer>,
) -> io::Result<(
ConfigRequirementsWithSources,
LoadedConfigLayers,
@@ -202,7 +210,11 @@ pub(super) async fn load_requirements_from_sources(
bundle_requirements,
)
.await?;
let mut requirements = compose_requirements(requirements_layers.clone())?.unwrap_or_default();
let mut requirements = crate::requirements_layers::compose_requirements_with_config_server(
requirements_layers.clone(),
applied.and_then(crate::BundleConfigServer::resolution),
)?
.unwrap_or_default();
if overrides.ignore_login_requirements {
requirements.allowed_login_methods = None;
requirements.allowed_chatgpt_workspaces = None;
+4 -1
View File
@@ -247,6 +247,7 @@ pub async fn load_config_layers_state(
&overrides,
strict_config,
bundle_requirements_layers,
applied_config_server.as_ref(),
)
.await?;
let mut startup_warnings = loaded_config_layers.startup_warnings.clone();
@@ -525,7 +526,9 @@ pub async fn load_config_layers_state(
let mut config_layer_stack =
ConfigLayerStack::new(layers, requirements, config_requirements_toml.into_toml())?
.with_cloud_config_binding(cloud_config_binding)
.with_applied_config_server(applied_config_server)
.with_applied_config_server(
applied_config_server.map(|server| server.configured().clone()),
)
.with_user_and_project_exec_policy_rules_ignored(
ignore_user_and_project_exec_policy_rules,
);
@@ -5,6 +5,7 @@ use super::layer::ComposableRequirementsLayer;
use super::stack::RequirementsCompositionError;
use crate::ConfigServer;
use crate::ConfigServerOAuth;
use crate::ConfigServerResolution;
use codex_model_provider_info::GatewayOAuthConfig;
use codex_model_provider_info::GatewayOAuthSettings;
use codex_model_provider_info::ModelProviderInfo;
@@ -21,15 +22,17 @@ use toml::Value;
pub struct GatewayRequirementsToml {
name: Option<String>,
base_url: RedactedString,
auth: ConfigServerOAuth,
auth: Option<Box<ConfigServerOAuth>>,
}
impl GatewayRequirementsToml {
fn into_requirements(self) -> Result<toml::Table, String> {
let auth = self.auth;
fn into_requirements(
self,
resolution: Option<&ConfigServerResolution>,
) -> Result<toml::Table, String> {
let mut server = ConfigServer {
base_url: self.base_url.into_inner(),
oauth: Some(Box::new(auth.clone())),
oauth: self.auth,
};
let root = server
.validated_base_url()
@@ -43,23 +46,32 @@ impl GatewayRequirementsToml {
return Err("gateway.name must be a non-empty, non-reserved provider name".into());
}
// 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(|| {
resolution
.filter(|resolution| resolution.configured == server)
.and_then(|resolution| resolution.resolved.oauth.as_deref())
});
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,
gateway_oauth: Some(GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
authorization_url: auth.authorization_url,
token_url: auth.token_url,
device_authorization_url: auth.device_authorization_url,
client_id: auth.client_id,
resource: auth.resource,
scopes: auth.scopes,
redirect_port: auth.redirect_port,
credentials_store: auth.credentials_store,
delivery: Default::default(),
})),
gateway_oauth: auth.cloned().map(|auth| {
GatewayOAuthConfig::OAuth(GatewayOAuthSettings {
authorization_url: auth.authorization_url,
token_url: auth.token_url,
device_authorization_url: auth.device_authorization_url,
client_id: auth.client_id,
resource: auth.resource,
scopes: auth.scopes,
redirect_port: auth.redirect_port,
credentials_store: auth.credentials_store,
delivery: Default::default(),
})
}),
..Default::default()
};
@@ -76,19 +88,19 @@ impl GatewayRequirementsToml {
pub(super) fn expand(
layers: &mut [ComposableRequirementsLayer],
resolution: Option<&ConfigServerResolution>,
) -> Result<(), RequirementsCompositionError> {
let mut enrollment = None;
for (index, layer) in layers.iter_mut().enumerate() {
let Some(gateway) = layer.domain_fields.gateway.take() else {
continue;
};
let requirements =
gateway
.into_requirements()
.map_err(|message| RequirementsCompositionError::Parse {
layer_source: layer.source.clone(),
message,
})?;
let requirements = gateway.into_requirements(resolution).map_err(|message| {
RequirementsCompositionError::Parse {
layer_source: layer.source.clone(),
message,
}
})?;
enrollment = Some((index, requirements));
}
@@ -12,3 +12,4 @@ pub use layer::RequirementsLayerEntry;
pub(crate) use layer::strip_cloud_auth_requirements;
pub use stack::compose_requirements;
pub use stack::compose_requirements_for_hostname;
pub(crate) use stack::compose_requirements_with_config_server;
@@ -87,7 +87,7 @@ impl From<RequirementsCompositionError> for io::Error {
pub fn compose_requirements(
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
compose_requirements_with_hostname_resolver(layers, crate::host_name)
compose_requirements_with_config_server(layers, /*resolution*/ None)
}
/// Composes requirements using an explicitly supplied execution-host hostname.
@@ -96,8 +96,9 @@ pub fn compose_requirements_for_hostname(
hostname: Option<&str>,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
let hostname = hostname.map(str::to_string);
compose_requirements_with_hostname_resolver_and_hook_directory(
compose_requirements_with_hostname_resolver(
layers,
/*resolution*/ None,
move || hostname.clone(),
HookDirectoryField::current_platform(),
)
@@ -110,26 +111,29 @@ pub(super) fn compose_requirements_for_hostname_and_hook_directory(
hook_directory_field: HookDirectoryField,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
let hostname = hostname.map(str::to_string);
compose_requirements_with_hostname_resolver_and_hook_directory(
compose_requirements_with_hostname_resolver(
layers,
/*resolution*/ None,
move || hostname.clone(),
hook_directory_field,
)
}
fn compose_requirements_with_hostname_resolver(
pub(crate) fn compose_requirements_with_config_server(
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
hostname_resolver: impl Fn() -> Option<String>,
resolution: Option<&crate::ConfigServerResolution>,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
compose_requirements_with_hostname_resolver_and_hook_directory(
compose_requirements_with_hostname_resolver(
layers,
hostname_resolver,
resolution,
crate::host_name,
HookDirectoryField::current_platform(),
)
}
fn compose_requirements_with_hostname_resolver_and_hook_directory(
fn compose_requirements_with_hostname_resolver(
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
resolution: Option<&crate::ConfigServerResolution>,
hostname_resolver: impl Fn() -> Option<String>,
hook_directory_field: HookDirectoryField,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
@@ -141,7 +145,7 @@ fn compose_requirements_with_hostname_resolver_and_hook_directory(
for layer in layers {
stack.add_layer(layer, &cached_hostname_resolver)?;
}
stack.compose()
stack.compose(resolution)
}
struct RequirementsLayerStack {
@@ -171,13 +175,14 @@ impl RequirementsLayerStack {
fn compose(
self,
resolution: Option<&crate::ConfigServerResolution>,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
let Self {
mut layers,
hook_directory_field,
} = self;
super::gateway::expand(&mut layers)?;
super::gateway::expand(&mut layers, resolution)?;
let network = super::network::compose(&mut layers)?;
let mut merged_toml = TomlValue::Table(toml::map::Map::new());
for layer in &layers {
@@ -1517,10 +1517,12 @@ fn hostname_resolver_is_not_called_without_remote_sandbox_config() {
allowed_sandbox_modes = ["read-only"]
"#,
)],
/*resolution*/ None,
|| {
calls.set(calls.get() + 1);
Some("build-01.example.com".to_string())
},
HookDirectoryField::current_platform(),
)
.expect("compose requirements")
.expect("requirements present")
@@ -1561,10 +1563,12 @@ allowed_sandbox_modes = ["workspace-write"]
"#,
),
],
/*resolution*/ None,
|| {
calls.set(calls.get() + 1);
Some("build-01.example.com".to_string())
},
HookDirectoryField::current_platform(),
)
.expect("compose requirements")
.expect("requirements present")
@@ -2323,10 +2327,6 @@ fn gateway_rejects_invalid_enrollment() {
(named_gateway(" "), "gateway.name"),
(named_gateway("OpenAI"), "gateway.name"),
(named_gateway("Azure"), "gateway.name"),
(
"[gateway]\nbase_url = 'https://gateway.example'".to_string(),
"auth",
),
(
format!(
"[gateway]\nbase_url = 'http://gateway.example'\n[gateway.auth]\n{GATEWAY_AUTH}"