Harden MCP OAuth callback handling (#40691)

## Why

MCP servers can share an OAuth callback URL. Without a validated issuer or a
server-specific callback path, an authorization response could be associated
with the wrong server.

## What changed

- Use stable callbacks when authorization metadata advertises issuer-bound
  responses, and validate the returned issuer before exchanging the code.
- Retain server-specific callback IDs for providers without issuer support,
  including fallback to the global or default callback for legacy registered
  clients.
- Persist registered callback URLs for MCP servers and plugins, and insert the
  active listener port into portless loopback redirects.

## Testing

Add coverage for issuer validation, callback-mode discovery, registered and
legacy clients, plugin OAuth, CLI persistence, and loopback listener ports.

GitOrigin-RevId: 2878c92e237fc17fd3def0bd2e1cce3e104a3db8
This commit is contained in:
stevenlee-oai authored and copyberry committed 2026-08-25 20:26:23 +00:00
1 parent 32ce703a80
commit 9be8d6e1c3
28 files changed
+1096 -127

No files matched your search

+48 -5
View File
@@ -15,6 +15,8 @@ use tracing::debug;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth::StoredOAuthTokenStatus;
use crate::oauth::oauth_token_status;
use crate::oauth_callback::McpOAuthCallbackMode;
use crate::oauth_callback::callback_mode;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::utils::build_default_headers;
use codex_config::types::AuthKeyringBackendKind;
@@ -39,6 +41,7 @@ impl OAuthDiscoveryTimeout {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamableHttpOAuthDiscovery {
pub scopes_supported: Option<Vec<String>>,
pub callback_mode: McpOAuthCallbackMode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -263,9 +266,14 @@ async fn discover_streamable_http_oauth_with_manager(
) -> Result<Option<StreamableHttpOAuthDiscovery>> {
match authorization_manager.resolve_metadata().boxed().await {
Ok(resolution) if !resolution.source.is_discovered() => Ok(None),
Ok(resolution) => Ok(Some(StreamableHttpOAuthDiscovery {
scopes_supported: normalize_scopes(resolution.metadata.scopes_supported),
})),
Ok(resolution) => {
let metadata = resolution.metadata;
Ok(Some(StreamableHttpOAuthDiscovery {
callback_mode: callback_mode(&metadata)
.unwrap_or(McpOAuthCallbackMode::CallbackSpecific),
scopes_supported: normalize_scopes(metadata.scopes_supported),
}))
}
Err(AuthError::NoAuthorizationSupport) => Ok(None),
Err(err) => Err(err.into()),
}
@@ -668,6 +676,7 @@ mod tests {
let server = spawn_oauth_discovery_server(serde_json::json!({
"authorization_endpoint": "https://example.com/authorize",
"token_endpoint": "https://example.com/token",
"authorization_response_iss_parameter_supported": true,
"scopes_supported": ["profile", " email ", "profile", "", " "],
}))
.await;
@@ -685,8 +694,42 @@ mod tests {
.expect("oauth support should be detected");
assert_eq!(
discovery.scopes_supported,
Some(vec!["profile".to_string(), "email".to_string()])
discovery,
StreamableHttpOAuthDiscovery {
scopes_supported: Some(vec!["profile".to_string(), "email".to_string()]),
callback_mode: McpOAuthCallbackMode::IssuerBound,
}
);
}
#[tokio::test]
async fn issuer_support_without_a_metadata_issuer_falls_back_to_distinct_callbacks() {
let server = spawn_oauth_discovery_server(serde_json::json!({
"issuer": null,
"authorization_endpoint": "https://example.com/authorize",
"token_endpoint": "https://example.com/token",
"authorization_response_iss_parameter_supported": true,
}))
.await;
let discovery = discover_streamable_http_oauth(
&server.url,
/*http_headers*/ None,
/*env_http_headers*/ None,
test_http_client(),
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await
.expect("discovery should succeed")
.expect("oauth support should be detected");
assert_eq!(
discovery,
StreamableHttpOAuthDiscovery {
scopes_supported: None,
callback_mode: McpOAuthCallbackMode::CallbackSpecific,
}
);
}
+3
View File
@@ -9,6 +9,7 @@ mod in_process_transport;
mod local_stdio_transport;
mod logging_client_handler;
mod oauth;
mod oauth_callback;
mod oauth_client_registration;
mod oauth_http_client;
mod perform_oauth_login;
@@ -38,6 +39,8 @@ pub use oauth::delete_oauth_tokens;
pub use oauth::save_oauth_tokens;
pub use oauth::stored_oauth_credential_snapshot;
pub use oauth::stored_oauth_credentials;
pub use oauth_callback::McpOAuthCallbackMode;
pub use oauth_callback::resolve_mcp_oauth_callback_url;
pub use oauth_client_registration::McpOAuthClientRegistration;
pub use perform_oauth_login::OAuthProviderError;
pub use perform_oauth_login::OauthLoginHandle;
+148
View File
@@ -0,0 +1,148 @@
//! OAuth callback identity and authorization-server mix-up protection.
//!
//! Codex can authorize against many independent MCP servers. If those servers
//! share a callback URL and a response does not identify its authorization
//! server, Codex could associate an authorization code with the wrong server
//! and send that code to an attacker-controlled token endpoint. RFC 9700 calls
//! this an authorization-server mix-up attack:
//! https://www.rfc-editor.org/rfc/rfc9700#section-4.4
//!
//! MCP prefers issuer identification: authorization servers SHOULD include
//! `iss` in authorization responses; servers that include `iss` MUST advertise
//! that support, and clients MUST validate any returned issuer before
//! exchanging the code. This also lets a CIMD document advertise one stable
//! redirect instead of separate redirects for every authorization server:
//! https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#authorization-response-validation
//!
//! This module prefers issuer binding when available and otherwise retains a
//! callback-specific compatibility fallback:
//!
//! - `IssuerBound`: reuse a stable callback only when authorization metadata
//! advertises `authorization_response_iss_parameter_supported` and contains
//! its issuer. RMCP validates the response's `iss` against that metadata
//! issuer before exchanging the authorization code, rejecting missing or
//! mismatched issuers:
//! https://www.rfc-editor.org/rfc/rfc9700#section-4.4.2.1
//! https://www.rfc-editor.org/rfc/rfc9207#section-2.4
//! - `CallbackSpecific`: append an ID derived from the complete MCP server URL.
//! Distinct callback paths bind each response to its intended server. This is
//! the required fallback when issuer identification is not supported:
//! https://www.rfc-editor.org/rfc/rfc9700#section-4.4.2.2
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use rmcp::transport::auth::AuthorizationMetadata;
use sha2::Digest;
use sha2::Sha256;
use url::Url;
/// The OAuth mix-up defense associated with a newly registered callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpOAuthCallbackMode {
/// A server-specific redirect path identifies the authorization server.
CallbackSpecific,
/// A validated authorization-response issuer permits a shared redirect.
IssuerBound,
}
pub(crate) fn callback_mode(metadata: &AuthorizationMetadata) -> Result<McpOAuthCallbackMode> {
let issuer_response_supported = metadata
.additional_fields
.get("authorization_response_iss_parameter_supported")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if !issuer_response_supported {
return Ok(McpOAuthCallbackMode::CallbackSpecific);
}
if metadata.issuer.is_none() {
bail!("OAuth authorization server advertises issuer support without a metadata issuer");
}
Ok(McpOAuthCallbackMode::IssuerBound)
}
/// Resolves the registered callback independently of runtime listener ports.
pub fn resolve_mcp_oauth_callback_url(
server_url: &str,
callback_url: Option<&str>,
callback_mode: McpOAuthCallbackMode,
) -> Result<String> {
let callback_url = callback_url.unwrap_or("http://127.0.0.1/callback");
match callback_mode {
McpOAuthCallbackMode::IssuerBound => {
Url::parse(callback_url)
.with_context(|| format!("invalid redirect URI `{callback_url}`"))?;
Ok(callback_url.to_string())
}
McpOAuthCallbackMode::CallbackSpecific => {
let callback_id = callback_id_from_server_url(server_url)?;
append_callback_id_to_redirect_uri(callback_url, &callback_id)
}
}
}
pub(crate) fn callback_id_from_server_url(server_url: &str) -> Result<String> {
// Native Codex callback IDs intentionally hash the complete MCP URL (minus its fragment)
// with SHA-256. Python connector callback IDs use SHAKE-256 over the origin and are distinct.
let mut parsed =
Url::parse(server_url).with_context(|| format!("invalid MCP server URL `{server_url}`"))?;
parsed
.host_str()
.ok_or_else(|| anyhow!("MCP server URL `{server_url}` must include a host"))?;
parsed.set_fragment(None);
let digest = Sha256::digest(parsed.as_str().as_bytes());
Ok(URL_SAFE_NO_PAD.encode(&digest[..9]))
}
pub(crate) fn append_callback_id_to_redirect_uri(
redirect_uri: &str,
callback_id: &str,
) -> Result<String> {
let mut parsed = Url::parse(redirect_uri)
.with_context(|| format!("invalid redirect URI `{redirect_uri}`"))?;
if parsed
.path_segments()
.and_then(|mut segments| segments.next_back())
== Some(callback_id)
{
return Ok(parsed.to_string());
}
let path = parsed.path();
let new_path = if path.ends_with('/') {
format!("{path}{callback_id}")
} else {
format!("{path}/{callback_id}")
};
parsed.set_path(&new_path);
Ok(parsed.to_string())
}
pub(crate) fn validate_callback_redirect(
redirect_uri: &str,
callback_id: &str,
callback_mode: McpOAuthCallbackMode,
) -> Result<()> {
let has_expected_callback_id = Url::parse(redirect_uri)?
.path_segments()
.and_then(|mut segments| segments.next_back())
== Some(callback_id);
if !has_expected_callback_id && callback_mode != McpOAuthCallbackMode::IssuerBound {
bail!(
"OAuth callback requires its expected callback ID or authorization response issuer support"
);
}
Ok(())
}
#[cfg(test)]
#[path = "oauth_callback_tests.rs"]
mod tests;
@@ -0,0 +1,63 @@
use pretty_assertions::assert_eq;
use super::McpOAuthCallbackMode;
use super::callback_id_from_server_url;
use super::resolve_mcp_oauth_callback_url;
use super::validate_callback_redirect;
#[test]
fn resolved_callbacks_follow_the_selected_mix_up_defense() {
let server_url = "https://mcp.example.com/mcp?tenant=one";
let callback_id = callback_id_from_server_url(server_url).expect("resolve callback ID");
let distinct_callback = format!("http://127.0.0.1/callback/{callback_id}");
for (callback, mode, expected) in [
(
None,
McpOAuthCallbackMode::CallbackSpecific,
distinct_callback.as_str(),
),
(
None,
McpOAuthCallbackMode::IssuerBound,
"http://127.0.0.1/callback",
),
(
Some("http://127.0.0.1:8080/oauth/callback"),
McpOAuthCallbackMode::IssuerBound,
"http://127.0.0.1:8080/oauth/callback",
),
] {
assert_eq!(
resolve_mcp_oauth_callback_url(server_url, callback, mode)
.expect("resolve registered callback"),
expected
);
}
}
#[test]
fn callback_redirect_requires_a_server_specific_id_or_issuer_support() {
for (redirect_uri, mode, expected_valid) in [
(
"http://127.0.0.1/callback/expected-id",
McpOAuthCallbackMode::CallbackSpecific,
true,
),
(
"http://127.0.0.1/callback",
McpOAuthCallbackMode::IssuerBound,
true,
),
(
"http://127.0.0.1/callback/wrong-id",
McpOAuthCallbackMode::CallbackSpecific,
false,
),
] {
assert_eq!(
validate_callback_redirect(redirect_uri, "expected-id", mode).is_ok(),
expected_valid
);
}
}
@@ -10,6 +10,10 @@ use rmcp::transport::auth::OAuthState;
use url::Url;
use crate::oauth::validate_authorization_server_endpoints;
use crate::oauth_callback::McpOAuthCallbackMode;
use crate::oauth_callback::append_callback_id_to_redirect_uri;
use crate::oauth_callback::callback_mode;
use crate::oauth_callback::validate_callback_redirect;
/// OAuth client-registration strategy for one interactive HTTP MCP login.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -27,6 +31,7 @@ pub enum McpOAuthClientRegistration {
pub(crate) struct PreparedOAuthLogin {
pub(crate) oauth_state: OAuthState,
pub(crate) authorization_server_issuer: Option<String>,
pub(crate) redirect_uri: String,
}
pub(crate) async fn start_authorization(
@@ -43,6 +48,7 @@ pub(crate) async fn start_authorization(
let metadata = auth_manager.resolve_metadata().await?.metadata;
validate_authorization_server_endpoints(&metadata)?;
let authorization_server_issuer = metadata.issuer.clone();
let callback_mode = callback_mode(&metadata)?;
let cimd_advertised = metadata
.additional_fields
@@ -55,18 +61,30 @@ pub(crate) async fn start_authorization(
.and_then(serde_json::Value::as_array)
.is_some_and(|methods| methods.iter().any(|method| method.as_str() == Some("none")));
let parsed_redirect_uri = Url::parse(redirect_uri)?;
let uses_shared_callback = callback_mode == McpOAuthCallbackMode::IssuerBound;
let redirect_uri = if uses_shared_callback {
redirect_uri.to_string()
} else {
append_callback_id_to_redirect_uri(redirect_uri, callback_id)?
};
let parsed_redirect_uri = Url::parse(&redirect_uri)?;
let expected_callback_path = if uses_shared_callback {
"/callback".to_string()
} else {
format!("/callback/{callback_id}")
};
let native_redirect_supported = parsed_redirect_uri.scheme() == "http"
&& matches!(
parsed_redirect_uri.host_str(),
Some("127.0.0.1" | "localhost")
)
&& parsed_redirect_uri.port().is_some_and(|port| port > 0)
&& parsed_redirect_uri.path() == format!("/callback/{callback_id}")
&& parsed_redirect_uri.path() == expected_callback_path
&& parsed_redirect_uri.query().is_none()
&& parsed_redirect_uri.fragment().is_none()
&& parsed_redirect_uri.username().is_empty()
&& parsed_redirect_uri.password().is_none();
validate_callback_redirect(&redirect_uri, callback_id, callback_mode)?;
// MCP 2026-07-28 priority: pre-registered clients never reach this path; offer
// advertised CIMD here and otherwise let rmcp fall back to DCR.
// https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration
@@ -82,7 +100,7 @@ pub(crate) async fn start_authorization(
}
if !native_redirect_supported {
bail!(
"MCP OAuth CIMD requires an ephemeral loopback callback at `/callback/{callback_id}`"
"MCP OAuth CIMD requires an ephemeral loopback callback at `{expected_callback_path}`"
);
}
true
@@ -91,16 +109,19 @@ pub(crate) async fn start_authorization(
};
auth_manager.set_metadata(metadata);
let mut request = AuthorizationRequest::new(redirect_uri)
let mut request = AuthorizationRequest::new(redirect_uri.clone())
.with_scopes(scopes.iter().copied())
.with_client_name("Codex");
if offer_cimd {
// CIMD is an active IETF Internet-Draft: this HTTPS client identifier resolves
// to its self-referential JSON metadata document.
// https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/
request = request.with_client_metadata_url(format!(
"https://chatgpt.com/oauth/codex/{callback_id}/client.json"
));
let client_metadata_url = if uses_shared_callback {
"https://chatgpt.com/oauth/codex/client.json".to_string()
} else {
format!("https://chatgpt.com/oauth/codex/{callback_id}/client.json")
};
request = request.with_client_metadata_url(client_metadata_url);
}
let session = AuthorizationSession::new(auth_manager, request)
.await
@@ -109,6 +130,7 @@ pub(crate) async fn start_authorization(
Ok(PreparedOAuthLogin {
oauth_state: OAuthState::Session(session),
authorization_server_issuer,
redirect_uri,
})
}
@@ -128,20 +128,47 @@ async fn authorization(
}
#[tokio::test]
async fn automatic_cimd_uses_callback_specific_identity() -> Result<()> {
for host in ["127.0.0.1", "localhost"] {
let server = oauth_server(json!({})).await;
let redirect = format!("http://{host}:43123/callback/{CALLBACK_ID}");
async fn automatic_cimd_uses_stable_or_callback_specific_identity() -> Result<()> {
for (host, supports_issuer, expected_client_id, expected_redirect) in [
(
"127.0.0.1",
false,
"https://chatgpt.com/oauth/codex/abc123ABC_-x/client.json",
"http://127.0.0.1:43123/callback/abc123ABC_-x",
),
(
"localhost",
false,
"https://chatgpt.com/oauth/codex/abc123ABC_-x/client.json",
"http://localhost:43123/callback/abc123ABC_-x",
),
(
"127.0.0.1",
true,
"https://chatgpt.com/oauth/codex/client.json",
"http://127.0.0.1:43123/callback",
),
] {
let server = oauth_server(json!({
"authorization_response_iss_parameter_supported": supports_issuer,
}))
.await;
let redirect = format!("http://{host}:43123/callback");
let (mut state, query) =
authorization(&server, &redirect, McpOAuthClientRegistration::Auto).await?;
let expected_id = format!("https://chatgpt.com/oauth/codex/{CALLBACK_ID}/client.json");
assert_eq!(query["client_id"], expected_id);
assert_eq!(query["redirect_uri"], redirect);
assert_eq!(query["client_id"], expected_client_id);
assert_eq!(query["redirect_uri"], expected_redirect);
assert_eq!(query["code_challenge_method"], "S256");
assert_eq!(query["scope"], "read offline_access");
state
.handle_callback_with_issuer("valid-authorization-code", &query["state"], None)
.handle_callback_with_issuer(
"valid-authorization-code",
&query["state"],
supports_issuer
.then(|| format!("{}/mcp", server.uri()))
.as_deref(),
)
.await?;
let token_requests = requests_to(&server, "/token").await;
assert_eq!(token_requests.len(), 1);
@@ -149,8 +176,8 @@ async fn automatic_cimd_uses_callback_specific_identity() -> Result<()> {
let body: HashMap<_, _> = url::form_urlencoded::parse(&request.body)
.into_owned()
.collect();
assert_eq!(body["client_id"], expected_id);
assert_eq!(body["redirect_uri"], redirect);
assert_eq!(body["client_id"], expected_client_id);
assert_eq!(body["redirect_uri"], expected_redirect);
assert_eq!(body["grant_type"], "authorization_code");
assert!(body.contains_key("code_verifier"));
assert!(!body.contains_key("client_secret"));
@@ -170,6 +197,7 @@ async fn automatic_cimd_uses_callback_specific_identity() -> Result<()> {
#[tokio::test]
async fn registration_selection_preserves_dcr_capabilities_and_exact_redirects() -> Result<()> {
let native = "http://localhost:43123/callback/abc123ABC_-x";
let shared_native = "http://localhost:43123/callback";
let custom = "https://callbacks.example.com/oauth/callback/abc123ABC_-x";
for (metadata, redirect, registration, expected_redirect) in [
(
@@ -193,9 +221,9 @@ async fn registration_selection_preserves_dcr_capabilities_and_exact_redirects()
(json!({}), custom, McpOAuthClientRegistration::Auto, custom),
(
json!({"authorization_response_iss_parameter_supported": true}),
native,
shared_native,
McpOAuthClientRegistration::Dcr,
native,
shared_native,
),
] {
let server = oauth_server(metadata).await;
@@ -485,6 +513,14 @@ async fn resource_headers_follow_same_origin_registration_redirect_and_sdk_auth_
async fn invalid_cimd_metadata_and_redirects_fail_without_dynamic_registration() {
let valid = "http://127.0.0.1:43123/callback/abc123ABC_-x";
for (metadata, redirect, expected_error) in [
(
json!({
"authorization_response_iss_parameter_supported": true,
"issuer": null,
}),
valid,
"issuer-bound callbacks require an authorization server issuer",
),
(
json!({"token_endpoint_auth_methods_supported": ["private_key_jwt"]}),
valid,
+189 -68
View File
@@ -7,16 +7,13 @@ use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_exec_server::HttpClient;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::AuthorizationSession;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthClientConfig;
use rmcp::transport::auth::OAuthHttpClient;
use rmcp::transport::auth::OAuthState;
use sha2::Digest;
use sha2::Sha256;
use tiny_http::Response;
use tiny_http::Server;
use tokio::sync::oneshot;
@@ -29,6 +26,11 @@ use crate::WrappedOAuthTokenResponse;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth::compute_expires_at_millis;
use crate::oauth::validate_authorization_server_endpoints;
use crate::oauth_callback::McpOAuthCallbackMode;
use crate::oauth_callback::append_callback_id_to_redirect_uri;
use crate::oauth_callback::callback_id_from_server_url;
use crate::oauth_callback::callback_mode;
use crate::oauth_callback::validate_callback_redirect;
use crate::oauth_client_registration::McpOAuthClientRegistration;
use crate::oauth_client_registration::PreparedOAuthLogin;
use crate::oauth_client_registration::start_authorization as start_client_registration;
@@ -99,6 +101,7 @@ pub async fn perform_oauth_login(
oauth_resource: Option<&str>,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
http_client: Arc<dyn HttpClient>,
) -> Result<()> {
perform_oauth_login_with_browser_output(
@@ -114,6 +117,7 @@ pub async fn perform_oauth_login(
oauth_resource,
callback_port,
callback_url,
global_callback_url,
http_client,
/*emit_browser_url*/ true,
StreamableHttpRedirectMode::Legacy,
@@ -135,6 +139,7 @@ pub async fn perform_oauth_login_silent(
oauth_resource: Option<&str>,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
http_client: Arc<dyn HttpClient>,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<()> {
@@ -151,6 +156,7 @@ pub async fn perform_oauth_login_silent(
oauth_resource,
callback_port,
callback_url,
global_callback_url,
http_client,
/*emit_browser_url*/ false,
redirect_mode,
@@ -172,6 +178,7 @@ async fn perform_oauth_login_with_browser_output(
oauth_resource: Option<&str>,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
http_client: Arc<dyn HttpClient>,
emit_browser_url: bool,
redirect_mode: StreamableHttpRedirectMode,
@@ -195,6 +202,7 @@ async fn perform_oauth_login_with_browser_output(
/*launch_browser*/ true,
callback_port,
callback_url,
global_callback_url,
/*timeout_secs*/ None,
)
.await?
@@ -217,6 +225,7 @@ pub async fn perform_oauth_login_return_url(
timeout_secs: Option<i64>,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
http_client: Arc<dyn HttpClient>,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<OauthLoginHandle> {
@@ -239,6 +248,7 @@ pub async fn perform_oauth_login_return_url(
/*launch_browser*/ false,
callback_port,
callback_url,
global_callback_url,
timeout_secs,
)
.await?;
@@ -443,38 +453,32 @@ fn resolve_redirect_uri(server: &Server, callback_url: Option<&str>) -> Result<S
let Some(callback_url) = callback_url else {
return local_redirect_uri(server);
};
Url::parse(callback_url)
let mut parsed = Url::parse(callback_url)
.with_context(|| format!("invalid MCP OAuth callback URL `{callback_url}`"))?;
// Registered loopback callbacks omit the temporary listener port because
// the OS can assign a different port on every login. Add the active port
// only to this authorization request; RFC 8252 requires authorization
// servers to accept any request-time port for loopback IP redirects.
// https://www.rfc-editor.org/rfc/rfc8252#section-7.3
if parsed.scheme() == "http"
&& parsed.host_str() == Some("127.0.0.1")
&& parsed.port().is_none()
{
let listener_port = server
.server_addr()
.to_ip()
.ok_or_else(|| anyhow!("unable to determine OAuth callback listener port"))?
.port();
parsed
.set_port(Some(listener_port))
.map_err(|()| anyhow!("unable to set OAuth callback listener port"))?;
return Ok(parsed.to_string());
}
Ok(callback_url.to_string())
}
fn callback_id_from_server_url(server_url: &str) -> Result<String> {
// Native Codex callback IDs intentionally hash the complete MCP URL (minus its fragment)
// with SHA-256. Python connector callback IDs use SHAKE-256 over the origin and are distinct.
let mut parsed =
Url::parse(server_url).with_context(|| format!("invalid MCP server URL `{server_url}`"))?;
parsed
.host_str()
.ok_or_else(|| anyhow!("MCP server URL `{server_url}` must include a host"))?;
parsed.set_fragment(None);
let digest = Sha256::digest(parsed.as_str().as_bytes());
Ok(URL_SAFE_NO_PAD.encode(&digest[..9]))
}
fn append_callback_id_to_redirect_uri(redirect_uri: &str, callback_id: &str) -> Result<String> {
let mut parsed = Url::parse(redirect_uri)
.with_context(|| format!("invalid redirect URI `{redirect_uri}`"))?;
let path = parsed.path();
let new_path = if path.ends_with('/') {
format!("{path}{callback_id}")
} else {
format!("{path}/{callback_id}")
};
parsed.set_path(&new_path);
Ok(parsed.to_string())
}
fn callback_path_from_redirect_uri(redirect_uri: &str) -> Result<String> {
let parsed = Url::parse(redirect_uri)
.with_context(|| format!("invalid redirect URI `{redirect_uri}`"))?;
@@ -511,29 +515,24 @@ impl OauthLoginFlow {
launch_browser: bool,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
timeout_secs: Option<i64>,
) -> Result<Self> {
const DEFAULT_OAUTH_TIMEOUT_SECS: i64 = 300;
let bind_host = callback_bind_host(callback_url);
let callback_port = resolve_callback_port(callback_port)?;
let bind_addr = match callback_port {
Some(port) => format!("{bind_host}:{port}"),
None => format!("{bind_host}:0"),
};
let server = Arc::new(Server::http(&bind_addr).map_err(|err| anyhow!(err))?);
let guard = CallbackServerGuard {
server: Arc::clone(&server),
};
let redirect_uri = resolve_redirect_uri(&server, callback_url)?;
let callback_id = callback_id_from_server_url(server_url)?;
let redirect_uri = append_callback_id_to_redirect_uri(&redirect_uri, &callback_id)?;
let callback_path = callback_path_from_redirect_uri(&redirect_uri)?;
let (tx, rx) = oneshot::channel();
spawn_callback_server(server, tx, callback_path);
let oauth_client_id = oauth_client_id.filter(|client_id| !client_id.trim().is_empty());
let configured_callback = if oauth_client_id.is_some() {
callback_url
.map(|callback_url| {
Url::parse(callback_url)
.with_context(|| format!("invalid MCP OAuth callback URL `{callback_url}`"))
})
.transpose()?
} else {
None
};
let OAuthHttpContext {
http_headers,
@@ -548,26 +547,75 @@ impl OauthLoginFlow {
.as_ref()
.is_some_and(|headers| !headers.is_empty());
let default_headers = build_default_headers(http_headers, env_http_headers)?;
let oauth_http_client = Arc::new(OAuthHttpClientAdapter::new_with_redirect_mode(
http_client,
default_headers,
server_url,
has_configured_headers,
redirect_mode,
)?);
let oauth_http_client: Arc<dyn OAuthHttpClient> =
Arc::new(OAuthHttpClientAdapter::new_with_redirect_mode(
http_client,
default_headers,
server_url,
has_configured_headers,
redirect_mode,
)?);
let registered_authorization = if oauth_client_id.is_some() {
Some(resolve_authorization_manager(server_url, Arc::clone(&oauth_http_client)).await?)
} else {
None
};
let registered_callback_mode = registered_authorization
.as_ref()
.map(|(_, metadata)| callback_mode(metadata))
.transpose()?;
let use_legacy_fallback = registered_callback_mode
== Some(McpOAuthCallbackMode::CallbackSpecific)
&& configured_callback.as_ref().is_some_and(|callback_url| {
callback_url
.path_segments()
.and_then(|mut segments| segments.next_back())
!= Some(callback_id.as_str())
});
let callback_url = if use_legacy_fallback {
// Any preregistered client's callback can lack its required ID when
// the authorization server does not support issuer binding. This
// especially affects plugins, whose callbacks are configured before
// metadata discovery. Preserve compatibility and avoid making every
// login fail by using the global/default callback instead; its
// required server-specific callback ID is appended below.
global_callback_url
} else {
callback_url
};
let bind_host = callback_bind_host(callback_url);
// Port zero asks the OS for a free ephemeral port; the resolved
// redirect receives that port after the listener has been bound.
let bind_addr = match callback_port {
Some(port) => format!("{bind_host}:{port}"),
None => format!("{bind_host}:0"),
};
let server = Arc::new(Server::http(&bind_addr).map_err(|err| anyhow!(err))?);
let guard = CallbackServerGuard {
server: Arc::clone(&server),
};
let redirect_uri = resolve_redirect_uri(&server, callback_url)?;
let scope_refs: Vec<&str> = scopes.iter().map(String::as_str).collect();
let PreparedOAuthLogin {
oauth_state,
authorization_server_issuer,
} = if let Some(oauth_client_id) =
oauth_client_id.filter(|client_id| !client_id.trim().is_empty())
redirect_uri,
} = if let Some((oauth_client_id, (auth_manager, metadata))) =
oauth_client_id.zip(registered_authorization)
{
let redirect_uri = if callback_url.is_some() && !use_legacy_fallback {
redirect_uri
} else {
append_callback_id_to_redirect_uri(&redirect_uri, &callback_id)?
};
start_authorization(
server_url,
oauth_http_client,
auth_manager,
metadata,
&scope_refs,
&redirect_uri,
&callback_id,
oauth_client_id,
)
.await?
@@ -582,6 +630,9 @@ impl OauthLoginFlow {
)
.await?
};
let callback_path = callback_path_from_redirect_uri(&redirect_uri)?;
let (tx, rx) = oneshot::channel();
spawn_callback_server(server, tx, callback_path);
let auth_url = append_query_param(
&oauth_state.get_authorization_url().await?,
"resource",
@@ -700,19 +751,28 @@ impl OauthLoginFlow {
}
}
async fn start_authorization(
async fn resolve_authorization_manager(
server_url: &str,
http_client: Arc<dyn OAuthHttpClient>,
scopes: &[&str],
redirect_uri: &str,
oauth_client_id: &str,
) -> Result<PreparedOAuthLogin> {
) -> Result<(AuthorizationManager, AuthorizationMetadata)> {
let mut auth_manager =
AuthorizationManager::new_with_oauth_http_client(server_url, http_client).await?;
auth_manager.set_allow_missing_issuer(true);
let metadata = auth_manager.resolve_metadata().await?.metadata;
validate_authorization_server_endpoints(&metadata)?;
Ok((auth_manager, metadata))
}
async fn start_authorization(
mut auth_manager: AuthorizationManager,
metadata: AuthorizationMetadata,
scopes: &[&str],
redirect_uri: &str,
callback_id: &str,
oauth_client_id: &str,
) -> Result<PreparedOAuthLogin> {
let authorization_server_issuer = metadata.issuer.clone();
validate_callback_redirect(redirect_uri, callback_id, callback_mode(&metadata)?)?;
auth_manager.set_metadata(metadata);
auth_manager.configure_client(
OAuthClientConfig::new(oauth_client_id, redirect_uri)
@@ -727,6 +787,7 @@ async fn start_authorization(
redirect_uri,
)),
authorization_server_issuer,
redirect_uri: redirect_uri.to_string(),
})
}
@@ -792,6 +853,7 @@ mod tests {
use super::parse_oauth_callback;
use super::perform_oauth_login;
use super::perform_oauth_login_silent;
use super::resolve_authorization_manager;
use super::start_authorization;
use crate::oauth::stored_oauth_credentials;
use crate::oauth::test_support::TempCodexHome;
@@ -942,6 +1004,7 @@ mod tests {
/*launch_browser*/ false,
/*callback_port*/ None,
/*callback_url*/ None,
/*global_callback_url*/ None,
Some(/*timeout_secs*/ 5),
)
.await?;
@@ -977,7 +1040,7 @@ mod tests {
for (scopes, expected_scope) in [(&[][..], None), (&["read"][..], Some("read"))] {
let (base_url, registration_requests) = spawn_oauth_metadata_server().await;
let redirect_uri = "http://127.0.0.1:43123/callback/configured-client";
let prepared = start_authorization(
let (auth_manager, metadata) = resolve_authorization_manager(
&format!("{base_url}/mcp"),
Arc::new(OAuthHttpClientAdapter::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
@@ -986,8 +1049,15 @@ mod tests {
HeaderMap::new(),
&format!("{base_url}/mcp"),
)),
)
.await
.expect("resolve pre-registered OAuth metadata");
let prepared = start_authorization(
auth_manager,
metadata,
scopes,
redirect_uri,
"configured-client",
"eci-prd-pub-codex-123",
)
.await
@@ -1072,7 +1142,12 @@ mod tests {
.await
.expect("serve authorization metadata fixture");
});
let prepared = start_authorization(
let redirect_uri = if supports_issuer {
"http://127.0.0.1/callback"
} else {
"http://127.0.0.1/callback/test-callback"
};
let (auth_manager, metadata) = resolve_authorization_manager(
&format!("{issuer}/mcp"),
Arc::new(OAuthHttpClientAdapter::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
@@ -1081,8 +1156,15 @@ mod tests {
HeaderMap::new(),
&format!("{issuer}/mcp"),
)),
)
.await
.expect("resolve issuer-aware authorization metadata");
let prepared = start_authorization(
auth_manager,
metadata,
&[],
"http://127.0.0.1/callback",
redirect_uri,
"test-callback",
"test-client",
)
.await
@@ -1145,6 +1227,7 @@ mod tests {
/*oauth_resource*/ None,
/*callback_port*/ None,
/*callback_url*/ None,
/*global_callback_url*/ None,
http_client.clone(),
)
.await
@@ -1169,6 +1252,7 @@ mod tests {
/*oauth_resource*/ None,
/*callback_port*/ None,
/*callback_url*/ None,
/*global_callback_url*/ None,
http_client.clone(),
StreamableHttpRedirectMode::Legacy,
)
@@ -1276,6 +1360,11 @@ mod tests {
.expect("redirect URI should parse");
assert_eq!(redirect_uri, "http://127.0.0.1:1234/callback/abc123");
assert_eq!(
append_callback_id_to_redirect_uri(&redirect_uri, "abc123")
.expect("resolved redirect URI should parse"),
redirect_uri
);
}
#[test]
@@ -1292,6 +1381,38 @@ mod tests {
);
}
#[test]
fn portless_loopback_callbacks_use_the_active_listener_port() {
let server = tiny_http::Server::http("127.0.0.1:0").expect("start callback listener");
let listener_port = server
.server_addr()
.to_ip()
.expect("resolve callback listener address")
.port();
for path in ["/callback", "/callback/callback-id", "/custom/callback"] {
let callback = format!("http://127.0.0.1{path}");
assert_eq!(
super::resolve_redirect_uri(&server, Some(&callback))
.expect("insert active listener port"),
format!("http://127.0.0.1:{listener_port}{path}")
);
}
for callback in [
"http://localhost/callback",
"http://127.0.0.1:3080/callback",
"https://127.0.0.1/callback",
"https://devbox.example.com/callback",
] {
assert_eq!(
super::resolve_redirect_uri(&server, Some(callback))
.expect("preserve configured callback origin"),
callback
);
}
}
#[test]
fn append_query_param_adds_resource_to_absolute_url() {
let url = append_query_param(