Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Discover and validate MCP authorization servers before ID-JAG exchange (#49478)

Nick Steele15fd656ddb55
diff --git a/codex-rs/network-proxy/src/lib.rs b/codex-rs/network-proxy/src/lib.rs
index df310c58c2..559ec0a9b1 100644
--- a/codex-rs/network-proxy/src/lib.rs
+++ b/codex-rs/network-proxy/src/lib.rs
@@ -78,6 +78,7 @@ pub use network_policy::NetworkPolicyDecision;
pub use network_policy::NetworkPolicyRequest;
pub use network_policy::NetworkPolicyRequestArgs;
pub use network_policy::NetworkProtocol;
+pub use policy::is_non_public_ip;
pub use policy::normalize_host;
pub use process_log_metadata::ExecutorLogIdentity;
pub use process_log_metadata::NetworkProxyProcessLogMetadata;
diff --git a/codex-rs/network-proxy/src/policy.rs b/codex-rs/network-proxy/src/policy.rs
index 0cfd7c04c7..3b2486be1f 100644
--- a/codex-rs/network-proxy/src/policy.rs
+++ b/codex-rs/network-proxy/src/policy.rs
@@ -52,6 +52,7 @@ pub(crate) fn is_default_proxy_bypass_host(host: &str) -> bool {
}
}
+/// Classifies IP literals excluded from public network destinations; does not resolve DNS.
pub fn is_non_public_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(ip) => is_non_public_ipv4(ip),
diff --git a/codex-rs/protocol/src/mcp.rs b/codex-rs/protocol/src/mcp.rs
index 3e5c62e741..1a409c4931 100644
--- a/codex-rs/protocol/src/mcp.rs
+++ b/codex-rs/protocol/src/mcp.rs
@@ -34,6 +34,9 @@ pub const OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID: &str = "openai/standard-form-
pub const MCP_APP_UI_EXTENSION_ID: &str = "io.modelcontextprotocol/ui";
/// Host-supplied confirmation-policy documents for Node REPL-backed actor calls.
pub const CONFIRMATION_POLICIES_META_KEY: &str = "openai/confirmation_policies";
+/// Extension ID for enterprise-managed MCP authorization via ID-JAG.
+pub const ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID: &str =
+ "io.modelcontextprotocol/enterprise-managed-authorization";
/// Returns whether a raw MCP server name identifies a Node REPL-backed server.
pub fn is_node_repl_backed_server(server: &str) -> bool {
diff --git a/codex-rs/rmcp-client/src/ema_auth.rs b/codex-rs/rmcp-client/src/ema_auth.rs
new file mode 100644
index 0000000000..5d5f5de64b
--- /dev/null
+++ b/codex-rs/rmcp-client/src/ema_auth.rs
@@ -0,0 +1,205 @@
+//! Select the resource authorization server before polling identity or exchanging credentials.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use anyhow::Context;
+use anyhow::Result;
+use anyhow::anyhow;
+use anyhow::bail;
+use codex_exec_server::HttpClient;
+use futures::future::BoxFuture;
+use http::StatusCode;
+use serde::Deserialize;
+use serde_json::Value;
+use url::Url;
+
+use crate::ema_auth_policy::advertised_capability;
+use crate::ema_auth_policy::validate_ema_auth_resource;
+use crate::ema_auth_policy::validate_ema_oauth_endpoint;
+use crate::ema_auth_policy::validate_ema_public_client_auth;
+use crate::ema_exchange::EmaAccessToken;
+use crate::ema_exchange::EmaIdJagExchangeRequest;
+use crate::ema_exchange::JWT_BEARER_GRANT_TYPE;
+use crate::ema_exchange::exchange_id_jag;
+use crate::ema_identity::EmaIdpIdentity;
+use crate::ema_resource::EmaDiscoveryRequest;
+use crate::ema_resource::EmaResource;
+use crate::ema_resource::discover_ema_resource;
+use crate::ema_resource::validate_ema_metadata_issuer;
+
+const ID_JAG_GRANT_PROFILE: &str = "urn:ietf:params:oauth:grant-profile:id-jag";
+
+/// Token-only Resource AS metadata must not require an unused authorization endpoint.
+#[derive(Deserialize)]
+struct EmaAuthorizationMetadata {
+ issuer: Option<String>,
+ token_endpoint: String,
+ #[serde(flatten)]
+ additional_fields: HashMap<String, Value>,
+}
+
+/// Inputs for non-interactive enterprise-managed MCP authorization.
+pub struct EmaAuthTokenExchangeRequest<'a> {
+ pub server_url: &'a str,
+ pub resource: Option<&'a str>,
+ pub scopes: &'a [String],
+ pub mcp_client_id: Option<&'a str>,
+ pub expected_authorization_server_issuer: Option<&'a str>,
+ pub idp_issuer: &'a str,
+ pub idp_client_id: &'a str,
+ pub idp_identity: BoxFuture<'a, Result<EmaIdpIdentity>>,
+ pub idp_http_client: Arc<dyn HttpClient>,
+ pub resource_http_client: Arc<dyn HttpClient>,
+}
+
+impl<'a> From<&EmaAuthTokenExchangeRequest<'a>> for EmaDiscoveryRequest<'a> {
+ fn from(request: &EmaAuthTokenExchangeRequest<'a>) -> Self {
+ Self {
+ server_url: request.server_url,
+ resource: request.resource,
+ expected_issuer: request.expected_authorization_server_issuer,
+ http_client: Arc::clone(&request.resource_http_client),
+ }
+ }
+}
+
+/// Discover the resource's authorization server, then perform the ID-JAG flow.
+pub async fn exchange_ema_auth_token(
+ request: EmaAuthTokenExchangeRequest<'_>,
+) -> Result<EmaAccessToken> {
+ validate_ema_auth_resource(request.server_url, request.resource)?;
+ let client_id = request
+ .mcp_client_id
+ .filter(|value| !value.trim().is_empty())
+ .ok_or_else(|| {
+ anyhow!(
+ "ema_auth requires the OAuth client ID registered with the MCP authorization server"
+ )
+ })?;
+ let (metadata, resource) =
+ discover_ema_authorization_metadata(EmaDiscoveryRequest::from(&request)).await?;
+ let issuer = metadata
+ .issuer
+ .as_deref()
+ .ok_or_else(|| anyhow!("MCP authorization metadata is missing an issuer"))?;
+ let EmaIdpIdentity {
+ token_endpoint,
+ refresh_token,
+ credential_lock,
+ } = request.idp_identity.await?;
+ let result = exchange_id_jag(EmaIdJagExchangeRequest {
+ resource: &resource,
+ scopes: request.scopes,
+ mcp_client_id: client_id,
+ authorization_server_issuer: issuer,
+ authorization_server_token_endpoint: &metadata.token_endpoint,
+ idp_token_endpoint: &token_endpoint,
+ idp_issuer: request.idp_issuer,
+ idp_client_id: request.idp_client_id,
+ refresh_token,
+ idp_http_client: request.idp_http_client,
+ resource_http_client: request.resource_http_client,
+ })
+ .await;
+ drop(credential_lock);
+ result
+}
+
+async fn discover_ema_authorization_metadata(
+ request: EmaDiscoveryRequest<'_>,
+) -> Result<(EmaAuthorizationMetadata, String)> {
+ let expected_issuer = request.expected_issuer;
+ let EmaResource {
+ server_url: server,
+ resource,
+ authorization_servers: issuers,
+ client,
+ } = discover_ema_resource(request).await?;
+ for issuer in issuers {
+ let issuer_url = match Url::parse(&issuer) {
+ Ok(url) => url,
+ Err(error) if expected_issuer.is_some() => {
+ return Err(error)
+ .context("configured enterprise authorization server issuer is invalid");
+ }
+ Err(_) => continue,
+ };
+ if let Err(error) = validate_ema_metadata_issuer(&server, &issuer_url) {
+ if expected_issuer.is_some() {
+ return Err(error);
+ }
+ continue;
+ }
+ let path = issuer_url.path().trim_matches('/');
+ let suffix = if path.is_empty() {
+ String::new()
+ } else {
+ format!("/{path}")
+ };
+ let mut urls = vec![
+ issuer_url.join(&format!("/.well-known/oauth-authorization-server{suffix}"))?,
+ issuer_url.join(&format!("/.well-known/openid-configuration{suffix}"))?,
+ ];
+ if !path.is_empty() {
+ urls.push(issuer_url.join(&format!("/{path}/.well-known/openid-configuration"))?);
+ urls.push(issuer_url.join("/.well-known/oauth-authorization-server")?);
+ }
+ for url in urls {
+ let response = client.get(url).await?;
+ if response.status() != StatusCode::OK {
+ continue;
+ }
+ let Ok(metadata) = serde_json::from_slice::<EmaAuthorizationMetadata>(response.body())
+ else {
+ continue;
+ };
+ if metadata.issuer.as_deref() != Some(issuer.as_str()) {
+ bail!(
+ "enterprise authorization metadata issuer does not match its advertised issuer"
+ );
+ }
+ validate_ema_oauth_endpoint(
+ &metadata.token_endpoint,
+ "MCP authorization server token endpoint",
+ )?;
+ if expected_issuer.is_some()
+ && issuer_url.origin() != Url::parse(&metadata.token_endpoint)?.origin()
+ {
+ bail!("enterprise MCP authorization server token endpoint changed origin");
+ }
+ let profile = advertised_capability(
+ metadata
+ .additional_fields
+ .get("authorization_grant_profiles_supported"),
+ ID_JAG_GRANT_PROFILE,
+ "MCP authorization grant profiles",
+ )?;
+ let grant = advertised_capability(
+ metadata.additional_fields.get("grant_types_supported"),
+ JWT_BEARER_GRANT_TYPE,
+ "MCP authorization grant types",
+ )?;
+ if profile == Some(false) || grant != Some(true) {
+ break;
+ }
+ match validate_ema_public_client_auth(
+ metadata
+ .additional_fields
+ .get("token_endpoint_auth_methods_supported"),
+ "MCP authorization server",
+ ) {
+ Ok(()) => return Ok((metadata, resource)),
+ Err(error) if expected_issuer.is_some() => return Err(error),
+ Err(_) => break,
+ }
+ }
+ }
+ bail!(
+ "enterprise MCP discovery found no authorization server advertising public-client JWT bearer support for ID-JAG"
+ )
+}
+
+#[cfg(test)]
+#[path = "ema_auth_tests.rs"]
+mod tests;
diff --git a/codex-rs/rmcp-client/src/ema_auth_tests.rs b/codex-rs/rmcp-client/src/ema_auth_tests.rs
new file mode 100644
index 0000000000..d327ae34c2
--- /dev/null
+++ b/codex-rs/rmcp-client/src/ema_auth_tests.rs
@@ -0,0 +1,377 @@
+//! Bound metadata selection and HTTP confinement run before enterprise credential access.
+
+use std::sync::atomic::AtomicBool;
+use std::sync::atomic::Ordering;
+
+use codex_exec_server::RouteAwareHttpClient;
+use codex_http_client::HttpClientFactory;
+use codex_http_client::OutboundProxyPolicy;
+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;
+
+use super::*;
+
+fn request<'a>(resource: &'a str, issuer: Option<&'a str>) -> EmaAuthTokenExchangeRequest<'a> {
+ let client: Arc<dyn HttpClient> = Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
+ OutboundProxyPolicy::ReqwestDefault,
+ )));
+ EmaAuthTokenExchangeRequest {
+ server_url: resource,
+ resource: Some(resource),
+ scopes: &[],
+ mcp_client_id: Some("resource-client"),
+ expected_authorization_server_issuer: issuer,
+ idp_issuer: "https://idp.example",
+ idp_client_id: "enterprise-client",
+ idp_identity: Box::pin(async { bail!("identity resolver reached") }),
+ idp_http_client: Arc::clone(&client),
+ resource_http_client: client,
+ }
+}
+
+#[tokio::test]
+async fn discovery_pins_resource_issuer_and_public_jwt_bearer_before_identity() -> Result<()> {
+ let metadata_cases = [
+ (true, true, json!({}), true),
+ (false, true, json!({}), false),
+ (true, false, json!({}), false),
+ ]
+ .into_iter()
+ .chain(
+ [
+ json!({"issuer": null}),
+ json!({"issuer": "https://other.example"}),
+ json!({"token_endpoint": "https://other.example/token"}),
+ json!({"token_endpoint": "http://as.example/token"}),
+ json!({"grant_types_supported": null}),
+ json!({"grant_types_supported": ["authorization_code"]}),
+ json!({"authorization_grant_profiles_supported": ["other"]}),
+ json!({"token_endpoint_auth_methods_supported": ["private_key_jwt"]}),
+ ]
+ .into_iter()
+ .map(|invalid| (true, true, invalid, false)),
+ );
+ let fallback_paths = [
+ "/.well-known/oauth-protected-resource/enterprise",
+ "/enterprise/.well-known/oauth-protected-resource",
+ "/.well-known/oauth-protected-resource",
+ ];
+ let fallback_cases = fallback_paths.into_iter().flat_map(|path| {
+ [true, false].map(move |valid| ("GET", path, valid, true, json!({}), valid))
+ });
+ for (metadata_method, metadata_path, resource_matches, issuer_matches, additions, valid) in
+ metadata_cases
+ .map(|(resource, issuer, additions, valid)| {
+ (
+ "POST",
+ "/enterprise/tools",
+ resource,
+ issuer,
+ additions,
+ valid,
+ )
+ })
+ .chain(fallback_cases)
+ {
+ let server = MockServer::start().await;
+ let query = "tenant=one%2Ftwo&tenant=three+four&flag=&encoded=%2f";
+ let resource = format!("{}/enterprise?{query}", server.uri());
+ let transport = format!("{}/enterprise/tools?{query}", server.uri());
+ let issuer = format!("{}/as", server.uri());
+ // A query-only resource change must not be accepted as the same resource.
+ let advertised_resource = if resource_matches {
+ resource.clone()
+ } else {
+ resource.replace("one", "two")
+ };
+ Mock::given(method(metadata_method))
+ .and(path(metadata_path))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "resource": advertised_resource,
+ "authorization_servers": [format!("{}/unused", server.uri()), issuer],
+ })))
+ .mount(&server)
+ .await;
+ let mut metadata = json!({"issuer": issuer, "token_endpoint": format!("{issuer}/token"),
+ "grant_types_supported": [JWT_BEARER_GRANT_TYPE],
+ "token_endpoint_auth_methods_supported": ["none"]});
+ metadata
+ .as_object_mut()
+ .expect("metadata")
+ .extend(additions.as_object().expect("overrides").clone());
+ Mock::given(method("GET"))
+ .and(path("/.well-known/oauth-authorization-server/as"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(metadata))
+ .mount(&server)
+ .await;
+ let polled = AtomicBool::new(false);
+ let mut exchange = request(
+ &resource,
+ Some(if issuer_matches {
+ &issuer
+ } else {
+ "https://other.example"
+ }),
+ );
+ exchange.server_url = &transport;
+ exchange.idp_identity = Box::pin(async {
+ polled.store(true, Ordering::SeqCst);
+ bail!("identity resolver reached")
+ });
+ exchange_ema_auth_token(exchange)
+ .await
+ .expect_err("stop before token exchange");
+ assert_eq!(polled.load(Ordering::SeqCst), valid, "{additions}");
+ let requests = server.received_requests().await.expect("requests");
+ let resource_requests = requests
+ .iter()
+ .filter(|request| request.url.path() != "/.well-known/oauth-authorization-server/as")
+ .collect::<Vec<_>>();
+ assert!(
+ resource_requests
+ .iter()
+ .all(|request| request.url.query() == Some(query))
+ );
+ assert!(
+ resource_requests
+ .iter()
+ .all(|request| request.url.path() == "/enterprise/tools"
+ || (metadata_method == "GET" && fallback_paths.contains(&request.url.path())))
+ );
+ assert_eq!(
+ resource_requests
+ .last()
+ .expect("resource metadata request")
+ .url
+ .path(),
+ metadata_path
+ );
+ }
+ Ok(())
+}
+
+#[tokio::test]
+async fn modern_challenge_confines_metadata_redirects() -> Result<()> {
+ let server = MockServer::start().await;
+ let authorization = MockServer::start().await;
+ let attacker = MockServer::start().await;
+ let resource = format!("{}/mcp", server.uri());
+ let issuer = authorization.uri();
+ let prm = format!("{}/enterprise/resource", server.uri());
+ Mock::given(method("POST"))
+ .and(path("/mcp"))
+ .respond_with(move |request: &wiremock::Request| {
+ assert_eq!(request.headers["mcp-protocol-version"], "2026-07-28");
+ assert_eq!(
+ request.body_json::<Value>().expect("discovery")["method"],
+ "server/discover"
+ );
+ ResponseTemplate::new(401).insert_header(
+ "www-authenticate",
+ format!("Bearer resource_metadata=\"{prm}\""),
+ )
+ })
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/enterprise/resource"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .set_body_json(json!({"resource": resource, "authorization_servers": [issuer]})),
+ )
+ .mount(&server)
+ .await;
+ let metadata = json!({"issuer": issuer, "token_endpoint": format!("{issuer}/token"),
+ "grant_types_supported": [JWT_BEARER_GRANT_TYPE],
+ "token_endpoint_auth_methods_supported": ["none"]});
+ Mock::given(method("GET"))
+ .and(path("/.well-known/oauth-authorization-server"))
+ .respond_with(move |request: &wiremock::Request| {
+ assert!(!request.headers.contains_key("authorization"));
+ ResponseTemplate::new(200).set_body_json(metadata.clone())
+ })
+ .mount(&authorization)
+ .await;
+ let exchange = request(&resource, Some(&issuer));
+ let (metadata, actual_resource) =
+ discover_ema_authorization_metadata(EmaDiscoveryRequest::from(&exchange)).await?;
+ assert_eq!(
+ (metadata.issuer, metadata.token_endpoint, actual_resource),
+ (
+ Some(issuer.clone()),
+ format!("{issuer}/token"),
+ resource.clone()
+ )
+ );
+ Mock::given(method("GET"))
+ .and(path("/.well-known/oauth-authorization-server"))
+ .respond_with(
+ ResponseTemplate::new(307)
+ .insert_header("location", format!("{}/capture", attacker.uri())),
+ )
+ .with_priority(1)
+ .mount(&authorization)
+ .await;
+ let error = discover_ema_authorization_metadata(EmaDiscoveryRequest::from(&exchange))
+ .await
+ .err()
+ .context("cross-origin redirect must fail")?;
+ assert!(error.to_string().contains("cross-origin redirect"));
+ assert!(
+ attacker
+ .received_requests()
+ .await
+ .expect("requests")
+ .is_empty()
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn legacy_challenges_require_a_recognized_discovery_rejection() -> Result<()> {
+ for (status, id, code, message, legacy) in [
+ (404, json!(null), -1, "", true),
+ (405, json!(null), -1, "", true),
+ (
+ 200,
+ json!("ema-auth-discover"),
+ -32601,
+ "Method not found",
+ true,
+ ),
+ (
+ 400,
+ json!("ema-auth-discover"),
+ -32022,
+ "Unsupported protocol version: 2026-07-28",
+ true,
+ ),
+ (
+ 400,
+ json!(null),
+ -32000,
+ "Bad Request: No valid session ID provided",
+ true,
+ ),
+ (200, json!("unrelated"), -32601, "Method not found", false),
+ (400, json!(null), -32000, "Unrecognized rejection", false),
+ (503, json!(null), -1, "", false),
+ ] {
+ for (sse, get_status) in [
+ (false, 401),
+ (false, 400),
+ (false, 404),
+ (false, 405),
+ (false, 406),
+ (true, 401),
+ (true, 405),
+ ] {
+ let initialize = get_status != 401;
+ let server = MockServer::start().await;
+ let resource = format!("{}/mcp", server.uri());
+ let prm = format!("{}/custom/metadata", server.uri());
+ let rejection = if code == -1 {
+ ResponseTemplate::new(status)
+ } else {
+ let body = json!({
+ "jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message},
+ });
+ if sse {
+ ResponseTemplate::new(status).set_body_raw(
+ format!(": keepalive\n\nevent: message\ndata: {body}\n\n"),
+ "text/event-stream",
+ )
+ } else {
+ ResponseTemplate::new(status).set_body_json(body)
+ }
+ };
+ let challenge = ResponseTemplate::new(401).insert_header(
+ "www-authenticate",
+ format!("Bearer resource_metadata=\"{prm}\""),
+ );
+ let post_challenge = challenge.clone();
+ Mock::given(method("POST"))
+ .and(path("/mcp"))
+ .respond_with(move |request: &wiremock::Request| {
+ let body = request.body_json::<Value>().expect("probe");
+ if body["method"] == "server/discover" {
+ return rejection.clone();
+ }
+ assert!(legacy && initialize);
+ assert_eq!(body["method"], "initialize");
+ assert_eq!(body["params"]["protocolVersion"], "2025-06-18");
+ assert!(!request.headers.contains_key("authorization"));
+ post_challenge.clone()
+ })
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/mcp"))
+ .and(wiremock::matchers::header("accept", "text/event-stream"))
+ .respond_with(if initialize {
+ ResponseTemplate::new(get_status)
+ } else {
+ challenge
+ })
+ .expect(u64::from(legacy))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/custom/metadata"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "resource": resource, "authorization_servers": [server.uri()],
+ })))
+ .expect(u64::from(legacy))
+ .mount(&server)
+ .await;
+ let exchange = request(&resource, /*issuer*/ None);
+ let discovered = discover_ema_resource(EmaDiscoveryRequest::from(&exchange)).await;
+ assert_eq!(
+ discovered.is_ok(),
+ legacy,
+ "{status} {message}, sse={sse}, get_status={get_status}"
+ );
+ server.verify().await;
+ }
+ }
+ Ok(())
+}
+
+#[test]
+fn discovery_rejects_private_or_ambiguous_issuer_destinations() -> Result<()> {
+ let resource = Url::parse("https://mcp.example/mcp")?;
+ for issuer in [
+ "http://issuer.example",
+ "https://10.0.0.1",
+ "https://127.0.0.1",
+ "https://169.254.169.254",
+ "https://100.64.0.1",
+ "https://198.19.0.1",
+ "https://192.0.2.1",
+ "https://[::ffff:192.0.2.1]",
+ "https://[fd00::1]",
+ "https://[::ffff:169.254.169.254]",
+ "https://metadata.google.internal",
+ "https://metadata.azure.internal",
+ "https://test.localhost",
+ "https://issuer.example?query=1",
+ "https://issuer.example#fragment",
+ "https://[email protected]",
+ ] {
+ assert!(
+ validate_ema_metadata_issuer(&resource, &Url::parse(issuer)?).is_err(),
+ "{issuer}"
+ );
+ }
+ validate_ema_metadata_issuer(&resource, &Url::parse("https://issuer.example/tenant")?)?;
+ validate_ema_metadata_issuer(
+ &Url::parse("http://127.0.0.1/mcp")?,
+ &Url::parse("http://[::1]:1234")?,
+ )?;
+ Ok(())
+}
diff --git a/codex-rs/rmcp-client/src/ema_claims.rs b/codex-rs/rmcp-client/src/ema_claims.rs
index e70490047d..61a65cc34e 100644
--- a/codex-rs/rmcp-client/src/ema_claims.rs
+++ b/codex-rs/rmcp-client/src/ema_claims.rs
@@ -82,7 +82,7 @@ pub(crate) fn oidc_identity(
Ok(claims)
}
-pub fn validate_oidc_identity_assertion(
+pub(crate) fn validate_oidc_identity_assertion(
assertion: &str,
expected_issuer: &str,
expected_audience: &str,
diff --git a/codex-rs/rmcp-client/src/ema_exchange.rs b/codex-rs/rmcp-client/src/ema_exchange.rs
index 243a05c94d..afe5252b11 100644
--- a/codex-rs/rmcp-client/src/ema_exchange.rs
+++ b/codex-rs/rmcp-client/src/ema_exchange.rs
@@ -19,7 +19,6 @@ use crate::utils::build_default_headers;
pub(crate) const TOKEN_EXCHANGE_GRANT_TYPE: &str =
"urn:ietf:params:oauth:grant-type:token-exchange";
-#[cfg(test)]
pub(crate) const JWT_BEARER_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:jwt-bearer";
/// A resource-bound bearer and its server-reported lifetime, with redacted diagnostics.
@@ -41,7 +40,7 @@ impl std::fmt::Debug for EmaAccessToken {
/// The caller supplies trusted authorization-server metadata and an IdP credential.
/// This primitive does not perform resource discovery or interactive login.
-pub struct EmaIdJagExchangeRequest<'a> {
+pub(crate) struct EmaIdJagExchangeRequest<'a> {
pub resource: &'a str,
pub scopes: &'a [String],
pub mcp_client_id: &'a str,
@@ -56,7 +55,9 @@ pub struct EmaIdJagExchangeRequest<'a> {
}
/// Exchanges an enterprise IdP credential for a resource-bound MCP bearer token.
-pub async fn exchange_id_jag(request: EmaIdJagExchangeRequest<'_>) -> Result<EmaAccessToken> {
+pub(crate) async fn exchange_id_jag(
+ request: EmaIdJagExchangeRequest<'_>,
+) -> Result<EmaAccessToken> {
let idp_http = OAuthHttpClientAdapter::new_with_redirect_mode(
request.idp_http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
diff --git a/codex-rs/rmcp-client/src/ema_identity.rs b/codex-rs/rmcp-client/src/ema_identity.rs
index f906e553f7..b320c8855e 100644
--- a/codex-rs/rmcp-client/src/ema_identity.rs
+++ b/codex-rs/rmcp-client/src/ema_identity.rs
@@ -38,7 +38,6 @@ pub struct EmaIdpIdentityRequest<'a> {
}
/// An opaque IdP refresh token whose credential lock is held through token exchange.
-#[allow(dead_code)]
pub struct EmaIdpIdentity {
pub(crate) token_endpoint: String,
pub(crate) refresh_token: String,
diff --git a/codex-rs/rmcp-client/src/ema_resource.rs b/codex-rs/rmcp-client/src/ema_resource.rs
new file mode 100644
index 0000000000..19ba91b2fd
--- /dev/null
+++ b/codex-rs/rmcp-client/src/ema_resource.rs
@@ -0,0 +1,411 @@
+//! Bound resource discovery and its HTTP safety policy before enterprise credential use.
+//! The returned client keeps one deadline across resource and authorization-server discovery.
+
+use std::net::IpAddr;
+use std::sync::Arc;
+use std::time::Duration;
+use std::time::Instant;
+
+use anyhow::Result;
+use anyhow::anyhow;
+use anyhow::bail;
+use codex_exec_server::HttpClient;
+use codex_network_proxy::is_non_public_ip;
+use codex_protocol::mcp::ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID;
+use futures::StreamExt;
+use http::Method;
+use http::StatusCode;
+use http::header::ACCEPT;
+use http::header::CONTENT_TYPE;
+use http::header::LOCATION;
+use http::header::WWW_AUTHENTICATE;
+use rmcp::model::ClientCapabilities;
+use rmcp::model::ClientJsonRpcMessage;
+use rmcp::model::ClientRequest;
+use rmcp::model::DiscoverRequest;
+use rmcp::model::DiscoverRequestParams;
+use rmcp::model::ErrorCode;
+use rmcp::model::Implementation;
+use rmcp::model::InitializeRequest;
+use rmcp::model::InitializeRequestParams;
+use rmcp::model::JsonRpcMessage;
+use rmcp::model::JsonRpcRequest;
+use rmcp::model::ProtocolVersion;
+use rmcp::model::RequestId;
+use rmcp::model::RequestMetaObject;
+use rmcp::model::ServerJsonRpcMessage;
+use rmcp::transport::auth::OAuthHttpRedirectPolicy;
+use rmcp::transport::auth::WWWAuthenticateParams;
+use rmcp::transport::common::http_header::HEADER_MCP_METHOD;
+use rmcp::transport::common::http_header::HEADER_MCP_PROTOCOL_VERSION;
+use serde::Deserialize;
+use sse_stream::SseStream;
+use url::Host;
+use url::Url;
+
+use crate::ema_auth_policy::validate_ema_auth_resource;
+use crate::ema_auth_policy::validate_ema_oauth_endpoint;
+use crate::http_client_adapter::StreamableHttpRedirectMode;
+use crate::http_client_adapter::legacy_discovery_fallback_response;
+use crate::oauth_http_client::OAuthHttpClientAdapter;
+use crate::utils::build_default_headers;
+
+const MAX_EMA_AUTHORIZATION_SERVERS: usize = 16;
+const MAX_EMA_DISCOVERY_REDIRECTS: usize = 10;
+const EMA_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(30);
+
+#[derive(Deserialize)]
+struct EmaResourceMetadata {
+ resource: String,
+ authorization_server: Option<String>,
+ #[serde(default)]
+ authorization_servers: Vec<String>,
+}
+
+/// EMA discovery retains its own resource/issuer context while sharing the HTTP safety policy.
+pub(super) struct EmaDiscoveryClient {
+ inner: OAuthHttpClientAdapter,
+ deadline: Instant,
+}
+
+impl EmaDiscoveryClient {
+ pub(super) async fn get(&self, url: Url) -> Result<oauth2::HttpResponse> {
+ self.execute(
+ oauth2::http::Request::builder()
+ .uri(url.as_str())
+ .body(Vec::new())?,
+ )
+ .await
+ }
+
+ async fn post(
+ &self,
+ url: &Url,
+ request: &JsonRpcRequest<ClientRequest>,
+ version: ProtocolVersion,
+ ) -> Result<oauth2::HttpResponse> {
+ self.execute(
+ oauth2::http::Request::builder()
+ .method(Method::POST)
+ .uri(url.as_str())
+ .header(ACCEPT, "application/json, text/event-stream")
+ .header(CONTENT_TYPE, "application/json")
+ .header(HEADER_MCP_PROTOCOL_VERSION, version.as_str())
+ .header(HEADER_MCP_METHOD, request.request.method())
+ .body(serde_json::to_vec(request)?)?,
+ )
+ .await
+ }
+
+ async fn execute(&self, request: oauth2::HttpRequest) -> Result<oauth2::HttpResponse> {
+ let (parts, body) = request.into_parts();
+ let mut url = Url::parse(&parts.uri.to_string())?;
+ for _ in 0..MAX_EMA_DISCOVERY_REDIRECTS {
+ validate_ema_oauth_endpoint(url.as_str(), "enterprise metadata URL")?;
+ let remaining = self
+ .deadline
+ .checked_duration_since(Instant::now())
+ .ok_or_else(|| anyhow!("enterprise metadata discovery timed out"))?;
+ let mut request = oauth2::http::Request::builder()
+ .method(parts.method.clone())
+ .uri(url.as_str())
+ .body(body.clone())?;
+ *request.headers_mut() = parts.headers.clone();
+ let response = self
+ .inner
+ .execute_request(request, OAuthHttpRedirectPolicy::Stop, Some(remaining))
+ .await
+ .map_err(|error| {
+ anyhow!("enterprise metadata discovery request failed: {error}")
+ })?;
+ if response.status().is_server_error()
+ || matches!(
+ response.status(),
+ StatusCode::REQUEST_TIMEOUT
+ | StatusCode::TOO_EARLY
+ | StatusCode::TOO_MANY_REQUESTS
+ )
+ {
+ bail!(
+ "enterprise metadata discovery returned HTTP {}",
+ response.status()
+ );
+ }
+ if !response.status().is_redirection() || parts.method != Method::GET {
+ return Ok(response);
+ }
+ let Some(location) = response.headers().get(LOCATION) else {
+ return Ok(response);
+ };
+ let next = url.join(location.to_str()?)?;
+ if next.origin() != url.origin() {
+ bail!("enterprise metadata discovery refused a cross-origin redirect");
+ }
+ url = next;
+ }
+ bail!("enterprise metadata discovery exceeded its redirect limit")
+ }
+}
+
+// Discovery responses use the same JSON or SSE framing as ordinary MCP requests.
+// The HTTP adapter has already bounded this body; only a terminal RPC message matters.
+async fn discovery_response_message(
+ response: &oauth2::HttpResponse,
+) -> Option<ServerJsonRpcMessage> {
+ if !response
+ .headers()
+ .get(CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .is_some_and(|value| value.starts_with("text/event-stream"))
+ {
+ return serde_json::from_slice(response.body()).ok();
+ }
+ let mut events =
+ SseStream::from_bytes_stream(futures::stream::iter([Ok::<_, std::convert::Infallible>(
+ response.body().as_slice(),
+ )]));
+ while let Some(event) = events.next().await {
+ let event = event.ok()?;
+ if !matches!(event.event.as_deref(), None | Some("") | Some("message")) {
+ continue;
+ }
+ let Some(data) = event.data.filter(|data| !data.trim().is_empty()) else {
+ continue;
+ };
+ let message = serde_json::from_str(&data).ok()?;
+ if matches!(
+ message,
+ JsonRpcMessage::Response(_) | JsonRpcMessage::Error(_)
+ ) {
+ return Some(message);
+ }
+ }
+ None
+}
+
+/// Retain rmcp's denial of metadata endpoints on private addresses and cloud-metadata hosts.
+pub(super) fn validate_ema_metadata_issuer(resource: &Url, issuer: &Url) -> Result<()> {
+ validate_ema_oauth_endpoint(issuer.as_str(), "enterprise authorization server issuer")?;
+ if issuer.query().is_some() {
+ bail!("enterprise authorization server issuer must not contain a query");
+ }
+ let loopback = |url: &Url| match url.host() {
+ Some(Host::Domain(host)) => {
+ let host = host.trim_end_matches('.');
+ host == "localhost" || host.ends_with(".localhost")
+ }
+ Some(Host::Ipv4(ip)) => ip.is_loopback(),
+ Some(Host::Ipv6(ip)) => ip.is_loopback(),
+ None => false,
+ };
+ if loopback(resource) && loopback(issuer) {
+ return Ok(());
+ }
+ let disallowed = match issuer.host() {
+ Some(Host::Domain(host)) => {
+ let host = host.trim_end_matches('.').to_ascii_lowercase();
+ matches!(
+ host.as_str(),
+ "localhost" | "metadata" | "metadata.google.internal" | "metadata.azure.internal"
+ ) || host.ends_with(".localhost")
+ }
+ Some(Host::Ipv4(ip)) => is_non_public_ip(IpAddr::V4(ip)),
+ Some(Host::Ipv6(ip)) => is_non_public_ip(IpAddr::V6(ip)),
+ None => true,
+ };
+ if disallowed {
+ bail!("enterprise discovery refused a private authorization-server metadata destination");
+ }
+ Ok(())
+}
+
+pub(super) struct EmaDiscoveryRequest<'a> {
+ pub(super) server_url: &'a str,
+ pub(super) resource: Option<&'a str>,
+ pub(super) expected_issuer: Option<&'a str>,
+ pub(super) http_client: Arc<dyn HttpClient>,
+}
+
+/// A validated resource and candidate list, with the discovery deadline still in force.
+pub(super) struct EmaResource {
+ pub(super) server_url: Url,
+ pub(super) resource: String,
+ pub(super) authorization_servers: Vec<String>,
+ pub(super) client: EmaDiscoveryClient,
+}
+
+pub(super) async fn discover_ema_resource(request: EmaDiscoveryRequest<'_>) -> Result<EmaResource> {
+ let client = EmaDiscoveryClient {
+ inner: OAuthHttpClientAdapter::new_with_redirect_mode(
+ request.http_client,
+ build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
+ request.server_url,
+ /*has_configured_headers*/ false,
+ StreamableHttpRedirectMode::Legacy,
+ )?,
+ deadline: Instant::now() + EMA_DISCOVERY_TIMEOUT,
+ };
+ let server = Url::parse(request.server_url)?;
+ let resource = Url::parse(request.resource.unwrap_or(request.server_url))?;
+ let path = resource.path().trim_matches('/');
+ let mut resource_urls = vec![server.clone()];
+ let metadata_url = |path: &str| {
+ let mut url = resource.clone();
+ url.set_path(path);
+ url
+ };
+ if !path.is_empty() {
+ resource_urls.push(metadata_url(&format!(
+ "/.well-known/oauth-protected-resource/{path}"
+ )));
+ resource_urls.push(metadata_url(&format!(
+ "/{path}/.well-known/oauth-protected-resource"
+ )));
+ }
+ resource_urls.push(metadata_url("/.well-known/oauth-protected-resource"));
+ let mut resource_metadata = None;
+ for url in resource_urls {
+ let mut response = if url == server {
+ // Modern MCP servers need not serve GET. Probe a read-only RPC to receive
+ // their authentication challenge before resolving enterprise credentials.
+ let mut discover = DiscoverRequest::new(DiscoverRequestParams {});
+ discover
+ .extensions
+ .insert(RequestMetaObject::with_client_context(
+ ProtocolVersion::V_2026_07_28,
+ Implementation::new("codex", env!("CARGO_PKG_VERSION")),
+ ClientCapabilities::builder()
+ .enable_extensions_with(
+ [(
+ ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID.to_string(),
+ Default::default(),
+ )]
+ .into(),
+ )
+ .build(),
+ ));
+ let discover = JsonRpcRequest::new(
+ RequestId::String("ema-auth-discover".into()),
+ discover.into(),
+ );
+ let mut response = client
+ .post(&server, &discover, ProtocolVersion::V_2026_07_28)
+ .await?;
+ let legacy = response.status() != StatusCode::UNAUTHORIZED
+ && match discovery_response_message(&response).await {
+ Some(message) => matches!(
+ legacy_discovery_fallback_response(
+ &ClientJsonRpcMessage::Request(discover),
+ message,
+ response.status() == StatusCode::BAD_REQUEST,
+ ),
+ JsonRpcMessage::Error(error) if error.error.code == ErrorCode::METHOD_NOT_FOUND
+ ),
+ None => matches!(
+ response.status(),
+ StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED
+ ),
+ };
+ if legacy {
+ // Preserve legacy custom metadata challenges without exchanging credentials
+ // or retrying application operations. All probes share the same deadline.
+ response = client
+ .execute(
+ oauth2::http::Request::builder()
+ .uri(server.as_str())
+ .header(ACCEPT, "text/event-stream")
+ .body(Vec::new())?,
+ )
+ .await?;
+ if matches!(
+ response.status(),
+ StatusCode::BAD_REQUEST
+ | StatusCode::NOT_FOUND
+ | StatusCode::METHOD_NOT_ALLOWED
+ | StatusCode::NOT_ACCEPTABLE
+ ) {
+ response = client
+ .post(
+ &server,
+ &JsonRpcRequest::new(
+ RequestId::String("ema-auth-initialize".into()),
+ InitializeRequest::new(
+ InitializeRequestParams::new(
+ ClientCapabilities::default(),
+ Implementation::new("codex", env!("CARGO_PKG_VERSION")),
+ )
+ .with_protocol_version(ProtocolVersion::V_2025_06_18),
+ )
+ .into(),
+ ),
+ ProtocolVersion::V_2025_06_18,
+ )
+ .await?;
+ }
+ }
+ response
+ } else {
+ client.get(url).await?
+ };
+ if response.status() == StatusCode::UNAUTHORIZED {
+ let challenge_url = response
+ .headers()
+ .get_all(WWW_AUTHENTICATE)
+ .iter()
+ .filter_map(|value| value.to_str().ok())
+ .find_map(|value| {
+ WWWAuthenticateParams::parse(value, &server).resource_metadata_url
+ });
+ if let Some(url) = challenge_url {
+ response = client.get(url).await?;
+ }
+ }
+ if response.status() == StatusCode::OK
+ && let Ok(metadata) = serde_json::from_slice::<EmaResourceMetadata>(response.body())
+ {
+ resource_metadata = Some(metadata);
+ break;
+ }
+ }
+ let Some(EmaResourceMetadata {
+ resource,
+ authorization_server,
+ authorization_servers,
+ }) = resource_metadata
+ else {
+ bail!("enterprise MCP protected-resource metadata is missing or invalid");
+ };
+ if resource.trim().is_empty() {
+ bail!("enterprise MCP protected-resource identifier is empty");
+ }
+ validate_ema_auth_resource(request.server_url, Some(&resource))?;
+ if request
+ .resource
+ .is_some_and(|expected| expected != resource)
+ {
+ bail!(
+ "configured enterprise MCP resource does not match the RFC 9728 protected-resource metadata"
+ );
+ }
+ let mut issuers = authorization_server
+ .into_iter()
+ .chain(authorization_servers)
+ .collect::<Vec<_>>();
+ if issuers.len() > MAX_EMA_AUTHORIZATION_SERVERS {
+ bail!(
+ "enterprise MCP protected-resource metadata advertises too many authorization servers"
+ );
+ }
+ if let Some(expected) = request.expected_issuer {
+ issuers.retain(|issuer| issuer == expected);
+ if issuers.is_empty() {
+ bail!("enterprise MCP authorization server issuer does not match configured issuer");
+ }
+ }
+ Ok(EmaResource {
+ server_url: server,
+ resource,
+ authorization_servers: issuers,
+ client,
+ })
+}
diff --git a/codex-rs/rmcp-client/src/http_client_adapter.rs b/codex-rs/rmcp-client/src/http_client_adapter.rs
index bc49bd06c5..aa1239e0a4 100644
--- a/codex-rs/rmcp-client/src/http_client_adapter.rs
+++ b/codex-rs/rmcp-client/src/http_client_adapter.rs
@@ -796,7 +796,7 @@ fn mcp_redirect_policy(
// rmcp's automatic lifecycle does not yet recognize deployed legacy discovery
// rejection shapes. Remove this compatibility shim once the SDK does:
// https://github.com/modelcontextprotocol/rust-sdk/issues/1040
-fn legacy_discovery_fallback_response(
+pub(super) fn legacy_discovery_fallback_response(
request: &ClientJsonRpcMessage,
response: ServerJsonRpcMessage,
allow_uncorrelated_http_rejection: bool,
diff --git a/codex-rs/rmcp-client/src/lib.rs b/codex-rs/rmcp-client/src/lib.rs
index 3a4a2b0f1c..b4d65067ec 100644
--- a/codex-rs/rmcp-client/src/lib.rs
+++ b/codex-rs/rmcp-client/src/lib.rs
@@ -1,10 +1,12 @@
mod auth_status;
mod bounded_stdio_transport;
mod elicitation_client_service;
+mod ema_auth;
mod ema_auth_policy;
mod ema_claims;
mod ema_exchange;
mod ema_identity;
+mod ema_resource;
mod enterprise_oauth_login;
mod event_notification_transport;
mod executor_process_transport;
@@ -41,13 +43,12 @@ pub use auth_status::determine_streamable_http_auth_status;
pub use auth_status::determine_streamable_http_auth_status_from_credentials;
pub use auth_status::discover_streamable_http_oauth;
pub use codex_protocol::protocol::McpAuthStatus;
+pub use ema_auth::EmaAuthTokenExchangeRequest;
+pub use ema_auth::exchange_ema_auth_token;
pub use ema_auth_policy::EmaAuthFailure;
pub use ema_auth_policy::EmaInvalidGrantSource;
pub use ema_auth_policy::validate_ema_auth_resource;
-pub use ema_claims::validate_oidc_identity_assertion;
pub use ema_exchange::EmaAccessToken;
-pub use ema_exchange::EmaIdJagExchangeRequest;
-pub use ema_exchange::exchange_id_jag;
pub use ema_identity::EmaIdpIdentity;
pub use ema_identity::EmaIdpIdentityRequest;
pub use ema_identity::resolve_ema_idp_identity;