Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,926 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use codex_exec_server::HttpClient;
use codex_protocol::protocol::McpAuthStatus;
use futures::FutureExt;
use http::HeaderMap;
use http::header::AUTHORIZATION;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::auth::AuthError;
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;
use codex_config::types::OAuthCredentialsStoreMode;
const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5);
/// Timeout policy for OAuth metadata discovery through a supplied HTTP client.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthDiscoveryTimeout {
/// Preserve the timeout requested by the OAuth implementation.
Requested,
/// Cap OAuth discovery requests at the supplied duration.
Capped(Duration),
}
impl OAuthDiscoveryTimeout {
/// Preserves the existing timeout for local OAuth discovery.
pub const LOCAL: Self = Self::Capped(DISCOVERY_TIMEOUT);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamableHttpOAuthDiscovery {
pub scopes_supported: Option<Vec<String>>,
pub callback_mode: McpOAuthCallbackMode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpLoginRequirement {
Login,
Reauthentication,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpAuthState {
Unsupported,
Unknown,
LoggedOut(McpLoginRequirement),
BearerToken,
OAuth,
}
impl From<McpAuthState> for McpAuthStatus {
fn from(value: McpAuthState) -> Self {
match value {
McpAuthState::Unsupported => Self::Unsupported,
McpAuthState::Unknown => Self::Unknown,
McpAuthState::LoggedOut(_) => Self::NotLoggedIn,
McpAuthState::BearerToken => Self::BearerToken,
McpAuthState::OAuth => Self::OAuth,
}
}
}
enum AuthStatusCheck {
Complete(McpAuthState),
Discover(HeaderMap),
}
/// Determine authentication status while routing OAuth discovery through the
/// provided HTTP client.
#[allow(clippy::too_many_arguments)]
pub async fn determine_streamable_http_auth_status(
server_name: &str,
url: &str,
bearer_token_env_var: Option<&str>,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
http_client: Arc<dyn HttpClient>,
discovery_timeout: OAuthDiscoveryTimeout,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<McpAuthState> {
let has_configured_headers = has_configured_headers(&http_headers, &env_http_headers);
let default_headers = match auth_status_before_discovery(
server_name,
url,
bearer_token_env_var,
http_headers,
env_http_headers,
store_mode,
keyring_backend_kind,
)? {
AuthStatusCheck::Complete(status) => return Ok(status),
AuthStatusCheck::Discover(default_headers) => default_headers,
};
determine_auth_status_from_discovery(
server_name,
url,
discover_streamable_http_oauth_with_headers_and_http_client(
url,
default_headers,
http_client,
discovery_timeout,
has_configured_headers,
redirect_mode,
)
.await,
)
}
/// Determine authentication status using only configured and stored credentials.
///
/// Returns `None` when determining the status would require OAuth metadata discovery.
pub fn determine_streamable_http_auth_status_from_credentials(
server_name: &str,
url: &str,
bearer_token_env_var: Option<&str>,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<Option<McpAuthState>> {
match auth_status_before_discovery(
server_name,
url,
bearer_token_env_var,
http_headers,
env_http_headers,
store_mode,
keyring_backend_kind,
)? {
AuthStatusCheck::Complete(status) => Ok(Some(status)),
AuthStatusCheck::Discover(_) => Ok(None),
}
}
fn auth_status_before_discovery(
server_name: &str,
url: &str,
bearer_token_env_var: Option<&str>,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<AuthStatusCheck> {
if bearer_token_env_var.is_some() {
return Ok(AuthStatusCheck::Complete(McpAuthState::BearerToken));
}
let default_headers = build_default_headers(http_headers, env_http_headers)?;
if default_headers.contains_key(AUTHORIZATION) {
return Ok(AuthStatusCheck::Complete(McpAuthState::BearerToken));
}
match oauth_token_status(server_name, url, store_mode, keyring_backend_kind)? {
StoredOAuthTokenStatus::Usable => {
return Ok(AuthStatusCheck::Complete(McpAuthState::OAuth));
}
StoredOAuthTokenStatus::AuthorizationRequired => {
return Ok(AuthStatusCheck::Complete(McpAuthState::LoggedOut(
McpLoginRequirement::Reauthentication,
)));
}
StoredOAuthTokenStatus::Missing => {}
}
Ok(AuthStatusCheck::Discover(default_headers))
}
fn determine_auth_status_from_discovery(
server_name: &str,
url: &str,
discovery: Result<Option<StreamableHttpOAuthDiscovery>>,
) -> Result<McpAuthState> {
match discovery {
Ok(Some(_)) => Ok(McpAuthState::LoggedOut(McpLoginRequirement::Login)),
Ok(None) => Ok(McpAuthState::Unsupported),
Err(error) => {
debug!(
"failed to detect OAuth support for MCP server `{server_name}` at {url}: {error:?}"
);
Err(error)
}
}
}
pub async fn discover_streamable_http_oauth(
url: &str,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
http_client: Arc<dyn HttpClient>,
discovery_timeout: OAuthDiscoveryTimeout,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<Option<StreamableHttpOAuthDiscovery>> {
let has_configured_headers = has_configured_headers(&http_headers, &env_http_headers);
let default_headers = build_default_headers(http_headers, env_http_headers)?;
discover_streamable_http_oauth_with_headers_and_http_client(
url,
default_headers,
http_client,
discovery_timeout,
has_configured_headers,
redirect_mode,
)
.await
}
async fn discover_streamable_http_oauth_with_headers_and_http_client(
url: &str,
default_headers: HeaderMap,
http_client: Arc<dyn HttpClient>,
discovery_timeout: OAuthDiscoveryTimeout,
has_configured_headers: bool,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<Option<StreamableHttpOAuthDiscovery>> {
let oauth_http_client = match discovery_timeout {
OAuthDiscoveryTimeout::Requested => OAuthHttpClientAdapter::new_with_redirect_mode(
http_client,
default_headers,
url,
has_configured_headers,
redirect_mode,
)?,
OAuthDiscoveryTimeout::Capped(max_timeout) => {
OAuthHttpClientAdapter::new_with_max_timeout_and_redirect_mode(
http_client,
default_headers,
url,
max_timeout,
has_configured_headers,
redirect_mode,
)?
}
};
let mut authorization_manager =
AuthorizationManager::new_with_oauth_http_client(url, Arc::new(oauth_http_client)).await?;
authorization_manager.set_allow_missing_issuer(true);
discover_streamable_http_oauth_with_manager(&mut authorization_manager).await
}
fn has_configured_headers(
http_headers: &Option<HashMap<String, String>>,
env_http_headers: &Option<HashMap<String, String>>,
) -> bool {
http_headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
|| env_http_headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
}
async fn discover_streamable_http_oauth_with_manager(
authorization_manager: &mut AuthorizationManager,
) -> Result<Option<StreamableHttpOAuthDiscovery>> {
match authorization_manager.resolve_metadata().boxed().await {
Ok(resolution) if !resolution.source.is_discovered() => Ok(None),
Ok(resolution) => {
let metadata = resolution.metadata;
let callback_mode =
callback_mode(&metadata).unwrap_or(McpOAuthCallbackMode::CallbackSpecific);
authorization_manager.set_metadata(metadata);
Ok(Some(StreamableHttpOAuthDiscovery {
callback_mode,
// Prefer the initial challenge's scopes, falling back to resource metadata.
scopes_supported: normalize_scopes(
authorization_manager.select_initial_scopes(&[]).await,
),
}))
}
Err(AuthError::NoAuthorizationSupport) => Ok(None),
Err(err) => Err(err.into()),
}
}
fn normalize_scopes(scopes_supported: Vec<String>) -> Option<Vec<String>> {
let mut normalized = Vec::new();
for scope in scopes_supported {
let scope = scope.trim();
if scope.is_empty() {
continue;
}
let scope = scope.to_string();
if !normalized.contains(&scope) {
normalized.push(scope);
}
}
if normalized.is_empty() {
None
} else {
Some(normalized)
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::Json;
use axum::Router;
use axum::http::StatusCode;
use axum::http::header::WWW_AUTHENTICATE;
use axum::routing::get;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use serial_test::serial;
use std::collections::HashMap;
use std::ffi::OsString;
use std::sync::Mutex;
use tokio::task::JoinHandle;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
struct TestServer {
url: String,
handle: JoinHandle<()>,
}
async fn test_http_client() -> Arc<dyn HttpClient> {
let client: Arc<dyn HttpClient> = Arc::new(RouteAwareHttpClient::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
));
crate::oauth::test_support::warm_http_client(client.as_ref())
.await
.expect("warm production HTTP client before discovery deadlines");
client
}
impl Drop for TestServer {
fn drop(&mut self) {
self.handle.abort();
}
}
#[derive(Default)]
struct RecordingHttpClient {
headers: Mutex<Option<Vec<(String, String)>>>,
redirect_policy: Mutex<Option<HttpRedirectPolicy>>,
timeout_ms: Mutex<Option<Option<u64>>>,
}
impl HttpClient for RecordingHttpClient {
fn http_request(
&self,
_params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
Box::pin(async {
Err(ExecServerError::HttpRequest(
"unexpected buffered request".to_string(),
))
})
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>>
{
*self
.headers
.lock()
.expect("header recorder lock should not be poisoned") = Some(
params
.headers
.iter()
.map(|header| (header.name.clone(), header.value.clone()))
.collect(),
);
*self
.timeout_ms
.lock()
.expect("timeout recorder lock should not be poisoned") = Some(params.timeout_ms);
*self
.redirect_policy
.lock()
.expect("redirect policy recorder lock should not be poisoned") =
Some(params.redirect_policy);
Box::pin(async {
Err(ExecServerError::HttpRequest(
"expected discovery request failure".to_string(),
))
})
}
}
fn assert_recorded_discovery_failure(discovery: Result<Option<StreamableHttpOAuthDiscovery>>) {
let error = discovery.expect_err("the recording HTTP client rejects OAuth discovery");
assert!(
matches!(
error.downcast_ref::<AuthError>(),
Some(AuthError::MetadataError(reason))
if reason.contains("expected discovery request failure")
),
"OAuth discovery must preserve the executor transport failure: {error:#}"
);
}
async fn spawn_oauth_discovery_server(metadata: serde_json::Value) -> TestServer {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let address = listener.local_addr().expect("listener should have address");
let mut metadata = metadata;
if let Some(metadata) = metadata.as_object_mut() {
metadata
.entry("issuer")
.or_insert_with(|| format!("http://{address}/mcp").into());
}
let app = Router::new().route(
"/.well-known/oauth-authorization-server/mcp",
get({
let metadata = metadata.clone();
move || {
let metadata = metadata.clone();
async move { Json(metadata) }
}
}),
);
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.expect("server should run");
});
TestServer {
url: format!("http://{address}/mcp"),
handle,
}
}
struct EnvVarGuard {
key: String,
original: Option<OsString>,
}
impl EnvVarGuard {
fn set(key: &str, value: &str) -> Self {
let original = std::env::var_os(key);
unsafe {
std::env::set_var(key, value);
}
Self {
key: key.to_string(),
original,
}
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
if let Some(value) = &self.original {
unsafe {
std::env::set_var(&self.key, value);
}
} else {
unsafe {
std::env::remove_var(&self.key);
}
}
}
}
#[tokio::test]
async fn determine_auth_status_uses_bearer_token_when_authorization_header_present() {
let status = determine_streamable_http_auth_status(
"server",
"not-a-url",
/*bearer_token_env_var*/ None,
Some(HashMap::from([(
"Authorization".to_string(),
"Bearer token".to_string(),
)])),
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::default(),
Arc::new(RecordingHttpClient::default()),
OAuthDiscoveryTimeout::Requested,
StreamableHttpRedirectMode::Legacy,
)
.await
.expect("status should compute");
assert_eq!(status, McpAuthState::BearerToken);
}
#[tokio::test]
#[serial(auth_status_env)]
async fn determine_auth_status_uses_bearer_token_when_env_authorization_header_present() {
let _guard = EnvVarGuard::set("CODEX_RMCP_CLIENT_AUTH_STATUS_TEST_TOKEN", "Bearer token");
let status = determine_streamable_http_auth_status(
"server",
"not-a-url",
/*bearer_token_env_var*/ None,
/*http_headers*/ None,
Some(HashMap::from([(
"Authorization".to_string(),
"CODEX_RMCP_CLIENT_AUTH_STATUS_TEST_TOKEN".to_string(),
)])),
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::default(),
Arc::new(RecordingHttpClient::default()),
OAuthDiscoveryTimeout::Requested,
StreamableHttpRedirectMode::Legacy,
)
.await
.expect("status should compute");
assert_eq!(status, McpAuthState::BearerToken);
}
#[tokio::test]
async fn oauth_metadata_preserves_login_without_probing_anonymous_tools() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let address = listener.local_addr().expect("listener should have address");
let metadata = serde_json::json!({
"issuer": format!("http://{address}/mcp"),
"authorization_endpoint": format!("http://{address}/authorize"),
"token_endpoint": format!("http://{address}/token"),
});
let app = Router::new()
.route(
"/mcp",
get(|| async { StatusCode::METHOD_NOT_ALLOWED }).post(
|Json(request): Json<serde_json::Value>| async move {
let result = match request["method"].as_str() {
Some("initialize") => serde_json::json!({
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "oauth", "version": "1"},
}),
Some("tools/list") => serde_json::json!({"tools": []}),
_ => serde_json::json!({}),
};
Json(serde_json::json!({
"jsonrpc": "2.0",
"id": request["id"],
"result": result,
}))
},
),
)
.route(
"/.well-known/oauth-authorization-server/mcp",
get(move || async move { Json(metadata) }),
);
let server = tokio::spawn(async move {
axum::serve(listener, app).await.expect("server should run");
});
let url = format!("http://{address}/mcp");
let discovery = discover_streamable_http_oauth(
&url,
/*http_headers*/ None,
/*env_http_headers*/ None,
test_http_client().await,
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await;
assert_eq!(
determine_auth_status_from_discovery("server", &url, discovery)
.expect("auth status should compute"),
McpAuthState::LoggedOut(McpLoginRequirement::Login)
);
server.abort();
}
#[tokio::test]
async fn oauth_discovery_does_not_follow_cross_origin_redirects() {
let redirect_target = MockServer::start().await;
let redirect_url = format!("{}/redirect-target", redirect_target.uri());
Mock::given(method("GET"))
.and(path("/redirect-target"))
.and(header("x-api-key", "sensitive-key"))
.respond_with(ResponseTemplate::new(200))
.expect(0)
.mount(&redirect_target)
.await;
let resource_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/mcp"))
.and(header("x-api-key", "sensitive-key"))
.respond_with(
ResponseTemplate::new(302).insert_header("location", redirect_url.clone()),
)
.expect(1)
.mount(&resource_server)
.await;
let error = discover_streamable_http_oauth(
&format!("{}/mcp", resource_server.uri()),
Some(HashMap::from([(
"x-api-key".to_string(),
"sensitive-key".to_string(),
)])),
/*env_http_headers*/ None,
test_http_client().await,
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await
.expect_err("cross-origin OAuth discovery redirects must be rejected");
assert!(
matches!(
error.downcast_ref::<AuthError>(),
Some(AuthError::MetadataError(reason))
if reason.contains("OAuth discovery redirect to non-same-origin URL rejected")
&& reason.contains(&redirect_url)
),
"OAuth discovery must preserve the cross-origin redirect rejection: {error:#}"
);
redirect_target.verify().await;
resource_server.verify().await;
}
#[tokio::test]
async fn determine_auth_status_preserves_transient_http_errors() {
let _home = crate::oauth::test_support::TempCodexHome::new();
for status in [
StatusCode::REQUEST_TIMEOUT,
StatusCode::TOO_EARLY,
StatusCode::TOO_MANY_REQUESTS,
] {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(status.as_u16()))
.expect(1)
.mount(&server)
.await;
let error = determine_streamable_http_auth_status(
"transient-http-error",
&format!("{}/mcp", server.uri()),
/*bearer_token_env_var*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
test_http_client().await,
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await
.expect_err("transient OAuth discovery failures must not become unsupported access");
assert!(
matches!(
error.downcast_ref::<AuthError>(),
Some(AuthError::MetadataError(reason)) if reason.contains(status.as_str())
),
"auth-status discovery must preserve HTTP {status}: {error:#}"
);
server.verify().await;
}
}
#[tokio::test]
async fn discover_streamable_http_oauth_does_not_use_authorization_server_scopes() {
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;
let discovery = discover_streamable_http_oauth(
&server.url,
/*http_headers*/ None,
/*env_http_headers*/ None,
test_http_client().await,
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::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().await,
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,
}
);
}
#[tokio::test]
async fn routed_oauth_discovery_caps_local_discovery_timeout() {
let http_client = Arc::new(RecordingHttpClient::default());
let discovery = discover_streamable_http_oauth(
"http://example.com/mcp",
/*http_headers*/ None,
/*env_http_headers*/ None,
http_client.clone(),
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await;
assert_recorded_discovery_failure(discovery);
assert_eq!(
*http_client
.timeout_ms
.lock()
.expect("timeout recorder lock should not be poisoned"),
Some(Some(
u64::try_from(DISCOVERY_TIMEOUT.as_millis())
.expect("discovery timeout should fit in u64")
))
);
}
#[tokio::test]
async fn routed_oauth_discovery_preserves_requested_timeout() {
let http_client = Arc::new(RecordingHttpClient::default());
let discovery = discover_streamable_http_oauth(
"http://example.com/mcp",
/*http_headers*/ None,
/*env_http_headers*/ None,
http_client.clone(),
OAuthDiscoveryTimeout::Requested,
StreamableHttpRedirectMode::Legacy,
)
.await;
assert_recorded_discovery_failure(discovery);
assert_eq!(
*http_client
.timeout_ms
.lock()
.expect("timeout recorder lock should not be poisoned"),
Some(Some(30_000))
);
}
#[tokio::test]
async fn routed_agent_plugin_oauth_discovery_stops_with_configured_headers() {
let http_client = Arc::new(RecordingHttpClient::default());
let discovery = discover_streamable_http_oauth(
"http://example.com/mcp",
Some(HashMap::from([(
"X-Mcp-Discovery".to_string(),
"configured-value".to_string(),
)])),
/*env_http_headers*/ None,
http_client.clone(),
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::AgentPluginV1,
)
.await;
assert_recorded_discovery_failure(discovery);
let headers = http_client
.headers
.lock()
.expect("header recorder lock should not be poisoned")
.clone()
.expect("discovery should issue an HTTP request");
assert_eq!(
headers
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("x-mcp-discovery"))
.map(|(_, value)| value.as_str()),
Some("configured-value")
);
assert_eq!(
*http_client
.redirect_policy
.lock()
.expect("redirect policy recorder lock should not be poisoned"),
Some(HttpRedirectPolicy::Stop)
);
}
#[tokio::test]
async fn discover_streamable_http_oauth_follows_protected_resource_metadata() {
let authorization_server = spawn_oauth_discovery_server(serde_json::json!({
"authorization_endpoint": "https://example.com/authorize",
"token_endpoint": "https://example.com/token",
"scopes_supported": ["unrelated:admin", "offline_access"],
}))
.await;
for (challenge_scope, expected_scopes) in [
("", vec!["read", "write", "offline_access"]),
(", scope=\"read\"", vec!["read", "offline_access"]),
] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let address = listener.local_addr().expect("listener should have address");
let resource_metadata_url = format!("http://{address}/oauth-resource");
let challenge =
format!("Bearer resource_metadata=\"{resource_metadata_url}\"{challenge_scope}");
let authorization_server_url = authorization_server.url.clone();
let app = Router::new()
.route(
"/mcp",
get(move || {
let challenge = challenge.clone();
async move { (StatusCode::UNAUTHORIZED, [(WWW_AUTHENTICATE, challenge)]) }
}),
)
.route(
"/oauth-resource",
get(move || {
let authorization_server_url = authorization_server_url.clone();
async move {
Json(serde_json::json!({
"resource": format!("http://{address}/mcp"),
"authorization_servers": [authorization_server_url],
"scopes_supported": ["read", " write ", "read", "", " "],
}))
}
}),
);
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.expect("server should run");
});
let resource_server = TestServer {
url: format!("http://{address}/mcp"),
handle,
};
let discovery = discover_streamable_http_oauth(
&resource_server.url,
/*http_headers*/ None,
/*env_http_headers*/ None,
test_http_client().await,
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await
.expect("discovery should succeed")
.expect("oauth support should be detected");
assert_eq!(
discovery.scopes_supported,
Some(expected_scopes.into_iter().map(str::to_string).collect())
);
}
}
#[tokio::test]
async fn supports_oauth_login_does_not_require_scopes_supported() {
let server = spawn_oauth_discovery_server(serde_json::json!({
"authorization_endpoint": "https://example.com/authorize",
"token_endpoint": "https://example.com/token",
}))
.await;
let supported = discover_streamable_http_oauth(
&server.url,
/*http_headers*/ None,
/*env_http_headers*/ None,
test_http_client().await,
OAuthDiscoveryTimeout::LOCAL,
StreamableHttpRedirectMode::Legacy,
)
.await
.expect("support check should succeed")
.is_some();
assert!(supported);
}
}

View File

@@ -0,0 +1,151 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use rmcp::ErrorData as McpError;
use rmcp::ServiceExt;
use rmcp::handler::server::ServerHandler;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CallToolResult;
use rmcp::model::JsonObject;
use rmcp::model::ListToolsResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ServerCapabilities;
use rmcp::model::ServerConfig;
use rmcp::model::Tool;
use serde::Deserialize;
use serde_json::json;
use tokio::task;
#[derive(Clone)]
struct TestToolServer {
tools: Arc<Vec<Tool>>,
}
pub fn stdio() -> (tokio::io::Stdin, tokio::io::Stdout) {
(tokio::io::stdin(), tokio::io::stdout())
}
impl TestToolServer {
fn new() -> Self {
let tools = vec![Self::echo_tool()];
Self {
tools: Arc::new(tools),
}
}
fn echo_tool() -> Tool {
#[expect(clippy::expect_used)]
let schema: JsonObject = serde_json::from_value(json!({
"type": "object",
"properties": {
"message": { "type": "string" },
"env_var": { "type": "string" }
},
"required": ["message"],
"additionalProperties": false
}))
.expect("echo tool schema should deserialize");
let mut tool = Tool::new(
Cow::Borrowed("echo"),
Cow::Borrowed("Echo back the provided message and include environment data."),
Arc::new(schema),
);
#[expect(clippy::expect_used)]
let output_schema: JsonObject = serde_json::from_value(json!({
"type": "object",
"properties": {
"echo": { "type": "string" },
"env": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
]
}
},
"required": ["echo", "env"],
"additionalProperties": false
}))
.expect("echo tool output schema should deserialize");
tool.output_schema = Some(Arc::new(output_schema));
tool
}
}
#[derive(Deserialize)]
struct EchoArgs {
message: String,
env_var: Option<String>,
}
impl ServerHandler for TestToolServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_tool_list_changed()
.build(),
)
}
fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
let tools = self.tools.clone();
async move { Ok(ListToolsResult::with_all_items((*tools).clone())) }
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> Result<rmcp::model::CallToolResponse, McpError> {
match request.name.as_ref() {
"echo" => {
let args: EchoArgs = match request.arguments {
Some(arguments) => serde_json::from_value(serde_json::Value::Object(
arguments.into_iter().collect(),
))
.map_err(|err| McpError::invalid_params(err.to_string(), None))?,
None => {
return Err(McpError::invalid_params(
"missing arguments for echo tool",
None,
));
}
};
let env_snapshot: HashMap<String, String> = std::env::vars().collect();
let env_name = args.env_var.as_deref().unwrap_or("MCP_TEST_VALUE");
let structured_content = json!({
"echo": args.message,
"env": env_snapshot.get(env_name),
});
let mut result = CallToolResult::success(Vec::new());
result.structured_content = Some(structured_content);
Ok(result.into())
}
other => Err(McpError::invalid_params(
format!("unknown tool: {other}"),
None,
)),
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
eprintln!("starting rmcp test server");
// Run the server with STDIO transport. If the client disconnects we simply
// bubble up the error so the process exits.
let service = TestToolServer::new();
let running = service.serve(stdio()).await?;
// Wait for the client to finish interacting with the server.
running.waiting().await?;
// Drain background tasks to ensure clean shutdown.
task::yield_now().await;
Ok(())
}

View File

@@ -0,0 +1,66 @@
use std::io;
use std::io::BufRead;
use std::io::Write;
use anyhow::Result;
use serde_json::Value;
use serde_json::json;
fn main() -> Result<()> {
assert!(std::env::var_os("CODEX_MCP_PROTOCOL_VERSION").is_none());
let mut stdout = io::stdout().lock();
for line in io::stdin().lock().lines() {
let request: Value = serde_json::from_str(&line?)?;
let result = match request["method"].as_str() {
Some("server/discover") => {
assert_eq!(
request["params"]["_meta"]["io.modelcontextprotocol/protocolVersion"],
"2026-07-28"
);
json!({
"resultType": "complete",
"supportedVersions": ["2026-07-28"],
"capabilities": {"tools": {}, "resources": {}},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "strict-stdio-discovery",
"version": "1.0.0",
},
},
"ttlMs": 0,
"cacheScope": "private",
})
}
Some("tools/list") => json!({
"resultType": "complete",
"tools": [{
"name": "stdio_echo",
"inputSchema": {"type": "object"},
}],
}),
Some("resources/list") => json!({
"resultType": "complete",
"resources": [{
"uri": "test://stdio/resource",
"name": "stdio resource",
}],
}),
Some("resources/templates/list") => json!({
"resultType": "complete",
"resourceTemplates": [{
"uriTemplate": "test://stdio/{name}",
"name": "stdio resource template",
}],
}),
method => anyhow::bail!("unexpected modern stdio discovery method: {method:?}"),
};
serde_json::to_writer(
&mut stdout,
&json!({"jsonrpc": "2.0", "id": request["id"], "result": result}),
)?;
stdout.write_all(b"\n")?;
stdout.flush()?;
}
Ok(())
}

View File

@@ -0,0 +1,339 @@
use std::io;
use std::io::BufRead;
use std::io::Write;
use anyhow::Context;
use anyhow::Result;
use serde_json::Value;
use serde_json::json;
const MODERN_VERSION: &str = "2026-07-28";
const LEGACY_VERSION: &str = "2025-06-18";
const MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024;
fn write_message(stdout: &mut io::StdoutLock<'_>, message: Value) -> Result<()> {
serde_json::to_writer(&mut *stdout, &message)?;
stdout.write_all(b"\n")?;
stdout.flush()?;
Ok(())
}
fn assert_modern_metadata(message: &Value) {
let metadata = &message["params"]["_meta"];
assert_eq!(
metadata["io.modelcontextprotocol/protocolVersion"],
MODERN_VERSION
);
assert!(metadata["io.modelcontextprotocol/clientInfo"].is_object());
assert!(metadata["io.modelcontextprotocol/clientCapabilities"].is_object());
}
fn legacy_schema_defaults() -> Value {
json!({
"name": "John Doe",
"age": 30,
"score": 95.5,
"status": "active",
"verified": true,
})
}
fn main() -> Result<()> {
let mode = std::env::args().nth(1).unwrap_or_default();
assert!(matches!(
mode.as_str(),
"modern"
| "modern-late"
| "legacy"
| "legacy-fallback"
| "legacy-reject-and-exit"
| "legacy-init-first"
| "legacy-reject-late-initialize"
| "legacy-late"
| "legacy-silent"
| "legacy-versions"
| "oversized-stdout"
| "oversized-stdout-legacy"
));
assert!(std::env::var_os("CODEX_MCP_PROTOCOL_VERSION").is_none());
let is_legacy = mode.starts_with("legacy") || mode.ends_with("-legacy");
let oversized = mode.starts_with("oversized-stdout");
let mut stdout = io::stdout().lock();
let mut initialized = false;
let mut pending_legacy_call = None;
let mut late_discovery_id = None;
for (index, line) in io::stdin().lock().lines().enumerate() {
let message: Value = serde_json::from_str(&line?)?;
let Some(method) = message.get("method").and_then(Value::as_str) else {
let pending_call = pending_legacy_call
.take()
.ok_or_else(|| anyhow::anyhow!("unexpected server-request response"))?;
assert_eq!(message["id"], "legacy-approval");
assert_eq!(message["result"]["action"], "accept");
assert_eq!(message["result"]["content"], legacy_schema_defaults());
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0",
"id": pending_call,
"result": {"content": [{"type": "text", "text": "legacy approved"}]},
}),
)?;
continue;
};
// Some older helpers assume their first request is initialize without inspecting its method.
let method = if mode == "legacy-init-first" && !initialized {
"initialize"
} else {
method
};
match method {
// Some legacy stdio servers exit if their first message is not initialize.
"server/discover" if mode == "legacy" => {
// Some wrappers print a banner before starting the protocol.
writeln!(stdout, "starting server")?;
write_message(
&mut stdout,
json!({"jsonrpc": "2.0", "id": "startup", "method": "ping"}),
)?;
return Ok(());
}
"server/discover" if mode == "legacy-late" => {
late_discovery_id = Some(message["id"].clone());
}
// The first helper makes its version offer only after it receives initialize.
"server/discover"
if mode == "modern-late"
&& !std::path::Path::new("retry-modern").try_exists()? => {}
"initialize" if mode == "modern-late" => {
std::fs::write("retry-modern", [])?;
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0", "id": null,
"error": {"code": -32022, "message": "unsupported protocol", "data": {"supported": [MODERN_VERSION]}},
}),
)?;
return Ok(());
}
"server/discover" if mode == "legacy-silent" => {
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0", "method": "notifications/message",
"params": {"level": "info", "data": "starting server"},
}),
)?;
}
"server/discover" if mode == "legacy-versions" => {
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0", "id": message["id"],
"error": {"code": -32022, "message": "unsupported protocol", "data": {"supported": [LEGACY_VERSION]}},
}),
)?;
}
"server/discover" if is_legacy => {
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0",
"id": message["id"],
"error": {"code": -32601, "message": "method not found"},
}),
)?;
if mode == "legacy-reject-and-exit" {
return Ok(());
}
}
"server/discover" => {
assert!(!initialized);
assert_modern_metadata(&message);
initialized = true;
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0",
"id": message["id"],
"result": {
"resultType": "complete",
"supportedVersions": [MODERN_VERSION],
"capabilities": {"tools": {}, "resources": {}},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "strict-stdio-test",
"version": "1.0.0",
},
},
"ttlMs": 0,
"cacheScope": "private",
},
}),
)?;
}
"initialize" if mode == "legacy-reject-late-initialize" && index != 0 => {
write_message(
&mut stdout,
json!({"jsonrpc": "2.0", "id": message["id"], "error": {
"code": -32600, "message": "initialize must be the first request"
}}),
)?;
}
"initialize" => {
assert!(is_legacy);
if mode == "legacy-late" {
let id = late_discovery_id
.take()
.context("initialize must follow discover on the same pipe")?;
write_message(
&mut stdout,
json!({"jsonrpc":"2.0","id":id,"error":{"code":-32601,"message":"Method not found"}}),
)?;
}
if message["method"] == "initialize" {
assert_eq!(message["params"]["protocolVersion"], LEGACY_VERSION);
}
initialized = true;
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0",
"id": message["id"],
"result": {
"protocolVersion": LEGACY_VERSION,
"capabilities": {"tools": {}},
"serverInfo": {"name": "legacy-stdio-test", "version": "1.0.0"},
},
}),
)?;
}
"notifications/initialized" => assert!(is_legacy),
"tools/list" => {
assert!(initialized);
if !is_legacy {
assert_modern_metadata(&message);
}
if mode == "oversized-stdout-legacy" {
write!(stdout, "\u{feff}")?;
}
let description = if oversized {
"x".repeat(MAX_MESSAGE_BYTES + 1)
} else {
"echo a value".to_owned()
};
let mut result = json!({
"tools": [{
"name": "echo",
"description": description,
"inputSchema": {"type": "object"},
}],
});
if !is_legacy {
result["resultType"] = json!("complete");
result["ttlMs"] = json!(0);
result["cacheScope"] = json!("private");
}
write_message(
&mut stdout,
json!({"jsonrpc": "2.0", "id": message["id"], "result": result}),
)?;
}
"tools/call" if is_legacy => {
assert!(initialized);
pending_legacy_call = Some(message["id"].clone());
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0",
"id": "legacy-approval",
"method": "elicitation/create",
"params": {
"message": "Accept the schema defaults",
"requestedSchema": {
"type": "object",
"properties": {
"name": {"type": "string", "default": "John Doe"},
"age": {"type": "integer", "default": 30},
"score": {"type": "number", "default": 95.5},
"status": {
"type": "string",
"enum": ["active", "inactive"],
"default": "active",
},
"verified": {"type": "boolean", "default": true},
},
"required": [],
},
},
}),
)?;
}
"tools/call" => {
assert!(initialized);
assert_modern_metadata(&message);
if message.pointer("/params/inputResponses").is_none() {
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0",
"id": message["id"],
"result": {
"resultType": "input_required",
"inputRequests": {
"approval": {
"method": "elicitation/create",
"params": {
"mode": "form",
"message": "Approve stdio call?",
"requestedSchema": {
"type": "object",
"properties": {
"approved": {"type": "boolean"},
},
},
},
},
},
"requestState": "stdio-state",
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "strict-stdio-test",
"version": "1.0.0",
},
},
},
}),
)?;
continue;
}
assert_eq!(message["params"]["requestState"], "stdio-state");
assert_eq!(
message["params"]["inputResponses"]["approval"]["action"],
"accept"
);
assert_eq!(
message["params"]["inputResponses"]["approval"]["content"]["approved"],
true
);
write_message(
&mut stdout,
json!({
"jsonrpc": "2.0",
"id": message["id"],
"result": {
"resultType": "complete",
"content": [{"type": "text", "text": "modern approved"}],
},
}),
)?;
}
other => anyhow::bail!("unexpected MCP method {other}"),
}
}
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,599 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs;
use std::io::ErrorKind;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use axum::body::Body;
use axum::body::to_bytes;
use axum::extract::Json;
use axum::extract::State;
use axum::http::HeaderMap;
use axum::http::HeaderValue;
use axum::http::Method;
use axum::http::Request;
use axum::http::StatusCode;
use axum::http::header::AUTHORIZATION;
use axum::http::header::CONTENT_TYPE;
use axum::http::header::HOST;
use axum::http::header::WWW_AUTHENTICATE;
use axum::middleware;
use axum::middleware::Next;
use axum::response::Response;
use axum::routing::get;
use axum::routing::post;
use rmcp::ErrorData as McpError;
use rmcp::handler::server::ServerHandler;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CallToolResult;
use rmcp::model::JsonObject;
use rmcp::model::ListResourceTemplatesResult;
use rmcp::model::ListResourcesResult;
use rmcp::model::ListToolsResult;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::Resource;
use rmcp::model::ResourceContents;
use rmcp::model::ResourceTemplate;
use rmcp::model::ServerCapabilities;
use rmcp::model::ServerConfig;
use rmcp::model::Tool;
use rmcp::model::ToolAnnotations;
use rmcp::transport::StreamableHttpServerConfig;
use rmcp::transport::StreamableHttpService;
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use serde::Deserialize;
use serde_json::Value;
use serde_json::json;
use tokio::sync::Mutex;
use tokio::task;
use tokio::time::sleep;
#[derive(Clone)]
struct TestToolServer {
tools: Arc<Vec<Tool>>,
resources: Arc<Vec<Resource>>,
resource_templates: Arc<Vec<ResourceTemplate>>,
}
const MEMO_URI: &str = "memo://codex/example-note";
const MEMO_CONTENT: &str = "This is a sample MCP resource served by the rmcp test server.";
const MCP_SESSION_ID_HEADER: &str = "mcp-session-id";
const SESSION_POST_FAILURE_CONTROL_PATH: &str = "/test/control/session-post-failure";
const INITIALIZE_POST_FAILURE_CONTROL_PATH: &str = "/test/control/initialize-post-failure";
const INITIALIZED_NOTIFICATION_POST_FAILURE_CONTROL_PATH: &str =
"/test/control/initialized-notification-post-failure";
const MAX_MCP_POST_BODY_BYTES: usize = 1024 * 1024;
#[derive(Clone, Default)]
struct PostFailureState {
armed_failure: Arc<Mutex<Option<ArmedFailure>>>,
}
#[derive(Clone, Copy, Debug)]
enum ArmedFailureTarget {
Initialize,
InitializedNotification,
Session,
}
#[derive(Clone, Debug)]
struct ArmedFailure {
target: ArmedFailureTarget,
status: StatusCode,
remaining: usize,
/// Raw `WWW-Authenticate` challenge header field values returned with the failure.
www_authenticate_headers: Vec<HeaderValue>,
content_type: Option<HeaderValue>,
body: Option<String>,
}
#[derive(Debug, Deserialize)]
struct ArmSessionPostFailureRequest {
status: u16,
remaining: usize,
/// Raw `WWW-Authenticate` challenge header field values to add to the failure.
#[serde(default)]
www_authenticate_headers: Vec<String>,
content_type: Option<String>,
body: Option<String>,
}
#[derive(Deserialize)]
struct EchoArgs {
message: String,
#[allow(dead_code)]
env_var: Option<String>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args_os().skip(1);
match args.next().as_deref() {
Some(value) if value == std::ffi::OsStr::new("--http-headers-helper") => {
if std::env::var_os("MCP_TEST_AMBIENT_SECRET").is_some() {
return Err("helper inherited ambient secret".into());
}
if let Some(invocations) = args.next() {
let count = fs::read_to_string(&invocations).unwrap_or_default().len() + 1;
fs::write(invocations, "x".repeat(count))?;
let header =
if args.next().as_deref() == Some(std::ffi::OsStr::new("--authorization")) {
"Authorization"
} else {
"Proxy-Authorization"
};
println!(
r#"{{"{header}":"Bearer gateway-token","X-Helper-Generation":"{count}"}}"#
);
} else {
println!(r#"{{"Proxy-Authorization":"Bearer gateway-token"}}"#);
}
return Ok(());
}
_ => {}
}
let bind_addr = parse_bind_addr()?;
let post_failure_state = PostFailureState::default();
const MAX_BIND_RETRIES: u32 = 20;
const BIND_RETRY_DELAY: Duration = Duration::from_millis(50);
let mut bind_retries = 0;
let listener = loop {
match tokio::net::TcpListener::bind(&bind_addr).await {
Ok(listener) => break listener,
Err(err) if err.kind() == ErrorKind::PermissionDenied => {
eprintln!(
"failed to bind to {bind_addr}: {err}. make sure the process has network access"
);
return Ok(());
}
Err(err) if err.kind() == ErrorKind::AddrInUse && bind_retries < MAX_BIND_RETRIES => {
bind_retries += 1;
sleep(BIND_RETRY_DELAY).await;
}
Err(err) => return Err(err.into()),
}
};
let actual_bind_addr = listener.local_addr()?;
if let Ok(bound_addr_file) = std::env::var("MCP_STREAMABLE_HTTP_BOUND_ADDR_FILE") {
fs::write(bound_addr_file, actual_bind_addr.to_string())?;
}
eprintln!("starting rmcp streamable http test server on http://{actual_bind_addr}/mcp");
let mut transport_config = StreamableHttpServerConfig::default();
if !actual_bind_addr.ip().is_loopback() {
transport_config
.allowed_hosts
.push(actual_bind_addr.to_string());
transport_config =
transport_config.with_allowed_origins([format!("http://{actual_bind_addr}")]);
}
let router = Router::new()
.route(
SESSION_POST_FAILURE_CONTROL_PATH,
post(arm_session_post_failure),
)
.route(
INITIALIZE_POST_FAILURE_CONTROL_PATH,
post(arm_initialize_post_failure),
)
.route(
INITIALIZED_NOTIFICATION_POST_FAILURE_CONTROL_PATH,
post(arm_initialized_notification_post_failure),
)
.route(
"/.well-known/oauth-authorization-server/mcp",
get({
move |headers: HeaderMap| async move {
let metadata_base = headers
.get(HOST)
.and_then(|value| value.to_str().ok())
.map(|host| format!("http://{host}"))
.unwrap_or_else(|| format!("http://{actual_bind_addr}"));
#[expect(clippy::expect_used)]
Response::builder()
.status(StatusCode::OK)
.header(CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::to_vec(&json!({
"issuer": format!("{metadata_base}/mcp"),
"authorization_endpoint": format!("{metadata_base}/oauth/authorize"),
"token_endpoint": format!("{metadata_base}/oauth/token"),
"scopes_supported": [""],
})).expect("failed to serialize metadata"),
))
.expect("valid metadata response")
}
}),
)
.route(
"/oauth/token",
post(|| async {
(
StatusCode::BAD_REQUEST,
Json(json!({
"error": "invalid_grant",
"error_description": "refresh token expired or revoked",
})),
)
}),
)
.nest_service(
"/mcp",
StreamableHttpService::new(
|| Ok(TestToolServer::new()),
Arc::new(LocalSessionManager::default()),
transport_config,
),
)
.layer(middleware::from_fn_with_state(
post_failure_state.clone(),
fail_mcp_post_when_armed,
))
.with_state(post_failure_state);
let router = if let Ok(token) = std::env::var("MCP_EXPECT_BEARER") {
let expected = Arc::new(format!("Bearer {token}"));
router.layer(middleware::from_fn_with_state(expected, require_bearer))
} else {
router
};
let router = if let Ok(token) = std::env::var("MCP_EXPECT_GATEWAY_BEARER") {
let expected = Arc::new(format!("Bearer {token}"));
router.layer(middleware::from_fn_with_state(
expected,
require_gateway_bearer,
))
} else {
router
};
axum::serve(listener, router).await?;
task::yield_now().await;
Ok(())
}
impl ServerHandler for TestToolServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_tool_list_changed()
.enable_resources()
.build(),
)
}
fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
let tools = self.tools.clone();
async move { Ok(ListToolsResult::with_all_items((*tools).clone())) }
}
fn list_resources(
&self,
_request: Option<PaginatedRequestParams>,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> impl std::future::Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ {
let resources = self.resources.clone();
async move { Ok(ListResourcesResult::with_all_items((*resources).clone())) }
}
async fn list_resource_templates(
&self,
_request: Option<PaginatedRequestParams>,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> Result<ListResourceTemplatesResult, McpError> {
Ok(ListResourceTemplatesResult::with_all_items(
(*self.resource_templates).clone(),
))
}
async fn read_resource(
&self,
ReadResourceRequestParams { uri, .. }: ReadResourceRequestParams,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> Result<rmcp::model::ReadResourceResponse, McpError> {
if uri == MEMO_URI {
Ok(
ReadResourceResult::new(vec![ResourceContents::TextResourceContents {
uri,
mime_type: Some("text/plain".to_string()),
text: Self::memo_text().to_string(),
meta: None,
}])
.into(),
)
} else {
Err(McpError::resource_not_found(
"resource_not_found",
Some(json!({ "uri": uri })),
))
}
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> Result<rmcp::model::CallToolResponse, McpError> {
match request.name.as_ref() {
"echo" => {
let args: EchoArgs = match request.arguments {
Some(arguments) => serde_json::from_value(serde_json::Value::Object(
arguments.into_iter().collect(),
))
.map_err(|err| McpError::invalid_params(err.to_string(), None))?,
None => {
return Err(McpError::invalid_params(
"missing arguments for echo tool",
None,
));
}
};
let env_snapshot: HashMap<String, String> = std::env::vars().collect();
let structured_content = json!({
"echo": format!("ECHOING: {}", args.message),
"env": env_snapshot.get("MCP_TEST_VALUE"),
});
let mut result = CallToolResult::success(Vec::new());
result.structured_content = Some(structured_content);
Ok(result.into())
}
other => Err(McpError::invalid_params(
format!("unknown tool: {other}"),
None,
)),
}
}
}
impl TestToolServer {
fn new() -> Self {
let tools = vec![Self::echo_tool()];
let resources = vec![Self::memo_resource()];
let resource_templates = vec![Self::memo_template()];
Self {
tools: Arc::new(tools),
resources: Arc::new(resources),
resource_templates: Arc::new(resource_templates),
}
}
fn echo_tool() -> Tool {
#[expect(clippy::expect_used)]
let schema: JsonObject = serde_json::from_value(json!({
"type": "object",
"properties": {
"message": { "type": "string" },
"env_var": { "type": "string" }
},
"required": ["message"],
"additionalProperties": false
}))
.expect("echo tool schema should deserialize");
let mut tool = Tool::new(
Cow::Borrowed("echo"),
Cow::Borrowed("Echo back the provided message and include environment data."),
Arc::new(schema),
);
#[expect(clippy::expect_used)]
let output_schema: JsonObject = serde_json::from_value(json!({
"type": "object",
"properties": {
"echo": { "type": "string" },
"env": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
]
}
},
"required": ["echo", "env"],
"additionalProperties": false
}))
.expect("echo tool output schema should deserialize");
tool.output_schema = Some(Arc::new(output_schema));
tool.annotations = Some(ToolAnnotations::new().read_only(true));
tool
}
fn memo_resource() -> Resource {
Resource::new(MEMO_URI, "example-note")
.with_title("Example Note")
.with_description("A sample MCP resource exposed for integration tests.")
.with_mime_type("text/plain")
}
fn memo_template() -> ResourceTemplate {
ResourceTemplate::new("memo://codex/{slug}", "codex-memo")
.with_title("Codex Memo")
.with_description("Template for memo://codex/{slug} resources used in tests.")
.with_mime_type("text/plain")
}
fn memo_text() -> &'static str {
MEMO_CONTENT
}
}
fn parse_bind_addr() -> Result<SocketAddr, Box<dyn std::error::Error>> {
let default_addr = "127.0.0.1:3920";
let bind_addr = std::env::var("MCP_STREAMABLE_HTTP_BIND_ADDR")
.or_else(|_| std::env::var("BIND_ADDR"))
.unwrap_or_else(|_| default_addr.to_string());
Ok(bind_addr.parse()?)
}
async fn require_bearer(
State(expected): State<Arc<String>>,
request: Request<Body>,
next: Next,
) -> Result<Response, StatusCode> {
if request.uri().path().contains("/.well-known/") || request.uri().path() == "/oauth/token" {
return Ok(next.run(request).await);
}
if request
.headers()
.get(AUTHORIZATION)
.is_some_and(|value| value.as_bytes() == expected.as_bytes())
{
Ok(next.run(request).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
async fn require_gateway_bearer(
State(expected): State<Arc<String>>,
request: Request<Body>,
next: Next,
) -> Result<Response, StatusCode> {
if !request.uri().path().starts_with("/mcp") {
return Ok(next.run(request).await);
}
if request
.headers()
.get("proxy-authorization")
.is_some_and(|value| value.as_bytes() == expected.as_bytes())
{
Ok(next.run(request).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
async fn arm_session_post_failure(
State(state): State<PostFailureState>,
Json(request): Json<ArmSessionPostFailureRequest>,
) -> Result<StatusCode, StatusCode> {
arm_post_failure(state, request, ArmedFailureTarget::Session).await
}
async fn arm_initialize_post_failure(
State(state): State<PostFailureState>,
Json(request): Json<ArmSessionPostFailureRequest>,
) -> Result<StatusCode, StatusCode> {
arm_post_failure(state, request, ArmedFailureTarget::Initialize).await
}
async fn arm_initialized_notification_post_failure(
State(state): State<PostFailureState>,
Json(request): Json<ArmSessionPostFailureRequest>,
) -> Result<StatusCode, StatusCode> {
arm_post_failure(state, request, ArmedFailureTarget::InitializedNotification).await
}
async fn arm_post_failure(
state: PostFailureState,
request: ArmSessionPostFailureRequest,
target: ArmedFailureTarget,
) -> Result<StatusCode, StatusCode> {
let status = StatusCode::from_u16(request.status).map_err(|_| StatusCode::BAD_REQUEST)?;
let www_authenticate_headers = request
.www_authenticate_headers
.into_iter()
.map(|value| HeaderValue::from_str(&value).map_err(|_| StatusCode::BAD_REQUEST))
.collect::<Result<Vec<_>, _>>()?;
let content_type = request
.content_type
.map(|value| HeaderValue::from_str(&value).map_err(|_| StatusCode::BAD_REQUEST))
.transpose()?;
let armed_failure = if request.remaining == 0 {
None
} else {
Some(ArmedFailure {
target,
status,
remaining: request.remaining,
www_authenticate_headers,
content_type,
body: request.body,
})
};
*state.armed_failure.lock().await = armed_failure;
Ok(StatusCode::NO_CONTENT)
}
async fn fail_mcp_post_when_armed(
State(state): State<PostFailureState>,
request: Request<Body>,
next: Next,
) -> Response {
if request.uri().path() != "/mcp" || request.method() != Method::POST {
return next.run(request).await;
}
let (parts, body) = request.into_parts();
let body_bytes = match to_bytes(body, MAX_MCP_POST_BODY_BYTES).await {
Ok(body_bytes) => body_bytes,
Err(_) => {
let mut response = Response::new(Body::from("failed to read request body"));
*response.status_mut() = StatusCode::BAD_REQUEST;
return response;
}
};
let has_session_id = parts.headers.contains_key(MCP_SESSION_ID_HEADER);
let mcp_method = request_mcp_method(&body_bytes);
{
let mut armed_failure = state.armed_failure.lock().await;
if let Some(failure) = armed_failure.as_mut()
&& failure.remaining > 0
&& match failure.target {
ArmedFailureTarget::Initialize => !has_session_id,
ArmedFailureTarget::InitializedNotification => {
has_session_id && mcp_method.as_deref() == Some("notifications/initialized")
}
ArmedFailureTarget::Session => {
has_session_id && mcp_method.as_deref() != Some("notifications/initialized")
}
}
{
failure.remaining -= 1;
let status = failure.status;
let www_authenticate_headers = failure.www_authenticate_headers.clone();
let content_type = failure.content_type.clone();
let body = failure
.body
.clone()
.unwrap_or_else(|| format!("forced session failure with status {status}"));
if failure.remaining == 0 {
*armed_failure = None;
}
let mut response = Response::new(Body::from(body));
*response.status_mut() = status;
if let Some(content_type) = content_type {
response.headers_mut().insert(CONTENT_TYPE, content_type);
}
for www_authenticate_header in www_authenticate_headers {
response
.headers_mut()
.append(WWW_AUTHENTICATE, www_authenticate_header);
}
return response;
}
}
next.run(Request::from_parts(parts, Body::from(body_bytes)))
.await
}
fn request_mcp_method(body: &[u8]) -> Option<String> {
serde_json::from_slice::<Value>(body)
.ok()?
.get("method")?
.as_str()
.map(ToString::to_string)
}

View File

@@ -0,0 +1,149 @@
//! Bounded, compatibility-aware transport for modern locally spawned MCP servers.
use std::future::Future;
use std::io;
use std::sync::Arc;
use memchr::memchr;
use rmcp::service::RoleClient;
use rmcp::service::RxJsonRpcMessage;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::Transport;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::sync::Mutex;
use tracing::debug;
use tracing::warn;
use crate::local_stdio_io::Stdin;
use crate::local_stdio_io::Stdout;
/// Match the existing executor stdio transport and the production MCP limit.
pub(crate) const MAX_MCP_STDIO_LINE_BYTES: usize = 8 * 1024 * 1024;
pub(super) struct BoundedStdioTransport {
stdin: Arc<Mutex<Option<Stdin>>>,
stdout: BufReader<Stdout>,
pending_line: Vec<u8>,
program_name: String,
}
impl BoundedStdioTransport {
pub(super) fn new(stdin: Stdin, stdout: Stdout, program_name: String) -> Self {
Self {
stdin: Arc::new(Mutex::new(Some(stdin))),
stdout: BufReader::new(stdout),
pending_line: Vec::new(),
program_name,
}
}
/// Pass both a partial line and buffered read-ahead to the SDK's legacy codec.
pub(super) fn into_legacy_pipes(
self,
) -> io::Result<(Box<dyn AsyncRead + Send + Unpin>, Stdin)> {
let stdin = self
.stdin
.try_lock()
.map_err(io::Error::other)?
.take()
.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "MCP stdin closed"))?;
let stdout = io::Cursor::new(self.pending_line).chain(self.stdout);
Ok((Box::new(stdout), stdin))
}
async fn receive_message(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
loop {
let bytes = match self.stdout.fill_buf().await {
Ok(bytes) => bytes,
Err(error) => {
warn!(
"Failed to read MCP server stdout ({}): {error}",
self.program_name
);
return None;
}
};
if bytes.is_empty() {
if self.pending_line.is_empty() {
return None;
}
return self.decode_pending_message();
}
let newline = memchr(b'\n', bytes);
let content_len = newline.unwrap_or(bytes.len());
if content_len > MAX_MCP_STDIO_LINE_BYTES.saturating_sub(self.pending_line.len()) {
warn!(
"MCP stdio line exceeds {MAX_MCP_STDIO_LINE_BYTES} bytes ({}); closing transport",
self.program_name
);
self.pending_line.clear();
return None;
}
self.pending_line.extend_from_slice(&bytes[..content_len]);
let consumed = content_len + usize::from(newline.is_some());
self.stdout.consume(consumed);
if newline.is_some()
&& let Some(message) = self.decode_pending_message()
{
return Some(message);
}
}
}
fn decode_pending_message(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
let line = std::mem::take(&mut self.pending_line);
let line = line.strip_suffix(b"\r").unwrap_or(&line);
match serde_json::from_slice(line) {
Ok(message) => Some(message),
Err(error) => {
debug!(
"Failed to parse local MCP server message ({}): {error}",
self.program_name
);
None
}
}
}
}
impl Transport<RoleClient> for BoundedStdioTransport {
type Error = io::Error;
#[expect(
clippy::await_holding_invalid_type,
reason = "complete JSON-RPC frames must hold the stdin lock across writes"
)]
fn send(
&mut self,
item: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
let stdin = Arc::clone(&self.stdin);
async move {
let mut message = serde_json::to_vec(&item).map_err(io::Error::other)?;
message.push(b'\n');
let mut guard = stdin.lock().await;
let stdin = guard
.as_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "MCP stdin closed"))?;
stdin.write_all(&message).await?;
stdin.flush().await
}
}
fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<RoleClient>>> + Send {
self.receive_message()
}
async fn close(&mut self) -> Result<(), Self::Error> {
self.stdin.lock().await.take();
Ok(())
}
}

View File

@@ -0,0 +1,720 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use codex_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use rmcp::RoleClient;
use rmcp::model::ClientConfig;
use rmcp::model::ClientResult;
use rmcp::model::CustomRequest;
use rmcp::model::CustomResult;
use rmcp::model::ElicitResult;
use rmcp::model::ElicitationAction;
use rmcp::model::MetaObject;
use rmcp::model::ProtocolVersion;
use rmcp::model::RequestId;
use rmcp::model::RequestMetaObject;
use rmcp::model::RequestParamsMeta;
use rmcp::model::ServerNotification;
use rmcp::model::ServerRequest;
use rmcp::service::NotificationContext;
use rmcp::service::RequestContext;
use rmcp::service::Service;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Map;
use serde_json::Value;
use tokio::sync::oneshot;
use crate::logging_client_handler::LoggingClientHandler;
use crate::rmcp_client::Elicitation;
use crate::rmcp_client::ElicitationPauseState;
use crate::rmcp_client::ElicitationResponse;
use crate::rmcp_client::SendElicitation;
const MCP_PROGRESS_TOKEN_META_KEY: &str = "progressToken";
const MCP_ELICITATION_CREATE_METHOD: &str = "elicitation/create";
const OPENAI_FORM_METHOD: &str = "openai/form";
const OPENAI_ELICITATION_METHOD: &str = "openai/elicitation/create";
#[derive(Deserialize)]
#[serde(tag = "mode")]
enum OpenAiElicitationRequestParams {
#[serde(rename = "form")]
Form(OpenAiFormRequestParams),
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpenAiFormRequestParams {
#[serde(rename = "_meta")]
meta: Option<Value>,
message: String,
requested_schema: Value,
}
#[derive(Clone)]
pub(crate) struct ElicitationClientService {
handler: LoggingClientHandler,
supports_openai_form: bool,
supports_openai_elicitation_form: bool,
supports_user_verification: bool,
send_elicitation: Arc<SendElicitation>,
pause_state: ElicitationPauseState,
pending_verifications: Arc<Mutex<VerificationCancellations>>,
}
// A notification handler can run before its request handler. Never evict an early
// cancellation: after saturation, cancel new elicitations for this connection.
const MAX_EARLY_CANCELLATIONS: usize = 1024;
#[derive(Default)]
struct VerificationCancellations {
pending: HashMap<RequestId, oneshot::Sender<()>>,
early: HashSet<RequestId>,
saturated: bool,
}
struct PendingVerification {
request_id: RequestId,
cancellations: Arc<Mutex<VerificationCancellations>>,
}
impl Drop for PendingVerification {
fn drop(&mut self) {
self.cancellations
.lock()
.unwrap_or_else(PoisonError::into_inner)
.pending
.remove(&self.request_id);
}
}
impl ElicitationClientService {
/// Retains protocol validation and cancellation dispatch while isolating the caller's inputs.
pub(crate) fn for_request(
&self,
send_elicitation: Arc<SendElicitation>,
pause_state: ElicitationPauseState,
) -> Self {
Self {
send_elicitation,
pause_state,
..self.clone()
}
}
pub(crate) fn new(
client_info: ClientConfig,
send_elicitation: SendElicitation,
pause_state: ElicitationPauseState,
) -> Self {
let supports_openai_form = client_info
.capabilities
.extensions
.as_ref()
.is_some_and(|extensions| extensions.contains_key(OPENAI_FORM_METHOD));
let supports_openai_elicitation_form = client_info
.capabilities
.extensions
.as_ref()
.and_then(|extensions| extensions.get(OPENAI_ELICITATION_EXTENSION_ID))
.and_then(|settings| settings.get("form"))
.is_some_and(Value::is_object);
let send_elicitation = Arc::new(send_elicitation);
let supports_user_verification = client_info
.capabilities
.extensions
.as_ref()
.and_then(|extensions| extensions.get(OPENAI_ELICITATION_EXTENSION_ID))
.and_then(|settings| settings.get("userVerification"))
.is_some_and(Value::is_object);
Self {
handler: LoggingClientHandler::new(
client_info,
clone_send_elicitation(Arc::clone(&send_elicitation)),
),
supports_openai_form,
supports_openai_elicitation_form,
supports_user_verification,
send_elicitation,
pause_state,
pending_verifications: Arc::default(),
}
}
async fn create_elicitation(
&self,
request: Elicitation,
context: RequestContext<RoleClient>,
) -> Result<ElicitationResponse, rmcp::ErrorData> {
let RequestContext { id, meta, ct, .. } = context;
let request = restore_context_meta(request, meta);
let user_verification = matches!(&request, Elicitation::UserVerification { .. });
let (cancel_tx, cancel_rx) = oneshot::channel();
let _pending = {
let mut cancellations = self
.pending_verifications
.lock()
.unwrap_or_else(PoisonError::into_inner);
if cancellations.saturated || cancellations.early.remove(&id) {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: user_verification.then(|| {
if cancellations.saturated {
crate::UserVerificationReason::ApprovalUnavailable
} else {
crate::UserVerificationReason::Interrupted
}
.into_meta()
}),
});
}
cancellations.pending.insert(id.clone(), cancel_tx);
PendingVerification {
request_id: id.clone(),
cancellations: Arc::clone(&self.pending_verifications),
}
};
let _pause = self.pause_state.enter();
let response = tokio::select! {
biased;
_ = ct.cancelled() => {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: user_verification.then(|| crate::UserVerificationReason::Interrupted.into_meta()),
});
}
_ = cancel_rx => {
return Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: user_verification.then(|| crate::UserVerificationReason::Interrupted.into_meta()),
});
}
response = (self.send_elicitation)(id, request) => response,
}
.map_err(|err| rmcp::ErrorData::internal_error(err.to_string(), None))?;
Ok(if user_verification {
crate::user_verification::validate_response(response)
} else {
response
})
}
}
fn clone_send_elicitation(send_elicitation: Arc<SendElicitation>) -> SendElicitation {
Box::new(move |request_id, request| send_elicitation(request_id, request))
}
impl Service<RoleClient> for ElicitationClientService {
async fn handle_request(
&self,
request: ServerRequest,
context: RequestContext<RoleClient>,
) -> Result<ClientResult, rmcp::ErrorData> {
match request {
ServerRequest::ElicitRequest(request) => {
let modern_session = context
.peer
.peer_info()
.is_some_and(|info| info.protocol_version >= ProtocolVersion::V_2026_07_28);
let response = self
.create_elicitation(Elicitation::Mcp(request.params), context)
.await?;
if modern_session {
Ok(ClientResult::ElicitResult(typed_elicitation_result(
response,
)?))
} else {
Ok(ClientResult::CustomResult(elicitation_response_result(
response,
)?))
}
}
ServerRequest::CustomRequest(request)
if request.method == MCP_ELICITATION_CREATE_METHOD =>
{
let modern_session = context
.peer
.peer_info()
.is_some_and(|info| info.protocol_version >= ProtocolVersion::V_2026_07_28);
let response = self
.create_elicitation(custom_mcp_elicitation(request)?, context)
.await?;
if modern_session {
Ok(ClientResult::ElicitResult(typed_elicitation_result(
response,
)?))
} else {
Ok(ClientResult::CustomResult(elicitation_response_result(
response,
)?))
}
}
ServerRequest::CustomRequest(request)
if request.method == OPENAI_ELICITATION_METHOD
&& self.supports_user_verification
&& request
.params
.as_ref()
.and_then(|params| params.get("mode"))
.and_then(Value::as_str)
== Some(crate::user_verification::MODE) =>
{
let response = self
.create_elicitation(crate::user_verification::parse_request(request)?, context)
.await?;
Ok(ClientResult::CustomResult(elicitation_response_result(
response,
)?))
}
ServerRequest::CustomRequest(request)
if request.method == OPENAI_FORM_METHOD && self.supports_openai_form =>
{
let response = self
.create_elicitation(openai_form_elicitation(request)?, context)
.await?;
Ok(ClientResult::CustomResult(elicitation_response_result(
response,
)?))
}
ServerRequest::CustomRequest(request)
if request.method == OPENAI_ELICITATION_METHOD
&& self.supports_openai_elicitation_form =>
{
let response = self
.create_elicitation(openai_elicitation_form(request)?, context)
.await?;
Ok(ClientResult::CustomResult(elicitation_response_result(
response,
)?))
}
ServerRequest::CustomRequest(request)
if request.method == OPENAI_ELICITATION_METHOD
&& self.supports_user_verification =>
{
Err(rmcp::ErrorData::invalid_params(
"invalid elicitation mode",
/*data*/ None,
))
}
request => {
<LoggingClientHandler as Service<RoleClient>>::handle_request(
&self.handler,
request,
context,
)
.await
}
}
}
async fn handle_notification(
&self,
notification: ServerNotification,
context: NotificationContext<RoleClient>,
) -> Result<(), rmcp::ErrorData> {
if let ServerNotification::CancelledNotification(cancelled) = &notification
&& let Some(request_id) = cancelled.params.request_id.as_ref()
{
let mut cancellations = self
.pending_verifications
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(cancel) = cancellations.pending.remove(request_id) {
let _ = cancel.send(());
} else if !cancellations.saturated && !cancellations.early.contains(request_id) {
// Bound both the number and size of retained request IDs.
if cancellations.early.len() == MAX_EARLY_CANCELLATIONS
|| matches!(request_id, RequestId::String(id) if id.len() > 1024)
{
cancellations.saturated = true;
cancellations.early.clear();
} else {
cancellations.early.insert(request_id.clone());
}
}
}
<LoggingClientHandler as Service<RoleClient>>::handle_notification(
&self.handler,
notification,
context,
)
.await
}
fn get_info(&self) -> ClientConfig {
<LoggingClientHandler as Service<RoleClient>>::get_info(&self.handler)
}
}
fn custom_mcp_elicitation(request: CustomRequest) -> Result<Elicitation, rmcp::ErrorData> {
let raw_params = request
.params
.ok_or_else(|| rmcp::ErrorData::invalid_params("missing params", None))?;
let params: rmcp::model::ElicitRequestParams = serde_json::from_value(raw_params)
.map_err(|err| rmcp::ErrorData::invalid_params(err.to_string(), None))?;
Ok(Elicitation::Mcp(params))
}
fn openai_form_elicitation(request: CustomRequest) -> Result<Elicitation, rmcp::ErrorData> {
let params = request
.params_as::<OpenAiFormRequestParams>()
.map_err(|err| rmcp::ErrorData::invalid_params(err.to_string(), None))?
.ok_or_else(|| rmcp::ErrorData::invalid_params("missing params", None))?;
Ok(Elicitation::OpenAiForm {
meta: params.meta,
message: params.message,
requested_schema: params.requested_schema,
})
}
pub(crate) fn openai_elicitation_form(
request: CustomRequest,
) -> Result<Elicitation, rmcp::ErrorData> {
let params = request
.params_as::<OpenAiElicitationRequestParams>()
.map_err(|err| rmcp::ErrorData::invalid_params(err.to_string(), /*data*/ None))?
.ok_or_else(|| rmcp::ErrorData::invalid_params("missing params", /*data*/ None))?;
let OpenAiElicitationRequestParams::Form(params) = params;
Ok(Elicitation::OpenAiElicitationForm {
meta: params.meta,
message: params.message,
requested_schema: params.requested_schema,
})
}
fn restore_context_meta(
mut request: Elicitation,
mut context_meta: RequestMetaObject,
) -> Elicitation {
// RMCP lifts JSON-RPC `_meta` into RequestContext before invoking services.
context_meta.remove(MCP_PROGRESS_TOKEN_META_KEY);
if context_meta.is_empty() {
return request;
}
match &mut request {
Elicitation::Mcp(request) => request
.meta_mut()
.get_or_insert_with(RequestMetaObject::new)
.extend(context_meta),
Elicitation::OpenAiForm { meta, .. }
| Elicitation::OpenAiElicitationForm { meta, .. }
| Elicitation::UserVerification { meta, .. } => {
let meta = meta
.get_or_insert_with(|| Value::Object(Map::new()))
.as_object_mut();
if let Some(meta) = meta {
meta.extend(context_meta.0.0);
}
}
}
request
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CreateElicitationResultWithMeta {
action: ElicitationAction,
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<Value>,
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
meta: Option<Value>,
}
fn elicitation_response_result(
response: ElicitationResponse,
) -> Result<CustomResult, rmcp::ErrorData> {
let ElicitationResponse {
action,
content,
meta,
} = response;
let result = CreateElicitationResultWithMeta {
action,
content,
meta,
};
serde_json::to_value(result)
.map(CustomResult)
.map_err(|err| rmcp::ErrorData::internal_error(err.to_string(), None))
}
fn typed_elicitation_result(
response: ElicitationResponse,
) -> Result<ElicitResult, rmcp::ErrorData> {
let ElicitationResponse {
action,
content,
meta,
} = response;
let mut result = ElicitResult::new(action);
result.content = content;
result.meta = match meta {
None => None,
Some(Value::Object(meta)) => Some(MetaObject::from(meta)),
Some(meta) => {
return Err(rmcp::ErrorData::invalid_params(
format!("MCP elicitation response _meta must be an object, got {meta}"),
None,
));
}
};
Ok(result)
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use rmcp::model::BooleanSchema;
use rmcp::model::ElicitRequestParams;
use rmcp::model::ElicitationSchema;
use rmcp::model::PrimitiveSchemaDefinition;
use serde_json::Value;
use serde_json::json;
use super::*;
#[test]
fn restore_context_meta_adds_elicitation_meta_and_removes_progress_token() {
let request = restore_context_meta(
Elicitation::Mcp(form_request(/*meta*/ None)),
meta(json!({
"progressToken": "progress-token",
"persist": ["session", "always"],
})),
);
assert_eq!(
request,
Elicitation::Mcp(form_request(Some(meta(json!({
"persist": ["session", "always"],
})))))
);
}
#[test]
fn legacy_sep1034_elicitation_without_mode_preserves_schema_defaults() {
let request = json!({
"method": "elicitation/create",
"params": {
"message": "Confirm the default values",
"requestedSchema": {
"type": "object",
"properties": {
"name": {"type": "string", "default": "John Doe"},
"age": {"type": "integer", "default": 30},
"score": {"type": "number", "default": 95.5},
"status": {
"type": "string",
"enum": ["active", "inactive"],
"default": "active",
},
"verified": {"type": "boolean", "default": true},
},
"required": [],
},
},
});
let request = serde_json::from_value::<ServerRequest>(request)
.expect("legacy form elicitations must deserialize without a mode");
let ServerRequest::ElicitRequest(request) = request else {
panic!("legacy elicitation/create must dispatch to the typed handler");
};
let ElicitRequestParams::FormElicitationParams {
requested_schema, ..
} = request.params
else {
panic!("an omitted legacy elicitation mode must default to form");
};
assert_eq!(
serde_json::to_value(requested_schema)
.expect("legacy schema defaults must remain serializable"),
json!({
"type": "object",
"properties": {
"name": {"type": "string", "default": "John Doe"},
"age": {"type": "integer", "default": 30},
"score": {"type": "number", "default": 95.5},
"status": {
"type": "string",
"enum": ["active", "inactive"],
"default": "active",
},
"verified": {"type": "boolean", "default": true},
},
"required": [],
})
);
}
#[test]
fn parses_legacy_custom_elicitation_without_mode() {
let request = CustomRequest::new(
MCP_ELICITATION_CREATE_METHOD,
Some(json!({
"message": "Confirm?",
"requestedSchema": {
"type": "object",
"properties": {
"confirmed": {"type": "boolean"},
"age": {"type": "integer", "minimum": 1, "maximum": 99, "default": 30},
},
"required": ["confirmed"],
},
})),
);
let Elicitation::Mcp(rmcp::model::ElicitRequestParams::FormElicitationParams {
requested_schema,
..
}) = custom_mcp_elicitation(request)
.expect("legacy custom elicitation parameters must deserialize")
else {
panic!("omitted legacy elicitation mode must default to form");
};
assert_eq!(
serde_json::to_value(requested_schema).expect("schema must serialize"),
json!({
"type": "object",
"properties": {
"confirmed": {"type": "boolean"},
"age": {"type": "integer", "minimum": 1, "maximum": 99, "default": 30},
},
"required": ["confirmed"],
})
);
}
#[test]
fn parses_openai_form_custom_requests() {
let elicitation = openai_form_elicitation(CustomRequest::new(
OPENAI_FORM_METHOD,
Some(json!({
"message": "Select a template",
"requestedSchema": {
"type": "object",
"properties": {
"template": {
"type": "openai/imagePicker",
"items": [{
"id": "monthly-review",
"title": "Monthly review",
"image": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4="
}]
}
}
}
})),
))
.expect("valid openai/form request");
assert_eq!(
elicitation,
Elicitation::OpenAiForm {
meta: None,
message: "Select a template".to_string(),
requested_schema: json!({
"type": "object",
"properties": {
"template": {
"type": "openai/imagePicker",
"items": [{
"id": "monthly-review",
"title": "Monthly review",
"image": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4="
}]
}
}
}),
}
);
}
#[test]
fn elicitation_response_result_serializes_response_meta() {
let result = rmcp::model::ClientResult::CustomResult(
elicitation_response_result(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({ "confirmed": true })),
meta: Some(json!({ "persist": "always" })),
})
.expect("elicitation response should serialize"),
);
assert_eq!(
serde_json::to_value(result).expect("client result should serialize"),
json!({
"action": "accept",
"content": { "confirmed": true },
"_meta": { "persist": "always" },
})
);
}
#[test]
fn typed_elicitation_result_preserves_response_meta() {
let result = typed_elicitation_result(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({ "confirmed": true })),
meta: Some(json!({ "persist": "always" })),
})
.expect("modern elicitation response should serialize");
assert_eq!(
serde_json::to_value(result).expect("typed elicitation result should serialize"),
json!({
"action": "accept",
"content": { "confirmed": true },
"_meta": { "persist": "always" },
})
);
}
#[test]
fn typed_elicitation_result_rejects_non_object_meta() {
let error = typed_elicitation_result(ElicitationResponse {
action: ElicitationAction::Accept,
content: None,
meta: Some(json!(["invalid"])),
})
.expect_err("modern elicitation metadata must be an object");
assert_eq!(error.code, rmcp::model::ErrorCode::INVALID_PARAMS);
}
fn form_request(meta: Option<RequestMetaObject>) -> ElicitRequestParams {
ElicitRequestParams::FormElicitationParams {
meta,
message: "Confirm?".to_string(),
requested_schema: ElicitationSchema::builder()
.required_property(
"confirmed",
PrimitiveSchemaDefinition::Boolean(BooleanSchema::new()),
)
.build()
.expect("schema should build"),
}
}
fn meta(value: Value) -> RequestMetaObject {
let Value::Object(map) = value else {
panic!("meta must be an object");
};
RequestMetaObject::from(map)
}
}
#[cfg(test)]
#[path = "user_verification_dispatch_tests.rs"]
mod user_verification_dispatch_tests;

View File

@@ -0,0 +1,235 @@
//! 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_config::McpEmaTokenEndpointAuthMethod;
use codex_exec_server::HttpClient;
use futures::future::BoxFuture;
use http::StatusCode;
use serde::Deserialize;
use serde_json::Value;
use url::Url;
use crate::EmaCredentialLease;
use crate::EmaErrorDetail;
use crate::ema_auth_policy::advertised_capability;
use crate::ema_auth_policy::resolve_ema_client_auth;
use crate::ema_auth_policy::validate_ema_auth_resource;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
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;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
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, L = EmaCredentialLease> {
pub server_url: &'a str,
pub resource: Option<&'a str>,
pub scopes: &'a [String],
pub mcp_client_id: Option<&'a str>,
pub mcp_client_secret: Option<&'a str>,
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
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<L>>>,
pub idp_http_client: Arc<dyn HttpClient>,
pub resource_http_client: Arc<dyn HttpClient>,
}
impl<'a, L> From<&EmaAuthTokenExchangeRequest<'a, L>> for EmaDiscoveryRequest<'a> {
fn from(request: &EmaAuthTokenExchangeRequest<'a, L>) -> 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<L: Send, R: Send>(
request: EmaAuthTokenExchangeRequest<'_, L>,
finish_idp: impl FnOnce(L) -> R + Send,
) -> Result<(EmaAccessToken, R)> {
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"
)
})?;
if request.mcp_client_secret.is_some()
&& request
.expected_authorization_server_issuer
.is_none_or(|issuer| issuer.trim().is_empty())
{
bail!("confidential ema_auth requires a configured authorization server issuer");
}
let (metadata, resource, resource_client_authentication) = discover_ema_authorization_metadata(
EmaDiscoveryRequest::from(&request),
request.mcp_client_secret,
request.token_endpoint_auth_method,
)
.await
.context(EmaErrorDetail::new(
"enterprise MCP authorization server discovery failed",
))?;
let issuer = metadata
.issuer
.as_deref()
.ok_or_else(|| anyhow!("MCP authorization metadata is missing an issuer"))?;
let EmaIdpIdentity {
token_endpoint,
refresh_token,
credentials,
client_authentication: idp_client_authentication,
} = request.idp_identity.await?;
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,
idp_client_authentication,
resource_client_authentication,
refresh_token,
idp_http_client: request.idp_http_client,
resource_http_client: request.resource_http_client,
},
credentials,
finish_idp,
)
.await
}
async fn discover_ema_authorization_metadata(
request: EmaDiscoveryRequest<'_>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<(EmaAuthorizationMetadata, String, EmaClientAuthentication)> {
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!(EmaErrorDetail::new(
"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 resolve_ema_client_auth(
metadata
.additional_fields
.get("token_endpoint_auth_methods_supported"),
client_secret,
token_endpoint_auth_method,
"MCP authorization server",
) {
Ok(authentication) => return Ok((metadata, resource, authentication)),
Err(error) if expected_issuer.is_some() => return Err(error),
Err(_) => break,
}
}
}
bail!(
"enterprise MCP discovery found no authorization server supporting the configured client authentication and ID-JAG JWT bearer grant"
)
}
#[cfg(test)]
#[path = "ema_auth_tests.rs"]
mod tests;

View File

@@ -0,0 +1,364 @@
//! Credential-destination policy for enterprise MCP OAuth.
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use rmcp::transport::auth::enterprise::EmaError;
use rmcp::transport::auth::enterprise::EmaExchangeStage;
use serde_json::Value;
use url::Host;
use url::Url;
/// A sanitized enterprise-auth failure that callers may handle without parsing text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum EmaAuthFailure {
#[error("invalid_grant")]
InvalidGrant { grant_source: EmaInvalidGrantSource },
#[error("insufficient_user_authentication")]
InsufficientUserAuthentication { grant_source: EmaInvalidGrantSource },
#[error("enterprise identity rejected the OAuth client")]
IdentityClientRejected,
#[error("enterprise identity requires authentication")]
ReauthenticationRequired,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmaInvalidGrantSource {
EnterpriseIdentity,
ResourceAuthorization,
}
/// The credential source selected for enterprise token acquisition or validation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EmaCredentialKind {
Account,
Keyring,
}
/// A diagnostic containing only static local text or sanitized SDK exchange fields.
/// Never retains an arbitrary error's display text, provider response, or source chain.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EmaErrorDetail {
message: &'static str,
stage: Option<EmaExchangeStage>,
status: Option<u16>,
}
impl EmaErrorDetail {
pub fn new(message: &'static str) -> Self {
Self {
message,
stage: None,
status: None,
}
}
pub fn from_error(error: &anyhow::Error) -> Self {
// SDK diagnostics are already sanitized, including allowlisted OAuth codes.
// Prefer them to an outer operation label when both are available.
if let Some(error) = error.downcast_ref::<EmaError>() {
let (stage, status, message) = match error {
EmaError::InvalidRequest(message) => (None, None, *message),
EmaError::InvalidResponse { stage, message } => (Some(*stage), None, *message),
EmaError::RequestFailed(stage) => (Some(*stage), None, "request failed"),
EmaError::InvalidGrant(stage) => (Some(*stage), None, "invalid_grant"),
EmaError::InsufficientUserAuthentication(stage) => {
(Some(*stage), None, "insufficient_user_authentication")
}
EmaError::OAuthRejected {
stage,
status,
code,
} => (Some(*stage), Some(*status), *code),
_ => (None, None, "enterprise MCP token exchange failed"),
};
return Self {
message,
stage,
status,
};
}
error
.chain()
.filter_map(|cause| cause.downcast_ref::<Self>())
.last()
.copied()
.or_else(|| error.downcast_ref::<Self>().copied())
.unwrap_or_else(|| Self::new("enterprise MCP token exchange failed"))
}
}
impl std::fmt::Display for EmaErrorDetail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(stage) = self.stage {
write!(f, "{stage:?}: ")?;
}
if let Some(status) = self.status {
write!(f, "HTTP {status}: ")?;
}
f.write_str(self.message)
}
}
impl std::error::Error for EmaErrorDetail {}
/// Carries a credential kind and sanitized failure to transport, without raw error chains.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EmaTokenSourceError {
AuthFailure {
credential: EmaCredentialKind,
failure: EmaAuthFailure,
},
Unexpected {
credential: EmaCredentialKind,
detail: EmaErrorDetail,
},
}
impl EmaTokenSourceError {
pub fn new(credential: EmaCredentialKind, failure: EmaAuthFailure) -> Self {
Self::AuthFailure {
credential,
failure,
}
}
pub fn unexpected(credential: EmaCredentialKind) -> Self {
Self::Unexpected {
credential,
detail: EmaErrorDetail::new("enterprise MCP token exchange failed"),
}
}
fn credential(self) -> EmaCredentialKind {
match self {
Self::AuthFailure { credential, .. } | Self::Unexpected { credential, .. } => {
credential
}
}
}
fn failure(self) -> Option<EmaAuthFailure> {
match self {
Self::AuthFailure { failure, .. } => Some(failure),
Self::Unexpected { .. } => None,
}
}
pub fn is_authentication_required(&self) -> bool {
match (self.credential(), self.failure()) {
(
_,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::ReauthenticationRequired,
),
)
| (EmaCredentialKind::Account, Some(EmaAuthFailure::IdentityClientRejected)) => true,
(
_,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
},
)
| None,
)
| (EmaCredentialKind::Keyring, Some(EmaAuthFailure::IdentityClientRejected)) => false,
}
}
}
impl std::fmt::Display for EmaTokenSourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Self::Unexpected { detail, .. } = self {
return std::fmt::Display::fmt(detail, f);
}
let message = match (self.credential(), self.failure()) {
(
_,
Some(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}),
) => {
"The MCP authorization server requires additional user authentication; contact your administrator"
}
(EmaCredentialKind::Keyring, Some(EmaAuthFailure::IdentityClientRejected)) => {
"The enterprise IdP rejected the configured MCP OAuth client; contact your administrator"
}
(
EmaCredentialKind::Account,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::IdentityClientRejected,
),
) => "Complete enterprise sign-in for this MCP server",
(EmaCredentialKind::Account, Some(EmaAuthFailure::ReauthenticationRequired)) => {
"Sign in to your Codex account to restore enterprise MCP access"
}
(
EmaCredentialKind::Keyring,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::ReauthenticationRequired,
),
) => "Complete enterprise sign-in to restore MCP access",
(
_,
Some(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}),
) => "The MCP authorization server rejected the enterprise grant: invalid_grant",
(_, None) => "enterprise MCP token exchange failed",
};
f.write_str(message)
}
}
impl std::error::Error for EmaTokenSourceError {}
pub(crate) fn ema_reauthentication_required(message: &'static str) -> anyhow::Error {
anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired).context(message)
}
pub(crate) fn resolve_ema_client_auth(
advertised_methods: Option<&Value>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
issuer_description: &str,
) -> Result<rmcp::transport::auth::enterprise::EmaClientAuthentication> {
use oauth2::ClientSecret;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
if let Some(secret) = client_secret {
if secret.trim().is_empty() {
bail!("{issuer_description} client secret must not be empty");
}
let registered_method = token_endpoint_auth_method.unwrap_or_default();
// RFC 8414 defaults absent server capabilities to Basic. Capabilities
// validate the registration; they do not select its authentication method.
let supported = match advertised_methods {
None => registered_method == McpEmaTokenEndpointAuthMethod::ClientSecretBasic,
Some(methods) => methods.as_array().is_some_and(|methods| {
methods
.iter()
.any(|method| method.as_str() == Some(registered_method.as_str()))
}),
};
if !supported {
bail!(
"{issuer_description} does not support the registered token endpoint authentication method"
);
}
let secret = ClientSecret::new(secret.to_owned());
return Ok(match registered_method {
McpEmaTokenEndpointAuthMethod::ClientSecretBasic => {
EmaClientAuthentication::ClientSecretBasic(secret)
}
McpEmaTokenEndpointAuthMethod::ClientSecretPost => {
EmaClientAuthentication::ClientSecretPost(secret)
}
});
}
if token_endpoint_auth_method.is_some() {
bail!("{issuer_description} token endpoint authentication method requires a client secret");
}
let advertised_methods = advertised_methods.ok_or_else(|| {
anyhow!(
"{issuer_description} does not explicitly advertise public-client token endpoint authentication"
)
})?;
let methods = advertised_methods.as_array().ok_or_else(|| {
anyhow!("{issuer_description} advertised malformed token endpoint authentication methods")
})?;
if !methods.iter().any(|method| method.as_str() == Some("none")) {
bail!("{issuer_description} does not support public-client token endpoint authentication");
}
Ok(EmaClientAuthentication::None)
}
pub(crate) fn validate_ema_oauth_endpoint(endpoint: &str, description: &str) -> Result<()> {
let url = Url::parse(endpoint).with_context(|| format!("{description} is not a valid URL"))?;
validate_credential_destination(&url, description)
}
fn validate_credential_destination(url: &Url, description: &str) -> Result<()> {
let loopback = match url.host() {
Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
Some(Host::Ipv4(address)) => address.is_loopback(),
Some(Host::Ipv6(address)) => address.is_loopback(),
None => false,
};
if url.scheme() != "https" && !(url.scheme() == "http" && loopback) {
bail!("{description} must use HTTPS or an HTTP loopback address");
}
if !url.username().is_empty() || url.password().is_some() || url.fragment().is_some() {
bail!("{description} contains disallowed credentials or a URL fragment");
}
Ok(())
}
pub(crate) fn advertised_capability(
value: Option<&Value>,
expected: &str,
description: &str,
) -> Result<Option<bool>> {
value
.map(|value| {
let values = value
.as_array()
.ok_or_else(|| anyhow!("{description} is malformed"))?;
Ok(values.iter().any(|value| value.as_str() == Some(expected)))
})
.transpose()
}
/// Resource indicators must describe the configured MCP origin, query and path.
pub fn validate_ema_auth_resource(server_url: &str, resource: Option<&str>) -> Result<()> {
let server = Url::parse(server_url).context("enterprise MCP server URL is invalid")?;
validate_credential_destination(&server, "enterprise MCP server URL")?;
let Some(resource) = resource.filter(|resource| !resource.trim().is_empty()) else {
return Ok(());
};
let resource = Url::parse(resource).context("enterprise MCP resource indicator is invalid")?;
validate_credential_destination(&resource, "enterprise MCP resource indicator")?;
if resource.origin() != server.origin() || resource.query() != server.query() {
bail!(
"enterprise MCP resource indicator must match the configured MCP server origin and query"
);
}
let resource_path = resource.path().trim_end_matches('/');
let server_path = server.path().trim_end_matches('/');
if server_path != resource_path
&& !server_path
.strip_prefix(resource_path)
.is_some_and(|suffix| suffix.starts_with('/'))
{
bail!("enterprise MCP resource indicator path must contain the configured MCP server path");
}
Ok(())
}
#[cfg(test)]
#[path = "ema_auth_policy_tests.rs"]
mod tests;

View File

@@ -0,0 +1,73 @@
use pretty_assertions::assert_eq;
use serde_json::json;
use super::*;
#[test]
fn resource_origin_query_and_path_are_bound() {
let server = "https://mcp.example/enterprise/tools?tenant=one";
for (resource, valid) in [
("https://mcp.example/enterprise?tenant=one", true),
("https://other.example/enterprise?tenant=one", false),
("https://mcp.example/enterprise-admin?tenant=one", false),
("https://mcp.example/enterprise?tenant=two", false),
("https://mcp.example/enterprise", false),
("http://localhost:4000/enterprise?tenant=one", false),
] {
assert_eq!(
validate_ema_auth_resource(server, Some(resource)).is_ok(),
valid,
"{resource}"
);
}
for (server, valid) in [
("https://mcp.example/mcp", true),
("http://localhost:4000/mcp", true),
("http://127.0.0.1:4000/mcp", true),
("http://mcp.example/mcp", false),
] {
assert_eq!(
validate_ema_auth_resource(server, /*resource*/ None).is_ok(),
valid,
"{server}"
);
}
}
#[test]
fn public_clients_require_an_explicitly_advertised_auth_method() {
for (advertised, valid) in [
(None, false),
(Some(json!(["none"])), true),
(Some(json!(["client_secret_basic", "none"])), true),
(Some(json!(["private_key_jwt"])), false),
(Some(json!("none")), false),
] {
assert_eq!(
resolve_ema_client_auth(
advertised.as_ref(),
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
"IdP"
)
.is_ok(),
valid
);
}
use McpEmaTokenEndpointAuthMethod::ClientSecretPost;
for (advertised, registered, valid) in [
(None, None, true),
(None, Some(ClientSecretPost), false),
(
Some(json!(["client_secret_basic"])),
Some(ClientSecretPost),
false,
),
(Some(json!(["client_secret_post"])), None, false),
] {
assert_eq!(
resolve_ema_client_auth(advertised.as_ref(), Some("secret"), registered, "IdP").is_ok(),
valid
);
}
}

View File

@@ -0,0 +1,483 @@
//! Bound metadata selection and HTTP confinement run before enterprise credential access.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_config::types::AuthKeyringBackendKind;
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::*;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaInvalidGrantSource;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::ResolvedOAuthCredentialStore;
use crate::oauth::StoredOAuthCredentialSnapshot;
use crate::oauth::StoredOAuthTokens;
use crate::oauth::test_support::TempCodexHome;
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 {
mcp_client_secret: None,
token_endpoint_auth_method: None,
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, std::convert::identity)
.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),
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
)
.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 = exchange_ema_auth_token(exchange, std::convert::identity)
.await
.err()
.context("cross-origin redirect must fail")?;
assert!(format!("{error:#}").contains("cross-origin redirect"));
assert_eq!(
EmaErrorDetail::from_error(&error).to_string(),
"enterprise MCP authorization server discovery failed"
);
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://credentials@issuer.example",
] {
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(())
}
#[tokio::test]
async fn rejected_grants_preserve_their_source_and_release_the_credential_lease() -> Result<()> {
let _home = TempCodexHome::new();
for failure_source in [
EmaInvalidGrantSource::EnterpriseIdentity,
EmaInvalidGrantSource::ResourceAuthorization,
] {
let server = MockServer::start().await;
let resource = format!("{}/mcp", server.uri());
let issuer = format!("{}/as", server.uri());
let idp = format!("{}/idp", server.uri());
let assertion = format!(
"{}.{}.{}",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256","typ":"oauth-id-jag+jwt"}"#),
URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"iss": idp, "aud": issuer,
"client_id": "resource-client", "sub": "user", "jti": "one", "iat": 0,
"exp": u64::MAX, "resource": resource}))?),
URL_SAFE_NO_PAD.encode(b"signature")
);
for (endpoint, status, response) in [
(
"/mcp",
200,
json!({"resource": resource, "authorization_servers": [issuer]}),
),
(
"/.well-known/oauth-authorization-server/as",
200,
json!({"issuer": issuer, "token_endpoint": format!("{issuer}/token"),
"grant_types_supported": [JWT_BEARER_GRANT_TYPE], "token_endpoint_auth_methods_supported": ["none"]}),
),
(
"/idp/token",
if failure_source == EmaInvalidGrantSource::EnterpriseIdentity {
400
} else {
200
},
if failure_source == EmaInvalidGrantSource::EnterpriseIdentity {
json!({"error": "invalid_grant"})
} else {
json!({"access_token": assertion, "token_type": "N_A", "issued_token_type": "urn:ietf:params:oauth:token-type:id-jag"})
},
),
("/as/token", 400, json!({"error": "invalid_grant"})),
] {
Mock::given(path(endpoint))
.respond_with(ResponseTemplate::new(status).set_body_json(response))
.mount(&server)
.await;
}
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": "ema-idp:revoked-test", "url": idp, "issuer": idp, "client_id": "enterprise-client",
"token_response": {"access_token": "unused", "token_type": "Bearer", "refresh_token": "old-grant"},
}))?;
let credentials = StoredOAuthCredentialSnapshot::new(tokens.clone(), store);
let mut exchange = request(&resource, Some(&issuer));
exchange.idp_issuer = &idp;
exchange.idp_identity = Box::pin(async {
Ok(EmaIdpIdentity {
client_authentication: EmaClientAuthentication::None,
token_endpoint: format!("{idp}/token"),
refresh_token: "old-grant".to_string(),
credentials: crate::EmaCredentialLease { credentials },
})
});
let error = exchange_ema_auth_token(exchange, std::convert::identity)
.await
.expect_err("invalid grant");
assert_eq!(
error.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::InvalidGrant {
grant_source: failure_source
})
);
let _exclusive = tokio::time::timeout(
std::time::Duration::from_secs(1),
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &idp),
)
.await
.expect("failed exchange must not retain the credential lock")?;
}
Ok(())
}

View File

@@ -0,0 +1,105 @@
//! Validate OIDC identity assertion bindings before storing enterprise credentials.
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Deserialize;
use serde::de::DeserializeOwned;
pub(crate) const ID_JAG_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:id-jag";
#[derive(Deserialize)]
struct JwtHeader {
alg: String,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum OAuthResource {
Single(String),
Multiple(Vec<String>),
}
fn signed_jwt<T: DeserializeOwned>(token: &str) -> Result<T> {
let mut parts = token.split('.');
let (Some(header), Some(payload), Some(signature), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
bail!("identity assertion is not a compact signed JWT");
};
if header.is_empty() || payload.is_empty() || signature.is_empty() {
bail!("identity assertion contains an empty JWT segment");
}
let header: JwtHeader = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(header)?)
.map_err(|_| anyhow!("invalid identity assertion JWT header"))?;
if header.alg.trim().is_empty() || header.alg.eq_ignore_ascii_case("none") {
bail!("identity assertion is unsigned");
}
let claims = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload)?)
.map_err(|_| anyhow!("invalid identity assertion JWT claims"))?;
Ok(claims)
}
#[derive(Deserialize)]
pub(crate) struct OidcClaims {
iss: String,
sub: String,
aud: OAuthResource,
azp: Option<String>,
exp: u64,
}
pub(crate) fn oidc_identity(
assertion: &str,
expected_issuer: &str,
expected_audience: &str,
) -> Result<OidcClaims> {
if expected_issuer.trim().is_empty() || expected_audience.trim().is_empty() {
bail!("OIDC identity assertion requires a non-empty expected issuer and client");
}
let claims: OidcClaims = signed_jwt(assertion)?;
if claims.iss != expected_issuer || claims.sub.trim().is_empty() {
bail!("OIDC identity assertion issuer or subject does not match the enterprise IdP");
}
let (audience_matches, multiple_audiences) = match &claims.aud {
OAuthResource::Single(value) => (value == expected_audience, false),
OAuthResource::Multiple(values) => (
values.iter().any(|value| value == expected_audience),
values.len() > 1,
),
};
if !audience_matches
|| claims
.azp
.as_deref()
.is_some_and(|party| party != expected_audience)
|| multiple_audiences && claims.azp.as_deref() != Some(expected_audience)
{
bail!("OIDC identity assertion audience or authorized party does not match the IdP client");
}
Ok(claims)
}
/// Unverified issuer claim used only to explain a legacy login migration.
/// Never use this hint to choose where a refresh token is sent.
pub(crate) fn oidc_issuer_hint(assertion: &str, expected_issuer: &str) -> bool {
signed_jwt::<OidcClaims>(assertion).is_ok_and(|claims| claims.iss == expected_issuer)
}
pub(crate) fn validate_oidc_identity_assertion(
assertion: &str,
expected_issuer: &str,
expected_audience: &str,
) -> Result<()> {
let claims = oidc_identity(assertion, expected_issuer, expected_audience)?;
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
if claims.exp <= now {
bail!("OIDC identity assertion is expired");
}
Ok(())
}

View File

@@ -0,0 +1,161 @@
//! Adapt the SDK enterprise exchange to Codex HTTP routing and credential lifecycle errors.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use codex_exec_server::HttpClient;
use oauth2::RefreshToken;
use rmcp::transport::auth::enterprise::EmaAuthorizationServer;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
use rmcp::transport::auth::enterprise::EmaError;
use rmcp::transport::auth::enterprise::EmaExchangeRequest;
use rmcp::transport::auth::enterprise::EmaExchangeStage;
use tokio::time::Instant;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaInvalidGrantSource;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::utils::build_default_headers;
pub(crate) const TOKEN_EXCHANGE_GRANT_TYPE: &str =
"urn:ietf:params:oauth:grant-type:token-exchange";
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.
#[derive(Clone, PartialEq, Eq)]
pub struct EmaAccessToken {
pub access_token: String,
pub expires_in: Option<Duration>,
/// Exchange completion time, before any asynchronous credential validation.
pub received_at: Instant,
}
impl std::fmt::Debug for EmaAccessToken {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("EmaAccessToken")
.field("access_token", &"[REDACTED]")
.field("expires_in", &self.expires_in)
.finish()
}
}
/// The caller supplies trusted authorization-server metadata and an IdP credential.
/// This primitive does not perform resource discovery or interactive login.
pub(crate) struct EmaIdJagExchangeRequest<'a> {
pub resource: &'a str,
pub scopes: &'a [String],
pub mcp_client_id: &'a str,
pub authorization_server_issuer: &'a str,
pub authorization_server_token_endpoint: &'a str,
pub idp_token_endpoint: &'a str,
pub idp_issuer: &'a str,
pub idp_client_id: &'a str,
pub idp_client_authentication: EmaClientAuthentication,
pub resource_client_authentication: EmaClientAuthentication,
pub refresh_token: String,
pub idp_http_client: Arc<dyn HttpClient>,
pub resource_http_client: Arc<dyn HttpClient>,
}
/// Exchanges an enterprise IdP credential for a resource-bound MCP bearer token.
pub(crate) async fn exchange_id_jag<L: Send, R: Send>(
request: EmaIdJagExchangeRequest<'_>,
credentials: L,
finish_idp: impl FnOnce(L) -> R + Send,
) -> Result<(EmaAccessToken, R)> {
let idp_http = OAuthHttpClientAdapter::new_with_redirect_mode(
request.idp_http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
request.idp_token_endpoint,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)?;
let resource_http = OAuthHttpClientAdapter::new_with_redirect_mode(
request.resource_http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
request.authorization_server_token_endpoint,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)?;
let refresh_token = RefreshToken::new(request.refresh_token);
// Discovery has already verified each registration's authentication method. The SDK owns
// token validation and the two exchanges; Codex retains routing and credential policy.
let assertion = EmaExchangeRequest::new(
EmaAuthorizationServer::new(
request.idp_issuer,
request.idp_token_endpoint,
request.idp_client_id,
)
.with_client_authentication(request.idp_client_authentication),
EmaAuthorizationServer::new(
request.authorization_server_issuer,
request.authorization_server_token_endpoint,
request.mcp_client_id,
)
.with_client_authentication(request.resource_client_authentication),
request.resource,
&refresh_token,
)
.with_scopes(request.scopes.iter().cloned())
.exchange_id_jag(&idp_http)
.await
.map_err(exchange_error)?;
drop(refresh_token);
// Only the IdP uses the refresh token. Release its lease before resource-AS I/O.
let receipt = finish_idp(credentials);
let token = assertion
.exchange(&resource_http)
.await
.map_err(exchange_error)?;
Ok((
EmaAccessToken {
access_token: token.access_token.secret().to_owned(),
expires_in: token.expires_in,
received_at: Instant::now(),
},
receipt,
))
}
fn exchange_error(error: EmaError) -> anyhow::Error {
let failure = match &error {
EmaError::InvalidGrant(EmaExchangeStage::IdentityProvider) => {
Some(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
})
}
EmaError::InvalidGrant(EmaExchangeStage::ResourceAuthorizationServer) => {
Some(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
})
}
EmaError::InsufficientUserAuthentication(EmaExchangeStage::IdentityProvider) => {
Some(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
})
}
EmaError::InsufficientUserAuthentication(EmaExchangeStage::ResourceAuthorizationServer) => {
Some(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
})
}
EmaError::OAuthRejected {
stage: EmaExchangeStage::IdentityProvider,
code: "unauthorized_client" | "invalid_client",
..
} => Some(EmaAuthFailure::IdentityClientRejected),
// Future SDK stages must not invalidate the shared enterprise credential.
_ => None,
};
match failure {
Some(failure) => anyhow::Error::new(failure).context(error),
None => anyhow::Error::new(error),
}
}
#[cfg(test)]
#[path = "ema_exchange_tests.rs"]
mod tests;

View File

@@ -0,0 +1,468 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::EmaCredentialKind;
use crate::EmaErrorDetail;
use crate::EmaTokenSourceError;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::ema_claims::ID_JAG_TOKEN_TYPE;
use crate::ema_claims::validate_oidc_identity_assertion;
fn http_client() -> Arc<dyn HttpClient> {
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
)))
}
fn unique_form_fields(body: &[u8]) -> HashMap<String, String> {
let pairs = url::form_urlencoded::parse(body)
.into_owned()
.collect::<Vec<_>>();
let fields = pairs.iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(
pairs.len(),
fields.len(),
"OAuth form must not contain duplicate fields"
);
fields
}
fn jwt(claims: &Value) -> String {
format!(
"{}.{}.c2lnbmF0dXJl",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256","typ":"oauth-id-jag+jwt"}"#),
URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).expect("serialize claims"))
)
}
fn claims(issuer: &str, audience: &str, resource: &str) -> Value {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("current time")
.as_secs();
json!({"iss":issuer,"aud":audience,"sub":"user","client_id":"mcp-client",
"jti":"unique-jag","iat":now,"exp":now + 3600,"resource":resource,"scope":"files.read"})
}
fn jag_response(claims: &Value) -> Value {
let mut response = json!({"access_token":jwt(claims),"issued_token_type":ID_JAG_TOKEN_TYPE,
"token_type":"N_A","resource":claims["resource"]});
if let Some(scope) = claims.get("scope") {
response["scope"] = scope.clone();
}
response
}
fn token_response() -> Value {
json!({"access_token":"resource-token","token_type":"Bearer","expires_in":300})
}
async fn exchange(server: &MockServer, refresh_token: &str) -> Result<EmaAccessToken> {
let issuer = format!("{}/idp", server.uri());
let audience = format!("{}/as", server.uri());
exchange_id_jag(
EmaIdJagExchangeRequest {
idp_client_authentication: EmaClientAuthentication::None,
resource_client_authentication: EmaClientAuthentication::None,
resource: &format!("{}/mcp", server.uri()),
scopes: &[],
mcp_client_id: "mcp-client",
authorization_server_issuer: &audience,
authorization_server_token_endpoint: &format!("{audience}/token"),
idp_token_endpoint: &format!("{issuer}/token"),
idp_issuer: &issuer,
idp_client_id: "idp-client",
refresh_token: refresh_token.to_string(),
idp_http_client: http_client(),
resource_http_client: http_client(),
},
(),
std::convert::identity,
)
.await
.map(|(token, ())| token)
}
#[tokio::test]
async fn client_round_trip_preserves_signed_narrowing() -> Result<()> {
let requested_scopes = ["files.read".to_string(), "files.write".to_string()];
let client = http_client();
use codex_config::McpEmaTokenEndpointAuthMethod::ClientSecretBasic;
use codex_config::McpEmaTokenEndpointAuthMethod::ClientSecretPost;
for (scopes, echo_scope, refresh_token, idp_method) in [
(
requested_scopes.as_slice(),
true,
"opaque-refresh-token",
None,
),
(&[], true, "opaque-refresh-token", Some(ClientSecretBasic)),
(&[], false, "opaque-refresh-token", Some(ClientSecretPost)),
(requested_scopes.as_slice(), true, "", None),
(requested_scopes.as_slice(), true, " \t", None),
] {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
let audience = format!("{}/as", server.uri());
let resource = format!("{}/mcp", server.uri());
let mut jag = jag_response(&claims(&issuer, &audience, &resource));
if !echo_scope {
jag.as_object_mut()
.expect("ID-JAG response")
.remove("scope");
}
let valid = !refresh_token.trim().is_empty();
for (endpoint, response) in [("/idp/token", jag.clone()), ("/as/token", token_response())] {
Mock::given(method("POST"))
.and(path(endpoint))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(u64::from(valid))
.mount(&server)
.await;
}
let expected_subject = refresh_token.to_string();
let resource_method = idp_method.map(|method| match method {
ClientSecretBasic => ClientSecretPost,
ClientSecretPost => ClientSecretBasic,
});
let authentication = |method: Option<_>, secret| {
crate::ema_auth_policy::resolve_ema_client_auth(
Some(&json!([
"none",
"client_secret_basic",
"client_secret_post"
])),
method.map(|_| secret),
method,
"test issuer",
)
};
let idp_secret = "idp:+ /%secret";
let resource_secret = "resource:+ /%secret";
let result = exchange_id_jag(
EmaIdJagExchangeRequest {
idp_client_authentication: authentication(idp_method, idp_secret)?,
resource_client_authentication: authentication(resource_method, resource_secret)?,
resource: &resource,
scopes,
mcp_client_id: "mcp-client",
authorization_server_issuer: &audience,
authorization_server_token_endpoint: &format!("{audience}/token"),
idp_token_endpoint: &format!("{issuer}/token"),
idp_issuer: &issuer,
idp_client_id: "idp-client",
refresh_token: refresh_token.to_string(),
idp_http_client: Arc::clone(&client),
resource_http_client: Arc::clone(&client),
},
(),
std::convert::identity,
)
.boxed()
.await
.map(|(token, ())| token);
if !valid {
assert!(result.is_err(), "invalid subject must fail before HTTP");
assert!(
server
.received_requests()
.await
.expect("requests")
.is_empty()
);
continue;
}
let token = result?;
assert_eq!(
token,
EmaAccessToken {
access_token: "resource-token".to_string(),
expires_in: Some(Duration::from_secs(300)),
received_at: token.received_at,
}
);
let requests = server.received_requests().await.expect("requests");
assert_eq!(requests.len(), 2);
let mut forms = requests
.iter()
.map(|request| unique_form_fields(&request.body))
.collect::<Vec<_>>();
for (index, (method, client_id, secret)) in [
(idp_method, "idp-client", idp_secret),
(resource_method, "mcp-client", resource_secret),
]
.into_iter()
.enumerate()
{
let authorization = requests[index]
.headers
.get("authorization")
.map(|value| value.to_str().unwrap());
let encoded = url::form_urlencoded::byte_serialize(secret.as_bytes())
.collect::<String>()
.replace("%20", "+");
let basic = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!("{client_id}:{encoded}"))
);
assert_eq!(
authorization,
(method == Some(ClientSecretBasic)).then_some(basic.as_str())
);
assert_eq!(
forms[index].remove("client_secret").as_deref(),
(method == Some(ClientSecretPost)).then_some(secret)
);
assert_eq!(
forms[index].remove("client_id").as_deref(),
(method != Some(ClientSecretBasic)).then_some(client_id)
);
}
assert_eq!(
forms[0].remove("scope"),
(!scopes.is_empty()).then(|| scopes.join(" "))
);
assert_eq!(
forms[0],
HashMap::from([
(
"grant_type".to_string(),
TOKEN_EXCHANGE_GRANT_TYPE.to_string()
),
(
"requested_token_type".to_string(),
ID_JAG_TOKEN_TYPE.to_string(),
),
("subject_token".to_string(), expected_subject),
(
"subject_token_type".to_string(),
"urn:ietf:params:oauth:token-type:refresh_token".to_string(),
),
("audience".to_string(), audience.clone()),
("resource".to_string(), resource.clone()),
])
);
assert_eq!(
forms[1],
HashMap::from([
("grant_type".to_string(), JWT_BEARER_GRANT_TYPE.to_string()),
(
"assertion".to_string(),
jag["access_token"].as_str().expect("JAG").to_string()
),
])
);
}
Ok(())
}
#[tokio::test]
async fn sdk_validation_rejects_unsupported_authorization_before_returning_a_bearer() {
for location in [
"signed claims",
"IdP response",
"resource response",
"signed scope",
] {
let server = MockServer::builder().start().await;
let original = claims(
&format!("{}/idp", server.uri()),
&format!("{}/as", server.uri()),
&format!("{}/mcp", server.uri()),
);
let mut jag = jag_response(&original);
let mut bearer = token_response();
let details = json!([{"type": "payment_initiation"}]);
match location {
"signed claims" | "signed scope" => {
let mut changed = original;
if location == "signed claims" {
changed["authorization_details"] = details;
} else {
changed["scope"] = json!("files.read\tfiles.write");
}
jag = jag_response(&changed);
}
"IdP response" => jag["authorization_details"] = details,
"resource response" => bearer["authorization_details"] = details,
_ => unreachable!(),
}
let resource_requested = location == "resource response";
for (endpoint, response, count) in [
("/idp/token", jag, 1),
("/as/token", bearer, u64::from(resource_requested)),
] {
Mock::given(method("POST"))
.and(path(endpoint))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(count)
.mount(&server)
.await;
}
let error = exchange(&server, "refresh-token")
.await
.expect_err("SDK must reject unsupported authorization");
assert_eq!(
error.downcast_ref::<EmaError>(),
Some(&EmaError::InvalidResponse {
stage: if resource_requested {
EmaExchangeStage::ResourceAuthorizationServer
} else {
EmaExchangeStage::IdentityProvider
},
message: if location == "signed scope" {
"malformed or duplicate scopes"
} else {
"authorization_details is not supported"
},
}),
"{location}"
);
assert_eq!(
server.received_requests().await.expect("requests").len(),
if resource_requested { 2 } else { 1 }
);
}
}
#[test]
fn identity_and_credential_destinations_are_bound() {
for endpoint in [
"http://idp.example/token",
"https://user:pass@idp.example/token",
"https://idp.example/token#fragment",
] {
assert!(
validate_ema_oauth_endpoint(endpoint, "IdP").is_err(),
"accepted {endpoint}"
);
}
let original = claims("https://idp.example", "idp-client", "https://mcp.example");
assert!(
validate_oidc_identity_assertion(&jwt(&original), "https://idp.example", "idp-client")
.is_ok()
);
for (field, value) in [
("iss", json!("https://other.example")),
("aud", json!(["idp-client", "other"])),
("azp", json!("other")),
("exp", json!(0)),
("sub", json!("")),
] {
let mut changed = original.clone();
changed[field] = value;
assert!(
validate_oidc_identity_assertion(&jwt(&changed), "https://idp.example", "idp-client")
.is_err(),
"accepted changed {field}"
);
}
}
#[tokio::test]
async fn provider_errors_preserve_credential_policy_without_reflecting_credentials() {
const SENTINEL: &str = "secret-assertion-sentinel";
for (endpoint, grant_source) in [
("/idp/token", EmaInvalidGrantSource::EnterpriseIdentity),
("/as/token", EmaInvalidGrantSource::ResourceAuthorization),
] {
for code in [
SENTINEL,
"invalid_grant",
"insufficient_user_authentication",
"unauthorized_client",
"invalid_client",
"invalid_scope",
"malformed",
] {
let server = MockServer::builder().start().await;
if endpoint == "/as/token" {
let jag = jag_response(&claims(
&format!("{}/idp", server.uri()),
&format!("{}/as", server.uri()),
&format!("{}/mcp", server.uri()),
));
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(jag))
.expect(1)
.mount(&server)
.await;
}
let response = if code == "malformed" {
ResponseTemplate::new(200).set_body_json(json!({"expires_in": SENTINEL}))
} else {
ResponseTemplate::new(400).set_body_json(json!({
"error":code,"error_description":SENTINEL,
}))
};
Mock::given(method("POST"))
.and(path(endpoint))
.respond_with(response)
.expect(1)
.mount(&server)
.await;
let error = exchange(&server, SENTINEL)
.await
.expect_err("provider error should fail");
let expected = match code {
"invalid_grant" => Some(EmaAuthFailure::InvalidGrant { grant_source }),
"insufficient_user_authentication" => {
Some(EmaAuthFailure::InsufficientUserAuthentication { grant_source })
}
"unauthorized_client" | "invalid_client"
if grant_source == EmaInvalidGrantSource::EnterpriseIdentity =>
{
Some(EmaAuthFailure::IdentityClientRejected)
}
_ => None,
};
assert_eq!(error.downcast_ref::<EmaAuthFailure>(), expected.as_ref());
assert!(
!format!("{error:#?}").contains(SENTINEL),
"provider reflected a credential"
);
// Even an unsafe outer context must not reach the transport diagnostic.
let detail = EmaErrorDetail::from_error(&error.context(SENTINEL));
let transport_error = EmaTokenSourceError::Unexpected {
credential: EmaCredentialKind::Keyring,
detail,
};
assert!(!format!("{transport_error:#?} {transport_error}").contains(SENTINEL));
if code == "invalid_scope" {
let stage = if endpoint == "/idp/token" {
"IdentityProvider"
} else {
"ResourceAuthorizationServer"
};
assert_eq!(
transport_error.to_string(),
format!("{stage}: HTTP 400: invalid_scope")
);
}
assert_eq!(
server.received_requests().await.expect("requests").len(),
if endpoint == "/as/token" { 2 } else { 1 },
"exchange must not retry a rejected grant"
);
}
}
}

View File

@@ -0,0 +1,387 @@
//! Renewable, endpoint-confined EMA bearers. An unauthorized MCP operation is never replayed.
//! Authentication shares the request deadline, and a rejected bearer cannot evict a newer one.
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use std::time::Duration;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::future::BoxFuture;
use tokio::sync::OwnedRwLockReadGuard;
use tokio::sync::RwLock;
use tokio::sync::Semaphore;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use url::Url;
use crate::EmaAccessToken;
use crate::is_authentication_required_error;
use crate::validate_ema_auth_resource;
/// Supplies resource tokens for one immutable endpoint and pinned enterprise login.
/// Credential ownership is checked when renewing a token, not for cached bearer requests.
pub trait EmaTokenSource: Send + Sync {
fn endpoint(&self) -> &Url;
/// Acquires and validates credentials for renewal. Implementations recheck ownership
/// and a saved grant's generation after exchange before publishing the bearer.
fn access_token(&self) -> impl Future<Output = anyhow::Result<EmaAccessToken>> + Send;
}
/// Revocable authority held while one EMA connection awaits HTTP responses.
#[derive(Clone)]
pub struct EmaRequestAuthority {
revoked: CancellationToken,
is_current: Arc<dyn Fn() -> bool + Send + Sync>,
responses: Arc<RwLock<()>>,
policy: Option<codex_config::CloudConfigBundleBinding>,
}
impl Default for EmaRequestAuthority {
fn default() -> Self {
Self::new(CancellationToken::new(), || true)
}
}
impl EmaRequestAuthority {
/// Couples prompt cancellation with a synchronous check at each HTTP boundary.
/// The check must be cheap and must not perform credential or network I/O.
pub fn new(
revoked: CancellationToken,
is_current: impl Fn() -> bool + Send + Sync + 'static,
) -> Self {
Self {
revoked,
is_current: Arc::new(is_current),
responses: Arc::default(),
policy: None,
}
}
/// Policy changes stop new dispatches without cancelling already admitted responses.
pub fn with_policy(mut self, policy: Option<codex_config::CloudConfigBundleBinding>) -> Self {
self.policy = policy;
self
}
/// Isolate one connection's credential failure while sharing the owner's response drain.
pub fn child(&self) -> Self {
let owner = self.clone();
Self {
revoked: self.revoked.child_token(),
is_current: Arc::new(move || !owner.is_revoked()),
responses: Arc::clone(&self.responses),
policy: self.policy.clone(),
}
}
pub fn revoke(&self) {
self.revoked.cancel();
}
pub fn is_revoked(&self) -> bool {
if !self.revoked.is_cancelled() && !(self.is_current)() {
self.revoke();
}
self.revoked.is_cancelled()
}
pub fn check(&self) -> Result<(), ExecServerError> {
if self.is_revoked() {
return Err(revoked_authority_error());
}
Ok(())
}
pub fn check_new_request(&self) -> Result<(), ExecServerError> {
self.check()?;
if self.policy.as_ref().is_some_and(|binding| {
binding.read().status != codex_config::CloudConfigBundleBindingStatus::Current
}) {
return Err(ExecServerError::RequestNotSent(
"enterprise MCP policy is updating or unavailable; retry after it is applied"
.into(),
));
}
Ok(())
}
/// Wait until response futures admitted before revocation complete or are cancelled.
pub async fn quiesce(&self) {
let _responses = self.responses.clone().write_owned().await;
}
async fn acquire(&self) -> Result<OwnedRwLockReadGuard<()>, ExecServerError> {
let response = self.responses.clone().read_owned().await;
self.check_new_request()?;
Ok(response)
}
async fn cancelled(&self) {
self.revoked.cancelled().await;
}
}
/// Adds a renewable resource bearer to the existing runtime-selected HTTP capability.
pub struct EmaAuthenticatedHttpClient<S> {
inner: Arc<dyn HttpClient>,
source: S,
authority: EmaRequestAuthority,
token: Mutex<Option<CachedToken>>,
renewal: Semaphore,
}
struct CachedToken {
value: String,
refresh_at: Instant,
}
impl CachedToken {
fn new(token: EmaAccessToken) -> Self {
// Bound reuse even when the authorization server omits an expiry.
let lifetime = token
.expires_in
.unwrap_or(Duration::from_secs(300))
.min(Duration::from_secs(300));
let skew = Duration::from_secs(30).min(lifetime / 2);
Self {
value: token.access_token,
refresh_at: token.received_at + lifetime.saturating_sub(skew),
}
}
}
impl<S: EmaTokenSource> EmaAuthenticatedHttpClient<S> {
pub fn new(
inner: Arc<dyn HttpClient>,
source: S,
access_token: EmaAccessToken,
authority: EmaRequestAuthority,
) -> Self {
Self {
inner,
source,
authority,
token: Mutex::new(Some(CachedToken::new(access_token))),
renewal: Semaphore::new(/*permits*/ 1),
}
}
fn cached_token(&self) -> MutexGuard<'_, Option<CachedToken>> {
self.token.lock().unwrap_or_else(PoisonError::into_inner)
}
async fn authenticate(
&self,
params: &mut HttpRequestParams,
) -> Result<String, ExecServerError> {
let expected = self.source.endpoint();
let target = Url::parse(&params.url).map_err(|_| {
ExecServerError::HttpRequest("invalid enterprise MCP destination".to_string())
})?;
if expected.origin() != target.origin()
|| expected.path() != target.path()
|| expected.query() != target.query()
|| validate_ema_auth_resource(&params.url, /*resource*/ None).is_err()
{
return Err(ExecServerError::HttpRequest(
"refusing to send enterprise bearer outside the configured MCP endpoint"
.to_string(),
));
}
let current_token = || {
self.cached_token()
.as_ref()
.filter(|token| Instant::now() < token.refresh_at)
.map(|token| token.value.clone())
};
let value = if let Some(value) = current_token() {
value
} else {
let _renewal = self.renewal.acquire().await.map_err(|_| {
ExecServerError::HttpRequest("enterprise token renewal gate closed".to_string())
})?;
if let Some(value) = current_token() {
value
} else {
let renewed = self.source.access_token().await.map_err(|error| {
if let Err(refusal) = self.authority.check_new_request() {
return refusal;
}
if is_authentication_required_error(&error) {
self.authority.revoke();
}
auth_error(error)
})?;
let token = CachedToken::new(renewed);
if Instant::now() >= token.refresh_at {
return Err(ExecServerError::HttpRequest(
"enterprise MCP bearer expired during credential validation".to_string(),
));
}
let value = token.value.clone();
*self.cached_token() = Some(token);
value
}
};
params.redirect_policy = HttpRedirectPolicy::Stop;
params
.headers
.retain(|header| !header.name.eq_ignore_ascii_case("authorization"));
params.headers.push(HttpHeader {
name: "authorization".to_string(),
value: format!("Bearer {value}"),
value_env_var: None,
});
Ok(value)
}
fn clear_rejected_token(&self, rejected: &str) {
let mut token = self.cached_token();
if token.as_ref().is_some_and(|token| token.value == rejected) {
*token = None;
}
}
fn validate_response(
&self,
response: &HttpRequestResponse,
token: &str,
) -> Result<(), ExecServerError> {
if response.status == 401 {
self.clear_rejected_token(token);
return Err(ExecServerError::AuthenticationRequired(
"enterprise MCP bearer was rejected; reconnect to renew authorization".to_string(),
));
}
// An outer redirect wrapper may still follow a response even though the
// inner HTTP capability received Stop. Do not let it replay this operation.
if (300..400).contains(&response.status) {
return Err(ExecServerError::HttpRequest(
"enterprise MCP redirects are not allowed".to_string(),
));
}
Ok(())
}
}
fn auth_error(error: anyhow::Error) -> ExecServerError {
if let Some(error) = error.downcast_ref::<crate::EmaTokenSourceError>() {
return if error.is_authentication_required() {
ExecServerError::AuthenticationRequired(error.to_string())
} else {
ExecServerError::HttpRequest(error.to_string())
};
}
if is_authentication_required_error(&error) {
ExecServerError::AuthenticationRequired(
"enterprise MCP authentication is required".to_string(),
)
} else {
ExecServerError::HttpRequest(
"enterprise MCP token acquisition or credential validation failed".to_string(),
)
}
}
impl<S: EmaTokenSource> HttpClient for EmaAuthenticatedHttpClient<S> {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
Box::pin(async move {
let deadline = params
.timeout_ms
.map(|timeout_ms| Instant::now() + Duration::from_millis(timeout_ms));
let request = async {
let _authority = self.authority.acquire().await?;
let token = self.authenticate(&mut params).await?;
self.authority.check_new_request()?;
if let Some(deadline) = deadline {
params.timeout_ms = Some(remaining_timeout(deadline)?);
}
let response = self.inner.http_request(params).await?;
self.authority.check()?;
self.validate_response(&response, &token)?;
Ok(response)
};
tokio::select! {
biased;
() = self.authority.cancelled() => Err(revoked_authority_error()),
() = deadline_elapsed(deadline) => Err(request_timeout_error()),
result = request => result,
}
})
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
Box::pin(async move {
let deadline = params
.timeout_ms
.map(|timeout_ms| Instant::now() + Duration::from_millis(timeout_ms));
let request = async {
let _authority = self.authority.acquire().await?;
let token = self.authenticate(&mut params).await?;
self.authority.check_new_request()?;
if let Some(deadline) = deadline {
params.timeout_ms = Some(remaining_timeout(deadline)?);
}
let response = self.inner.http_request_stream(params).await?;
self.authority.check()?;
self.validate_response(&response.0, &token)?;
Ok((
response.0,
response.1.cancel_on(self.authority.revoked.clone()),
))
};
tokio::select! {
biased;
() = self.authority.cancelled() => Err(revoked_authority_error()),
() = deadline_elapsed(deadline) => Err(request_timeout_error()),
result = request => result,
}
})
}
}
async fn deadline_elapsed(deadline: Option<Instant>) {
match deadline {
Some(deadline) => tokio::time::sleep_until(deadline).await,
None => std::future::pending().await,
}
}
fn remaining_timeout(deadline: Instant) -> Result<u64, ExecServerError> {
let remaining = deadline
.checked_duration_since(Instant::now())
.filter(|remaining| !remaining.is_zero())
.ok_or_else(request_timeout_error)?;
Ok(u64::try_from(remaining.as_millis())
.unwrap_or(u64::MAX)
.max(1))
}
fn request_timeout_error() -> ExecServerError {
ExecServerError::HttpRequest("enterprise MCP request timed out".to_string())
}
fn revoked_authority_error() -> ExecServerError {
ExecServerError::AuthenticationRequired(
"enterprise MCP authorization changed; reconnect before using this server".to_string(),
)
}
#[cfg(test)]
#[path = "ema_http_client_tests.rs"]
mod tests;

View File

@@ -0,0 +1,470 @@
//! Authentication, deadlines, and concurrent responses share the same request invariants.
use codex_config::CloudConfigBundlePolicy;
use codex_config::CloudConfigBundleSnapshot;
use codex_config::test_support::CloudConfigBundleFixture;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use super::*;
use crate::ema_auth_policy::EmaInvalidGrantSource;
type Client = EmaAuthenticatedHttpClient<Arc<Source>>;
#[derive(Clone, Copy)]
enum RequestMode {
Buffered,
Streaming,
}
impl RequestMode {
fn start(
self,
client: Arc<Client>,
mut params: HttpRequestParams,
) -> tokio::task::JoinHandle<Result<HttpRequestResponse, ExecServerError>> {
tokio::spawn(async move {
params.stream_response = matches!(self, Self::Streaming);
match self {
Self::Buffered => client.http_request(params).await,
Self::Streaming => client
.http_request_stream(params)
.await
.map(|(response, _body)| response),
}
})
}
}
#[derive(Debug)]
struct PendingRequest {
params: HttpRequestParams,
response: oneshot::Sender<u16>,
}
struct ControlledHttpClient(mpsc::UnboundedSender<PendingRequest>);
impl HttpClient for ControlledHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
Box::pin(async move {
let (response, receiver) = oneshot::channel();
self.0
.send(PendingRequest { params, response })
.expect("capture HTTP request");
Ok(HttpRequestResponse {
status: receiver.await.expect("provide HTTP response"),
headers: Vec::new(),
body: Vec::new().into(),
})
})
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
Box::pin(async move {
Ok((
self.http_request(params).await?,
HttpResponseBodyStream::from_chunks(Vec::new()),
))
})
}
}
fn controlled_fixture() -> (
Arc<Client>,
Arc<Source>,
HttpRequestParams,
mpsc::UnboundedReceiver<PendingRequest>,
) {
controlled_fixture_for_endpoint("https://mcp.example/mcp")
}
fn controlled_fixture_for_endpoint(
endpoint: &str,
) -> (
Arc<Client>,
Arc<Source>,
HttpRequestParams,
mpsc::UnboundedReceiver<PendingRequest>,
) {
let (mut client, source, params) = fixture(endpoint);
let (sender, receiver) = mpsc::unbounded_channel();
client.inner = Arc::new(ControlledHttpClient(sender));
(Arc::new(client), source, params, receiver)
}
#[tokio::test]
async fn exact_endpoint_and_renewal_credentials_are_checked_before_network_use()
-> anyhow::Result<()> {
let endpoint = "https://mcp.example/mcp?tenant=one";
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
let (client, source, params, mut requests) = controlled_fixture_for_endpoint(endpoint);
for target in [
endpoint.replace("one", "two"),
endpoint.replace("/mcp", "/other"),
"https://other.example/mcp?tenant=one".to_string(),
format!("{endpoint}#fragment"),
] {
let mut request = params.clone();
request.url = target;
assert!(matches!(
mode.start(Arc::clone(&client), request).await?,
Err(ExecServerError::HttpRequest(message))
if message == "refusing to send enterprise bearer outside the configured MCP endpoint"
));
}
source.valid.store(false, Ordering::SeqCst);
*client.cached_token() = None;
assert!(matches!(
mode.start(Arc::clone(&client), params.clone()).await?,
Err(ExecServerError::AuthenticationRequired(_))
));
source.valid.store(true, Ordering::SeqCst);
source.invalidate_on_refresh.store(true, Ordering::SeqCst);
*client.cached_token() = None;
assert!(matches!(
mode.start(client, params).await?,
Err(ExecServerError::AuthenticationRequired(_))
));
assert!(requests.try_recv().is_err());
}
Ok(())
}
#[tokio::test]
async fn outgoing_requests_replace_all_authorization_headers_and_stop_redirects()
-> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
let (client, _source, mut params, mut requests) = controlled_fixture();
params
.headers
.extend(["authorization", "aUtHoRiZaTiOn"].map(|name| HttpHeader {
name: name.to_string(),
value: "another-stale-credential".to_string(),
value_env_var: None,
}));
let response = mode.start(client, params);
let request = requests.recv().await.expect("authenticated request");
assert_eq!(request.params.redirect_policy, HttpRedirectPolicy::Stop);
assert_eq!(
request.params.headers,
vec![HttpHeader {
name: "authorization".to_string(),
value: "Bearer initial".to_string(),
value_env_var: None,
}],
"replace every case variant with exactly one bearer"
);
request.response.send(/*t*/ 200).expect("complete request");
assert_eq!(response.await??.status, 200);
}
Ok(())
}
#[tokio::test]
async fn resource_bearers_never_follow_redirects() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(307).insert_header("location", "/mcp"))
.expect(2)
.mount(&server)
.await;
let (client, _source, params) = fixture(&format!("{}/mcp", server.uri()));
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
let client = crate::http_client_redirect::SameOriginRedirectHttpClient::new(Arc::new(client));
for result in [
client.http_request(params.clone()).await.map(|_| ()),
client.http_request_stream(params).await.map(|_| ()),
] {
assert!(matches!(
result,
Err(ExecServerError::HttpRequest(message))
if message == "enterprise MCP redirects are not allowed"
));
}
Ok(())
}
fn bearer(request: &PendingRequest) -> &str {
&request
.params
.headers
.iter()
.find(|header| header.name == "authorization")
.expect("bearer header")
.value
}
#[tokio::test]
async fn credential_failures_are_classified_before_dispatch() -> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
for failure in [
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
},
EmaAuthFailure::InsufficientUserAuthentication {
grant_source: crate::EmaInvalidGrantSource::EnterpriseIdentity,
},
EmaAuthFailure::ReauthenticationRequired,
] {
let (client, source, params, mut requests) = controlled_fixture();
*client.cached_token() = None;
match failure {
EmaAuthFailure::ReauthenticationRequired => {
source.valid.store(/*val*/ false, Ordering::SeqCst);
}
failure => {
*source.renewal_error.lock().unwrap() =
Some(anyhow::Error::new(failure).context("token exchange failed"));
}
}
assert!(matches!(
mode.start(client, params).await?,
Err(ExecServerError::AuthenticationRequired(_))
));
assert!(requests.try_recv().is_err());
}
for error in [
anyhow::Error::new(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
})
.context("resource authorization failed without invalidating the enterprise identity"),
anyhow::anyhow!("temporary network failure"),
anyhow::Error::new(crate::EmaTokenSourceError::unexpected(
crate::EmaCredentialKind::Account,
)),
] {
let (client, source, params, mut requests) = controlled_fixture();
*client.cached_token() = None;
*source.renewal_error.lock().unwrap() = Some(error);
assert!(matches!(
mode.start(Arc::clone(&client), params.clone()).await?,
Err(ExecServerError::HttpRequest(_))
));
assert!(requests.try_recv().is_err());
let retry = mode.start(client, params);
let request = requests
.recv()
.await
.expect("retry after transient failure");
assert_eq!(bearer(&request), "Bearer renewed-2");
request.response.send(/*t*/ 200).expect("complete retry");
assert_eq!(retry.await??.status, 200);
}
}
Ok(())
}
#[tokio::test]
async fn delayed_unauthorized_response_preserves_the_renewed_bearer() -> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
let (client, source, params, mut requests) = controlled_fixture();
let first = mode.start(Arc::clone(&client), params.clone());
let first_request = requests.recv().await.expect("first request");
let delayed = mode.start(Arc::clone(&client), params.clone());
let delayed_request = requests.recv().await.expect("delayed request");
assert_eq!(
(bearer(&first_request), bearer(&delayed_request)),
("Bearer initial", "Bearer initial")
);
first_request.response.send(/*t*/ 401).expect("first 401");
assert!(matches!(
first.await?,
Err(ExecServerError::AuthenticationRequired(_))
));
let renewed = mode.start(Arc::clone(&client), params.clone());
let renewed_request = requests.recv().await.expect("renewed request");
assert_eq!(bearer(&renewed_request), "Bearer renewed-1");
renewed_request
.response
.send(/*t*/ 200)
.expect("renewed response");
assert_eq!(renewed.await??.status, 200);
delayed_request
.response
.send(/*t*/ 401)
.expect("delayed 401");
assert!(matches!(
delayed.await?,
Err(ExecServerError::AuthenticationRequired(_))
));
let next = mode.start(Arc::clone(&client), params);
let next_request = requests.recv().await.expect("next request");
assert_eq!(bearer(&next_request), "Bearer renewed-1");
next_request
.response
.send(/*t*/ 200)
.expect("next response");
assert_eq!(next.await??.status, 200);
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
assert!(requests.try_recv().is_err(), "no operation was replayed");
}
Ok(())
}
#[tokio::test]
async fn authentication_waits_share_the_request_deadline() -> anyhow::Result<()> {
#[derive(Clone, Copy)]
enum Wait {
Authority,
Renewal,
Credentials,
Exchange,
}
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
for wait in [
Wait::Authority,
Wait::Renewal,
Wait::Credentials,
Wait::Exchange,
] {
let (client, source, mut params, mut requests) = controlled_fixture();
let (gate, _entered, _release) = CredentialGate::new();
let mut authority = None;
let mut renewal = None;
match wait {
Wait::Authority => authority = Some(client.authority.responses.write().await),
Wait::Renewal => {
*client.cached_token() = None;
renewal = Some(client.renewal.acquire().await?);
}
Wait::Credentials => {
*client.cached_token() = None;
*source.credential_gate.lock().unwrap() = Some(gate);
}
Wait::Exchange => {
*client.cached_token() = None;
*source.renewal_gate.lock().unwrap() = Some(gate);
}
}
params.timeout_ms = Some(20);
let response = tokio::time::timeout(
Duration::from_secs(/*secs*/ 1),
mode.start(Arc::clone(&client), params),
)
.await??;
assert!(
matches!(response, Err(ExecServerError::HttpRequest(message))
if message == "enterprise MCP request timed out")
);
assert!(requests.try_recv().is_err());
drop((authority, renewal));
assert_eq!(source.active_leases.load(Ordering::SeqCst), 0);
}
let (client, source, mut params, mut requests) = controlled_fixture();
params.timeout_ms = Some(0);
assert!(matches!(
mode.start(client, params).await?,
Err(ExecServerError::HttpRequest(_))
));
assert_eq!(source.renewals.load(Ordering::SeqCst), 0);
assert!(requests.try_recv().is_err());
}
Ok(())
}
#[tokio::test]
async fn authentication_time_is_removed_from_the_inner_timeout() -> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
for timeout in [Some(1000), None] {
let (client, source, mut params, mut requests) = controlled_fixture();
let (gate, entered, release) = CredentialGate::new();
*client.cached_token() = None;
*source.credential_gate.lock().unwrap() = Some(gate);
params.timeout_ms = timeout;
let response = mode.start(client, params);
entered.await?;
tokio::time::sleep(Duration::from_millis(/*millis*/ 30)).await;
release.send(()).expect("release credentials");
let request = requests.recv().await.expect("authenticated request");
match timeout {
Some(timeout) => assert!(
request
.params
.timeout_ms
.is_some_and(|remaining| remaining > 0 && remaining <= timeout - 30)
),
None => assert_eq!(request.params.timeout_ms, None),
}
request.response.send(/*t*/ 200).expect("complete request");
assert_eq!(response.await??.status, 200);
}
}
Ok(())
}
#[tokio::test]
async fn policy_suspension_requires_fresh_authority_without_cancelling_admitted_request()
-> anyhow::Result<()> {
let (mut client, source, params, mut requests) = controlled_fixture();
let policy = CloudConfigBundlePolicy::default();
let mut snapshot = CloudConfigBundleSnapshot {
bundle: Ok(None),
binding: None,
config_server: None,
};
policy.publish_snapshot(&mut snapshot);
Arc::get_mut(&mut client)
.expect("single client owner")
.authority = EmaRequestAuthority::default().with_policy(snapshot.binding.take());
let pending = RequestMode::Buffered.start(Arc::clone(&client), params.clone());
let dispatched = requests.recv().await.expect("admitted request");
*client.cached_token() = None;
let (gate, waiting, release) = CredentialGate::new();
*source.credential_gate.lock().unwrap() = Some(gate);
let renewal = RequestMode::Streaming.start(Arc::clone(&client), params.clone());
waiting.await?;
let next = CloudConfigBundleFixture::enterprise_config("model = 'managed'").into_bundle();
policy.observe_remote_bundle(&next);
*source.renewal_error.lock().unwrap() =
Some(anyhow::anyhow!("exchange refused after policy changed"));
release.send(()).expect("release renewal");
assert!(matches!(
renewal.await?,
Err(ExecServerError::RequestNotSent(_))
));
assert!(matches!(
client.http_request(params.clone()).await,
Err(ExecServerError::RequestNotSent(message)) if message.contains("retry")
));
assert!(matches!(
requests.try_recv(),
Err(mpsc::error::TryRecvError::Empty)
));
dispatched
.response
.send(200)
.expect("complete admitted request");
assert_eq!(pending.await??.status, 200);
snapshot.bundle = Ok(Some(next));
policy.publish_snapshot(&mut snapshot);
assert!(matches!(
client.http_request(params).await,
Err(ExecServerError::RequestNotSent(_))
));
let (mut fresh_client, _source, fresh_params, mut fresh_requests) = controlled_fixture();
Arc::get_mut(&mut fresh_client)
.expect("single client owner")
.authority = EmaRequestAuthority::default().with_policy(snapshot.binding);
let pending = RequestMode::Buffered.start(fresh_client, fresh_params);
fresh_requests
.recv()
.await
.expect("request after recovery")
.response
.send(200)
.expect("complete recovered request");
assert_eq!(pending.await??.status, 200);
Ok(())
}

View File

@@ -0,0 +1,450 @@
//! Renewable sessions use cached bearers without credential reads and never replay operations.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
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 wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::oauth::RefreshCredentialLock;
struct Source {
endpoint: Url,
renewals: AtomicUsize,
valid: AtomicBool,
invalidate_on_refresh: AtomicBool,
credential_gate: Mutex<Option<CredentialGate>>,
renewal_gate: Mutex<Option<CredentialGate>>,
renewal_error: Mutex<Option<anyhow::Error>>,
active_leases: AtomicUsize,
renewal_with_lease: AtomicBool,
lock_identity: Mutex<Option<(String, String)>>,
}
struct CredentialGate {
entered: tokio::sync::oneshot::Sender<()>,
release: tokio::sync::oneshot::Receiver<()>,
}
impl CredentialGate {
fn new() -> (
Self,
tokio::sync::oneshot::Receiver<()>,
tokio::sync::oneshot::Sender<()>,
) {
let (entered, waiting) = tokio::sync::oneshot::channel();
let (release, released) = tokio::sync::oneshot::channel();
(
Self {
entered,
release: released,
},
waiting,
release,
)
}
async fn wait(self) {
let _ = self.entered.send(());
let _ = self.release.await;
}
}
struct CredentialLease {
source: Arc<Source>,
_lock: Option<RefreshCredentialLock>,
}
impl Drop for CredentialLease {
fn drop(&mut self) {
self.source
.active_leases
.fetch_sub(/*val*/ 1, Ordering::SeqCst);
}
}
impl EmaTokenSource for Arc<Source> {
fn endpoint(&self) -> &Url {
&self.endpoint
}
async fn access_token(&self) -> anyhow::Result<EmaAccessToken> {
if !self.valid.load(Ordering::SeqCst) {
return Err(anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired)
.context("credentials were removed"));
}
let identity = self.lock_identity.lock().unwrap().clone();
let lock = match identity {
Some((name, issuer)) => {
Some(RefreshCredentialLock::acquire_for_server(&name, &issuer).await?)
}
None => None,
};
self.active_leases.fetch_add(/*val*/ 1, Ordering::SeqCst);
let _lease = CredentialLease {
source: Arc::clone(self),
_lock: lock,
};
let gate = self.credential_gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.wait().await;
}
let renewal = self.renewals.fetch_add(/*val*/ 1, Ordering::SeqCst) + 1;
self.renewal_with_lease.fetch_or(
self.active_leases.load(Ordering::SeqCst) != 0,
Ordering::SeqCst,
);
if let Some(error) = self.renewal_error.lock().unwrap().take() {
return Err(error);
}
let received_at = Instant::now();
let gate = self.renewal_gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.wait().await;
}
tokio::task::yield_now().await;
if self.invalidate_on_refresh.load(Ordering::SeqCst) {
self.valid.store(false, Ordering::SeqCst);
return Err(anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired));
}
Ok(EmaAccessToken {
access_token: format!("renewed-{renewal}"),
expires_in: Some(Duration::from_secs(/*secs*/ 300)),
received_at,
})
}
}
fn fixture(
endpoint: &str,
) -> (
EmaAuthenticatedHttpClient<Arc<Source>>,
Arc<Source>,
HttpRequestParams,
) {
let source = Arc::new(Source {
endpoint: Url::parse(endpoint).expect("endpoint"),
renewals: AtomicUsize::new(0),
valid: AtomicBool::new(true),
invalidate_on_refresh: AtomicBool::new(false),
credential_gate: Mutex::new(/*t*/ None),
renewal_gate: Mutex::new(/*t*/ None),
renewal_error: Mutex::new(/*t*/ None),
active_leases: AtomicUsize::new(/*v*/ 0),
renewal_with_lease: AtomicBool::new(/*v*/ false),
lock_identity: Mutex::new(None),
});
let client = EmaAuthenticatedHttpClient::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
Arc::clone(&source),
EmaAccessToken {
access_token: "initial".to_string(),
expires_in: Some(Duration::from_secs(300)),
received_at: Instant::now(),
},
EmaRequestAuthority::default(),
);
let params = HttpRequestParams {
method: "POST".to_string(),
url: endpoint.to_string(),
headers: vec![HttpHeader {
name: "Authorization".to_string(),
value: "discard-me".to_string(),
value_env_var: None,
}],
body: Some(br#"{"method":"tools/call"}"#.to_vec().into()),
timeout_ms: Some(5000),
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "operation".to_string(),
stream_response: false,
};
(client, source, params)
}
#[tokio::test]
async fn cached_bearer_does_not_read_credentials_until_renewal() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
let (client, source, params) = fixture(&format!("{}/mcp", server.uri()));
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
assert_eq!(client.http_request(params.clone()).await?.status, 200);
source.valid.store(false, Ordering::SeqCst);
assert_eq!(client.http_request(params.clone()).await?.status, 200);
*client.cached_token() = None;
assert!(matches!(
client.http_request(params).await,
Err(ExecServerError::AuthenticationRequired(_))
));
assert_eq!(source.renewals.load(Ordering::SeqCst), 0);
let requests = server.received_requests().await.expect("recorded requests");
let bearers = requests
.iter()
.map(|request| {
request.headers["authorization"]
.to_str()
.expect("bearer header")
.to_string()
})
.collect::<Vec<_>>();
assert_eq!(bearers, ["Bearer initial", "Bearer initial"]);
Ok(())
}
#[tokio::test]
async fn revocation_during_renewal_prevents_dispatch() -> anyhow::Result<()> {
let server = MockServer::start().await;
let endpoint = format!("{}/mcp", server.uri());
let (gate, validated_rx, release_tx) = CredentialGate::new();
let (mut client, source, params) = fixture(&endpoint);
let current = Arc::new(AtomicBool::new(true));
client.authority = EmaRequestAuthority::new(CancellationToken::new(), {
let current = Arc::clone(&current);
move || current.load(Ordering::SeqCst)
});
*client.cached_token() = None;
*source.credential_gate.lock().unwrap() = Some(gate);
let authority = client.authority.clone();
let request = tokio::spawn(async move { client.http_request(params).await });
validated_rx.await?;
// A watcher need not have run: dispatch must check the current owner itself.
current.store(false, Ordering::SeqCst);
let _ = release_tx.send(());
tokio::time::timeout(Duration::from_secs(1), authority.quiesce()).await?;
assert!(matches!(
request.await?,
Err(ExecServerError::AuthenticationRequired(_))
));
assert!(
server
.received_requests()
.await
.expect("requests")
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn revocation_ends_an_existing_response_stream() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_string("account-a-data"))
.mount(&server)
.await;
let (mut client, _source, params) = fixture(&format!("{}/mcp", server.uri()));
let cancellation = CancellationToken::new();
client.authority = EmaRequestAuthority::new(cancellation.child_token(), || true);
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
let (_response, mut body) = client.http_request_stream(params).await?;
cancellation.cancel();
assert_eq!(body.recv().await?, None);
Ok(())
}
#[tokio::test]
async fn revocation_interrupts_an_active_multichunk_response() -> anyhow::Result<()> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let endpoint = format!("http://{}/mcp", listener.local_addr()?);
let (chunks, receiver) = tokio::sync::mpsc::channel::<Result<bytes::Bytes, std::io::Error>>(2);
let receiver = Arc::new(Mutex::new(Some(receiver)));
let app = axum::Router::new().route(
"/mcp",
axum::routing::post(move || {
let receiver = receiver.lock().unwrap().take().expect("one request");
async move {
let stream = futures::stream::unfold(receiver, |mut receiver| async {
receiver.recv().await.map(|chunk| (chunk, receiver))
});
(
[("content-type", "text/event-stream")],
axum::body::Body::from_stream(stream),
)
}
}),
);
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
axum::serve(listener, app).await
}));
let (client, _source, params) = fixture(&endpoint);
chunks
.send(Ok(bytes::Bytes::from_static(b"data: first\n\n")))
.await?;
let (_, mut body) = client.http_request_stream(params).await?;
assert_eq!(body.recv().await?, Some(b"data: first\n\n".to_vec()));
let mut next = Box::pin(body.recv());
assert!(futures::poll!(&mut next).is_pending());
client.authority.revoke();
tokio::time::timeout(Duration::from_secs(1), client.authority.quiesce()).await?;
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), next).await??,
None
);
// Even a later chunk cannot revive a stream whose authority was revoked.
let _ = chunks
.send(Ok(bytes::Bytes::from_static(b"data: second\n\n")))
.await;
assert_eq!(body.recv().await?, None);
server.abort();
let _ = server.await;
Ok(())
}
#[tokio::test]
async fn unauthorized_requests_are_not_replayed_and_later_requests_renew() -> anyhow::Result<()> {
for streaming in [false, true] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &wiremock::Request| {
ResponseTemplate::new(if request.headers["authorization"] == "Bearer initial" {
401
} else {
200
})
})
.mount(&server)
.await;
let (client, source, params) = fixture(&format!("{}/mcp", server.uri()));
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
for (status, count) in [(401, 1), (200, 2), (200, 3)] {
let result = if streaming {
client
.http_request_stream(params.clone())
.await
.map(|response| response.0.status)
} else {
client
.http_request(params.clone())
.await
.map(|response| response.status)
};
if status == 401 {
let error = result.expect_err("unauthorized operation fails without replay");
assert!(is_authentication_required_error(&anyhow::Error::new(error)));
} else {
assert_eq!(result?, status);
}
assert_eq!(
server.received_requests().await.expect("requests").len(),
count
);
}
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
// Concurrent callers of an expiring token share one renewal.
client
.cached_token()
.as_mut()
.expect("cached token")
.refresh_at = Instant::now();
let results =
futures::future::join_all((0..8).map(|_| client.http_request(params.clone()))).await;
assert!(results.iter().all(Result::is_ok));
assert_eq!(source.renewals.load(Ordering::SeqCst), 2);
}
Ok(())
}
#[path = "ema_http_client_regression_tests.rs"]
mod regressions;
#[tokio::test]
async fn initial_bearer_aged_during_validation_is_renewed_before_dispatch() -> anyhow::Result<()> {
for streaming in [false, true] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
let (client, source, params) = fixture(&format!("{}/mcp", server.uri()));
// Age the token by advancing time: backdating an Instant can underflow
// on a Windows runner that has only recently booted.
tokio::time::pause();
let received_at = Instant::now();
tokio::time::advance(Duration::from_secs(301)).await;
let client = EmaAuthenticatedHttpClient::new(
client.inner,
Arc::clone(&source),
EmaAccessToken {
access_token: "aged-in-validation".to_string(),
expires_in: Some(Duration::from_secs(300)),
received_at,
},
client.authority,
);
tokio::time::resume();
if streaming {
client.http_request_stream(params).await?;
} else {
client.http_request(params).await?;
}
let requests = server.received_requests().await.expect("requests");
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].headers["authorization"], "Bearer renewed-1");
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
}
Ok(())
}
#[tokio::test]
async fn renewal_aged_during_validation_is_not_dispatched_or_cached() -> anyhow::Result<()> {
for streaming in [false, true] {
let server = MockServer::start().await;
let (client, source, mut params) = fixture(&format!("{}/mcp", server.uri()));
params.timeout_ms = None;
*client.cached_token() = None;
let client = Arc::new(client);
let (gate, waiting, release) = CredentialGate::new();
*source.renewal_gate.lock().unwrap() = Some(gate);
tokio::time::pause();
let request = {
let client = Arc::clone(&client);
tokio::spawn(async move {
if streaming {
client
.http_request_stream(params)
.await
.map(|(response, _)| response)
} else {
client.http_request(params).await
}
})
};
waiting.await?;
tokio::time::advance(Duration::from_secs(301)).await;
release.send(()).expect("release validation");
let result = request.await?;
tokio::time::resume();
assert!(matches!(result, Err(ExecServerError::HttpRequest(message))
if message == "enterprise MCP bearer expired during credential validation"));
assert!(client.cached_token().is_none());
assert!(
server
.received_requests()
.await
.expect("requests")
.is_empty()
);
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
}
Ok(())
}

View File

@@ -0,0 +1,294 @@
//! Shared enterprise IdP discovery and stored refresh-token resolution.
//! Login and token exchange require published metadata bound to the configured issuer.
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use codex_exec_server::HttpClient;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use oauth2::TokenResponse;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthHttpClient;
use tracing::instrument::WithSubscriber;
use crate::EmaCredentialLease;
use crate::EmaErrorDetail;
use crate::ema_auth_policy::advertised_capability;
use crate::ema_auth_policy::ema_reauthentication_required;
use crate::ema_auth_policy::resolve_ema_client_auth;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::ema_claims::ID_JAG_TOKEN_TYPE;
use crate::ema_exchange::TOKEN_EXCHANGE_GRANT_TYPE;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::StoredOAuthTokens;
use crate::oauth::stored_oidc_identity;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::utils::build_default_headers;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
pub struct EmaIdpIdentityRequest<'a> {
pub issuer: &'a str,
pub client_id: &'a str,
pub client_secret: Option<&'a str>,
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
pub credentials: EmaCredentialLease,
pub http_client: Arc<dyn HttpClient>,
pub redirect_mode: StreamableHttpRedirectMode,
}
/// An opaque IdP refresh token paired with the credentials admitted for its exchange.
pub struct EmaIdpIdentity<L = EmaCredentialLease> {
pub(crate) token_endpoint: String,
pub(crate) refresh_token: String,
pub(crate) credentials: L,
pub(crate) client_authentication: EmaClientAuthentication,
}
impl<L> EmaIdpIdentity<L> {
/// Preserve an opaque credential lease when selecting an EMA credential source.
/// The mapping must retain its owned refresh guard until the IdP exchange finishes.
pub fn map_credentials<U>(self, map: impl FnOnce(L) -> U) -> EmaIdpIdentity<U> {
EmaIdpIdentity {
token_endpoint: self.token_endpoint,
refresh_token: self.refresh_token,
credentials: map(self.credentials),
client_authentication: self.client_authentication,
}
}
}
/// Resolve a refresh token issued by the account's validated OAuth authority.
/// The caller supplies trusted persisted issuer/client provenance and an ID/refresh-token
/// pair from one admitted account record. Discovery may run before acquiring a refresh
/// guard; before exchange, attach a lease that still matches that record with map_credentials.
/// ID-token claims corroborate that record; this does not verify a JWT signature or
/// authenticate an expired ID token. Only the refresh token is exchanged with the IdP.
pub async fn resolve_ema_account_idp_identity<L: Send>(
idp: &codex_config::McpServerIdpOAuthConfig,
client_id: &str,
id_token: &str,
refresh_token: String,
credentials: L,
http_client: Arc<dyn HttpClient>,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<EmaIdpIdentity<L>> {
if refresh_token.trim().is_empty() {
return Err(ema_reauthentication_required(
"Codex account has no refresh token; sign in again",
));
}
if idp.client_secret.is_some() && client_id != idp.client_id {
bail!("enterprise IdP client secret does not belong to the account OAuth client");
}
let issuer = &idp.issuer;
let client_secret = idp.client_secret.as_ref().map(|secret| secret.as_str());
crate::ema_claims::oidc_identity(id_token, issuer, client_id)?;
let (token_endpoint, client_authentication) = resolve_ema_idp_token_endpoint(
issuer,
client_secret,
idp.token_endpoint_auth_method,
http_client,
redirect_mode,
)
.await
.context(EmaErrorDetail::new(
"enterprise IdP discovery or validation failed",
))?;
Ok(EmaIdpIdentity {
token_endpoint,
refresh_token,
credentials,
client_authentication,
})
}
/// Validate account ID-token bindings without treating an expired ID token as an expired grant.
pub fn account_oidc_identity_is_usable(id_token: &str, issuer: &str, client_id: &str) -> bool {
crate::ema_claims::oidc_identity(id_token, issuer, client_id).is_ok()
}
/// Only an explanatory legacy-login hint, never authority for RT exchange.
pub fn account_oidc_issuer_hint(id_token: &str, issuer: &str) -> bool {
crate::ema_claims::oidc_issuer_hint(id_token, issuer)
}
/// Returns whether stored credentials contain a refresh token bound to the configured login.
pub fn stored_ema_identity_is_usable(
tokens: &StoredOAuthTokens,
issuer: &str,
client_id: &str,
) -> bool {
tokens.url == issuer
&& tokens.bound_issuer() == Some(issuer)
&& tokens.client_id == client_id
&& tokens.has_refresh_token()
&& stored_oidc_identity(tokens).is_ok()
}
pub(crate) async fn resolve_ema_idp_authorization_manager(
issuer: &str,
http_client: Arc<dyn OAuthHttpClient>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<(
AuthorizationManager,
AuthorizationMetadata,
EmaClientAuthentication,
)> {
validate_ema_oauth_endpoint(issuer, "enterprise IdP issuer")?;
let mut manager = AuthorizationManager::new_with_oauth_http_client(issuer, http_client)
.await
.context("failed to create enterprise IdP metadata discovery client")?;
manager.set_allow_missing_issuer(false);
let resolution = manager
.resolve_metadata()
.await
.context(EmaErrorDetail::new(
"failed to discover enterprise IdP authorization metadata",
))?;
if !resolution.source.is_discovered() {
bail!(EmaErrorDetail::new(
"enterprise IdP must publish authorization metadata"
));
}
let metadata = resolution.metadata;
if metadata.issuer.as_deref() != Some(issuer) {
bail!(EmaErrorDetail::new(
"enterprise IdP authorization metadata issuer does not match configuration"
));
}
validate_ema_oauth_endpoint(&metadata.token_endpoint, "enterprise IdP token endpoint")?;
let authentication = resolve_ema_client_auth(
metadata
.additional_fields
.get("token_endpoint_auth_methods_supported"),
client_secret,
token_endpoint_auth_method,
"enterprise IdP",
)?;
Ok((manager, metadata, authentication))
}
/// Resolve a stored refresh-token subject against the configured enterprise IdP metadata.
pub async fn resolve_ema_idp_identity(
request: EmaIdpIdentityRequest<'_>,
) -> Result<EmaIdpIdentity> {
resolve_ema_idp_identity_in(request, &DefaultKeyringStore).await
}
async fn resolve_ema_idp_identity_in<K: KeyringStore + Clone + 'static>(
request: EmaIdpIdentityRequest<'_>,
keyring_store: &K,
) -> Result<EmaIdpIdentity> {
if request.issuer.trim().is_empty() || request.client_id.trim().is_empty() {
bail!("ema_auth requires a non-empty enterprise IdP issuer and client ID");
}
let credentials = request.credentials.credentials.credentials();
if credentials.url != request.issuer
|| credentials.bound_issuer() != Some(request.issuer)
|| credentials.client_id != request.client_id
{
bail!("stored enterprise IdP credentials do not match the configured issuer and client");
}
stored_oidc_identity(credentials)?;
let (token_endpoint, client_authentication) = resolve_ema_idp_token_endpoint(
request.issuer,
request.client_secret,
request.token_endpoint_auth_method,
request.http_client,
request.redirect_mode,
)
.await
.context(EmaErrorDetail::new(
"enterprise IdP discovery or validation failed",
))?;
let credentials = request.credentials;
let credential_lock = RefreshCredentialLock::acquire_for_server(
&credentials.credentials.credentials().server_name,
request.issuer,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
let keyring_store = keyring_store.clone();
// The worker retains the short read lock if its caller stops waiting for the reread.
tokio::task::spawn_blocking(move || {
let _credential_lock = credential_lock;
let latest = credentials
.credentials
.load_ema_credentials(&keyring_store)?;
let refresh_token = latest
.token_response
.0
.refresh_token()
.filter(|token| !token.secret().trim().is_empty())
.ok_or_else(|| {
ema_reauthentication_required(
"enterprise IdP session has no refresh token; sign in again",
)
})?;
Ok(EmaIdpIdentity {
token_endpoint,
refresh_token: refresh_token.secret().to_string(),
credentials,
client_authentication,
})
})
.await
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"enterprise IdP credential reread task failed"
))
})?
}
async fn resolve_ema_idp_token_endpoint(
issuer: &str,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
http_client: Arc<dyn HttpClient>,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<(String, EmaClientAuthentication)> {
let client = OAuthHttpClientAdapter::new_with_redirect_mode(
http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
issuer,
/*has_configured_headers*/ false,
redirect_mode,
)?;
let (_, metadata, authentication) = resolve_ema_idp_authorization_manager(
issuer,
Arc::new(client),
client_secret,
token_endpoint_auth_method,
)
.await?;
for (name, expected) in [
(
"identity_chaining_requested_token_types_supported",
ID_JAG_TOKEN_TYPE,
),
("grant_types_supported", TOKEN_EXCHANGE_GRANT_TYPE),
] {
if advertised_capability(metadata.additional_fields.get(name), expected, name)?
== Some(false)
{
bail!(
"enterprise IdP does not advertise the required ID-JAG token exchange capability"
);
}
}
Ok((metadata.token_endpoint, authentication))
}
#[cfg(test)]
#[path = "ema_identity_tests.rs"]
mod tests;

View File

@@ -0,0 +1,439 @@
use std::io;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_config::types::AuthKeyringBackendKind;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_keyring_store::CredentialStoreError;
use codex_keyring_store::tests::MockKeyringStore;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use pretty_assertions::assert_ne;
use serde_json::json;
use tokio::sync::oneshot;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::EmaAuthFailure;
use crate::WrappedOAuthTokenResponse;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::ResolvedOAuthCredentialStore;
use crate::oauth::StoredOAuthCredentialSnapshot;
use crate::oauth::test_support::TempCodexHome;
fn credentials(issuer: &str, subject: &str, expires_at: u64) -> StoredOAuthTokens {
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
serde_json::to_vec(&json!({
"iss":issuer,"aud":"idp-client","sub":subject,"exp":expires_at,
}))
.expect("claims")
)
);
StoredOAuthTokens {
server_name: "ema-idp:enterprise-test".to_string(),
url: issuer.to_string(),
issuer: Some(issuer.to_string()),
client_id: "idp-client".to_string(),
token_response: WrappedOAuthTokenResponse(
serde_json::from_value(json!({
"access_token":"unused","token_type":"Bearer","id_token":assertion,
"refresh_token":"stored-refresh","scope":"openid offline_access",
}))
.expect("credentials"),
),
expires_at: None,
}
}
fn request<'a>(
issuer: &'a str,
credentials: &'a StoredOAuthCredentialSnapshot,
) -> EmaIdpIdentityRequest<'a> {
EmaIdpIdentityRequest {
client_secret: None,
token_endpoint_auth_method: None,
issuer,
client_id: "idp-client",
credentials: EmaCredentialLease {
credentials: credentials.clone(),
},
http_client: Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
redirect_mode: StreamableHttpRedirectMode::Legacy,
}
}
async fn discovery() -> (MockServer, String) {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/idp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer":issuer,"authorization_endpoint":format!("{issuer}/authorize"),
"token_endpoint":format!("{issuer}/token"),
"identity_chaining_requested_token_types_supported":[ID_JAG_TOKEN_TYPE],
"grant_types_supported":[TOKEN_EXCHANGE_GRANT_TYPE],
"token_endpoint_auth_methods_supported":["none"],
})))
.mount(&server)
.await;
(server, issuer)
}
#[tokio::test]
async fn enterprise_discovery_shares_idp_checks_but_keeps_login_endpoint_policy() -> Result<()> {
for case in [
"valid",
"missing-discovery",
"issuer",
"missing-issuer",
"token-endpoint",
"public-client",
"authorization-endpoint",
] {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
// Login need not advertise ID-JAG exchange capabilities.
let mut metadata = json!({
"issuer": issuer, "authorization_endpoint": format!("{issuer}/authorize"),
"token_endpoint": format!("{issuer}/token"),
"token_endpoint_auth_methods_supported": ["none"],
"grant_types_supported": ["authorization_code"],
});
match case {
"issuer" => metadata["issuer"] = json!("https://other.example"),
"missing-issuer" => {
metadata.as_object_mut().expect("metadata").remove("issuer");
}
"token-endpoint" => metadata["token_endpoint"] = json!("http://unsafe.example/token"),
"public-client" => {
metadata["token_endpoint_auth_methods_supported"] = json!(["client_secret_basic"])
}
"authorization-endpoint" => {
metadata["authorization_endpoint"] = json!("http://unsafe.example/authorize")
}
"valid" | "missing-discovery" => {}
_ => unreachable!(),
}
if case != "missing-discovery" {
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/idp"))
.respond_with(ResponseTemplate::new(200).set_body_json(metadata))
.mount(&server)
.await;
}
let client = Arc::new(OAuthHttpClientAdapter::new_with_redirect_mode(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
&issuer,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)?);
let shared = resolve_ema_idp_authorization_manager(
&issuer,
client.clone(),
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
)
.await;
let login = crate::enterprise_oauth_login::resolve_enterprise_authorization_manager(
&issuer, client, /*client_secret*/ None, /*token_endpoint_auth_method*/ None,
)
.await;
assert_eq!(
(shared.is_ok(), login.is_ok()),
(
matches!(case, "valid" | "authorization-endpoint"),
case == "valid"
),
"{case}",
);
if case == "missing-discovery" {
assert_eq!(
shared
.err()
.expect("reject synthesized metadata")
.to_string(),
"enterprise IdP must publish authorization metadata",
);
}
}
Ok(())
}
const REREAD_TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
const REREAD_PANIC_SENTINEL: &str = "credential-panic-payload-sentinel";
#[derive(Clone, Copy, Debug)]
enum ReadOutcome {
Stored,
BackendError,
Panic,
}
#[derive(Clone, Debug)]
struct GatedKeyringStore {
inner: MockKeyringStore,
executor_thread: thread::ThreadId,
entered: Arc<Mutex<Option<oneshot::Sender<()>>>>,
release: Arc<Mutex<mpsc::Receiver<ReadOutcome>>>,
}
impl KeyringStore for GatedKeyringStore {
fn load(&self, service: &str, account: &str) -> Result<Option<String>, CredentialStoreError> {
// Fail before blocking if a regression puts this read on the current-thread executor.
assert_ne!(thread::current().id(), self.executor_thread);
if let Some(entered) = self
.entered
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
{
let _ = entered.send(());
}
let outcome = match self
.release
.lock()
.unwrap_or_else(PoisonError::into_inner)
.recv_timeout(REREAD_TEST_TIMEOUT)
{
Ok(outcome) => outcome,
Err(mpsc::RecvTimeoutError::Disconnected) => ReadOutcome::Stored,
Err(mpsc::RecvTimeoutError::Timeout) => panic!("credential reread gate timed out"),
};
match outcome {
ReadOutcome::Stored => self.inner.load(service, account),
ReadOutcome::BackendError => Err(CredentialStoreError::new(
keyring::Error::PlatformFailure(Box::new(io::Error::new(
io::ErrorKind::PermissionDenied,
"credential backend unavailable",
))),
)),
ReadOutcome::Panic => panic!("{REREAD_PANIC_SENTINEL}"),
}
}
fn save(&self, service: &str, account: &str, value: &str) -> Result<(), CredentialStoreError> {
self.inner.save(service, account, value)
}
fn delete(&self, service: &str, account: &str) -> Result<bool, CredentialStoreError> {
self.inner.delete(service, account)
}
}
#[tokio::test(flavor = "current_thread")]
async fn refresh_subject_reread_is_cancellable_and_releases_guard_on_failure() -> Result<()> {
let _home = TempCodexHome::new();
let (_server, issuer) = discovery().await;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let stored = credentials(&issuer, "user", /*expires_at*/ 0);
let snapshot = StoredOAuthCredentialSnapshot::new(stored.clone(), store);
for outcome in [
ReadOutcome::Stored,
ReadOutcome::BackendError,
ReadOutcome::Panic,
] {
let inner = MockKeyringStore::default();
store.save(&inner, &stored.server_name, &stored)?;
let (entered_tx, entered_rx) = oneshot::channel();
// Dropping the sole sender releases the worker on any early return or panic.
let (release_tx, release_rx) = mpsc::channel();
let keyring = GatedKeyringStore {
inner,
executor_thread: thread::current().id(),
entered: Arc::new(Mutex::new(Some(entered_tx))),
release: Arc::new(Mutex::new(release_rx)),
};
let request = request(&issuer, &snapshot);
crate::oauth::test_support::warm_http_client(request.http_client.as_ref()).await?;
let mut identity = Box::pin(resolve_ema_idp_identity_in(request, &keyring));
tokio::select! {
result = &mut identity => {
result?;
bail!("credential reread completed before its gate was released");
}
entered = tokio::time::timeout(REREAD_TEST_TIMEOUT, entered_rx) => { entered??; }
}
if matches!(outcome, ReadOutcome::Stored) {
// The caller times out while the already-started blocking read remains gated.
assert!(
tokio::time::timeout(Duration::ZERO, identity)
.await
.is_err()
);
assert!(
RefreshCredentialLock::acquire_for_server(&stored.server_name, &issuer)
.now_or_never()
.is_none()
);
release_tx.send(outcome)?;
} else {
release_tx.send(outcome)?;
let error = tokio::time::timeout(REREAD_TEST_TIMEOUT, identity)
.await?
.err()
.context("credential reread should fail")?;
if matches!(outcome, ReadOutcome::Panic) {
assert_eq!(
format!("{error:#}"),
"enterprise IdP credential reread task failed"
);
} else {
assert_eq!(
format!("{error:#}"),
"failed to read enterprise IdP credentials from keyring"
);
assert!(
!error
.chain()
.any(<dyn std::error::Error + 'static>::is::<io::Error>)
);
}
}
// Drain the detached read before TempCodexHome changes the process environment.
let _released = tokio::time::timeout(
REREAD_TEST_TIMEOUT,
RefreshCredentialLock::acquire_for_server(&stored.server_name, &issuer),
)
.await??;
}
Ok(())
}
#[tokio::test]
async fn refresh_subject_rereads_pinned_credentials_after_id_token_expiry() -> Result<()> {
let _home = TempCodexHome::new();
let (_server, issuer) = discovery().await;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let stored = credentials(&issuer, "user", /*expires_at*/ 0);
let snapshot = StoredOAuthCredentialSnapshot::new(stored.clone(), store);
let keyring = MockKeyringStore::default();
store.save(&keyring, &stored.server_name, &stored)?;
let identity = resolve_ema_idp_identity_in(request(&issuer, &snapshot), &keyring).await?;
assert_eq!(
(&identity.token_endpoint, identity.refresh_token.as_str()),
(&format!("{issuer}/token"), "stored-refresh")
);
let _released = RefreshCredentialLock::acquire_for_server(&stored.server_name, &issuer).await?;
Ok(())
}
#[tokio::test]
async fn refresh_subject_rejects_removed_replaced_or_missing_credentials() -> Result<()> {
let _home = TempCodexHome::new();
let (server, issuer) = discovery().await;
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let original = credentials(&issuer, "user", /*expires_at*/ 0);
for change in [
"deleted",
"subject",
"issuer",
"client",
"refresh",
"login",
"missing-refresh",
"file",
] {
let keyring = MockKeyringStore::default();
let snapshot = StoredOAuthCredentialSnapshot::new(
original.clone(),
if change == "file" {
ResolvedOAuthCredentialStore::file()
} else {
store
},
);
let mut latest = original.clone();
match change {
"subject" => latest = credentials(&issuer, "other-user", /*expires_at*/ 0),
"issuer" => latest.issuer = Some("https://other.example".to_string()),
"client" => latest.client_id = "other-client".to_string(),
"refresh" => {
latest
.token_response
.0
.set_refresh_token(Some(oauth2::RefreshToken::new(
"other-users-refresh".to_string(),
)))
}
"login" => latest = credentials(&issuer, "user", now + 3600),
"missing-refresh" => latest.token_response.0.set_refresh_token(None),
"deleted" | "file" => {}
_ => panic!("unexpected change"),
}
if change != "deleted" {
store.save(&keyring, &original.server_name, &latest)?;
}
let error = resolve_ema_idp_identity_in(request(&issuer, &snapshot), &keyring)
.await
.err()
.expect("must not reuse the stale snapshot or fall back to its ID token");
if change == "file" {
assert!(error.to_string().contains("require keyring storage"));
} else {
assert_eq!(
error.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::ReauthenticationRequired),
"{change}"
);
}
}
assert!(
server
.received_requests()
.await
.expect("requests")
.iter()
.all(|request| request.method.as_str() == "GET")
);
Ok(())
}
#[test]
fn stored_identity_usability_requires_a_bound_refresh_token_not_a_current_id_token() {
let issuer = "https://idp.example";
let expired = credentials(issuer, "user", /*expires_at*/ 0);
assert!(stored_ema_identity_is_usable(
&expired,
issuer,
"idp-client"
));
for change in ["url", "issuer", "client", "refresh"] {
let mut changed = expired.clone();
match change {
"url" => changed.url = "https://other.example".to_string(),
"issuer" => changed.issuer = Some("https://other.example".to_string()),
"client" => changed.client_id = "other-client".to_string(),
"refresh" => changed.token_response.0.set_refresh_token(None),
_ => panic!("unexpected change"),
}
assert!(!stored_ema_identity_is_usable(
&changed,
issuer,
"idp-client"
));
}
}

View File

@@ -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,
})
}

View File

@@ -0,0 +1,446 @@
//! Enterprise OIDC policy and staged, keyring-only credential commits.
//! Browser completion never persists a grant; its owner revalidates authority under the commit lock.
use std::future::Future;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::sync::Arc;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
use http::Method;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthHttpClient;
use rmcp::transport::auth::OAuthHttpClientFuture;
use rmcp::transport::auth::OAuthHttpRequest;
use tracing::instrument::WithSubscriber;
use url::Host;
use url::Url;
use crate::EmaErrorDetail;
use crate::StoredOAuthTokens;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::ema_claims::validate_oidc_identity_assertion;
use crate::ema_identity::resolve_ema_idp_authorization_manager;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth::EnterpriseOAuthGeneration;
use crate::oauth::EnterpriseOAuthGenerationFile;
use crate::oauth::EnterpriseOAuthGenerationKind;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::delete_oauth_tokens_with_lock_held;
use crate::oauth::save_oauth_tokens_with_lock_held;
use crate::oauth::validate_authorization_server_endpoints;
use crate::oauth_client_registration::McpOAuthClientRegistration;
use crate::perform_oauth_login::OAuthHttpContext;
use crate::perform_oauth_login::OAuthLoginPurpose;
use crate::perform_oauth_login::OauthLoginFlow;
/// An exclusive credential mutation guard. Hold it through primary account logout
/// so a competing process cannot commit between deleting the grant and signing out.
/// Coordination, like ordinary OAuth refresh, is scoped to the same CODEX_HOME.
pub struct EnterpriseOAuthCredentialGuard {
credential_name: String,
issuer: String,
keyring_backend: AuthKeyringBackendKind,
generation_file: EnterpriseOAuthGenerationFile,
_lock: RefreshCredentialLock,
}
impl EnterpriseOAuthCredentialGuard {
pub async fn acquire(
credential_name: &str,
issuer: &str,
keyring_backend: AuthKeyringBackendKind,
) -> Result<Self> {
let lock = RefreshCredentialLock::acquire_for_server(credential_name, issuer)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!("failed to lock enterprise credentials"))?;
let generation_file = EnterpriseOAuthGenerationFile::open(
credential_name,
issuer,
EnterpriseOAuthGenerationKind::LoginAttempt,
&lock,
)
.map_err(|_| anyhow!("failed to open enterprise login generation"))?;
Ok(Self {
credential_name: credential_name.to_owned(),
issuer: issuer.to_owned(),
keyring_backend,
generation_file,
_lock: lock,
})
}
/// Invalidate pending logins and delete the grant, if present. A false return
/// means no grant was stored; earlier login attempts are still invalidated.
pub fn delete_tokens(&self) -> Result<bool> {
// Invalidate attempts that have not stored a grant yet, including other processes.
// Persist before deletion so no successful logout can admit an earlier login.
self.generation_file
.replace()
.map_err(|_| anyhow!("failed to invalidate pending enterprise sign-ins"))?;
// Underlying keyring diagnostics include the account-scoped key. Suppress
// them and discard their error chain, not merely the outer error message.
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
delete_oauth_tokens_with_lock_held(
&self._lock,
&self.credential_name,
&self.issuer,
OAuthCredentialsStoreMode::Keyring,
self.keyring_backend,
)
})
.map_err(|_| anyhow!("failed to delete enterprise credentials"))
}
}
/// Invalidate earlier enterprise logins across processes, then delete any stored grant.
pub async fn delete_enterprise_oauth_tokens(
credential_name: &str,
issuer: &str,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<bool> {
EnterpriseOAuthCredentialGuard::acquire(credential_name, issuer, keyring_backend_kind)
.await?
.delete_tokens()
}
/// A browser login with no detached persistence worker. Dropping this handle or
/// its wait future unblocks the callback listener and cannot write credentials.
pub struct EnterpriseOAuthLoginHandle {
flow: OauthLoginFlow,
keyring_backend: AuthKeyringBackendKind,
generation: EnterpriseOAuthGeneration,
}
impl EnterpriseOAuthLoginHandle {
pub fn authorization_url(&self) -> String {
self.flow.authorization_url()
}
/// Capture before waiting; after the handle or wait future is dropped, await
/// this to ensure the callback worker released its listener before rebinding.
pub fn callback_closed(&self) -> impl Future<Output = ()> + Send + 'static {
self.flow.callback_closed()
}
pub async fn wait(self) -> Result<EnterpriseOAuthCredentials> {
let stored = self
.flow
.complete(/*emit_browser_url*/ false)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("enterprise IdP authorization failed")))?;
validate_enterprise_credentials(&stored)?;
Ok(EnterpriseOAuthCredentials {
stored,
keyring_backend: self.keyring_backend,
generation: self.generation,
})
}
}
/// A validated grant that is not yet stored. It intentionally does not expose tokens.
pub struct EnterpriseOAuthCredentials {
stored: StoredOAuthTokens,
keyring_backend: AuthKeyringBackendKind,
generation: EnterpriseOAuthGeneration,
}
impl EnterpriseOAuthCredentials {
/// Revalidate the current attempt, account and configuration under the same
/// exclusive lock used by logout, then persist without an intervening await.
/// Return the authority proof so the caller can retire its attempt while still
/// holding the commit gate, before notifying clients or refreshing runtimes.
pub async fn commit_if<F, Fut, T>(self, is_current: F) -> Result<T>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Option<T>>,
{
let guard = EnterpriseOAuthCredentialGuard::acquire(
&self.stored.server_name,
&self.stored.url,
self.keyring_backend,
)
.await?;
let generation = guard.generation_file.current().map_err(|_| {
anyhow!(EmaErrorDetail::new(
"failed to read enterprise login generation"
))
})?;
if generation.as_ref() != Some(&self.generation) {
bail!(EmaErrorDetail::new(
"enterprise sign-in was invalidated by logout"
));
}
let Some(authority) = is_current().await else {
bail!(EmaErrorDetail::new(
"enterprise sign-in no longer matches the active account or configuration"
));
};
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
save_oauth_tokens_with_lock_held(
&guard._lock,
&self.stored.server_name,
&self.stored,
OAuthCredentialsStoreMode::Keyring,
self.keyring_backend,
)
})
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"failed to store enterprise credentials"
))
})?;
Ok(authority)
}
}
/// Start a host-registered enterprise login without launching the browser or
/// persisting a credential. The caller owns both the attempt and its later commit.
pub async fn perform_enterprise_oauth_login_return_url(
request: EnterpriseOAuthLoginRequest<'_>,
) -> Result<EnterpriseOAuthLoginHandle> {
let observed_generation = {
let guard = EnterpriseOAuthCredentialGuard::acquire(
request.credential_name,
request.issuer,
request.keyring_backend_kind,
)
.await?;
guard
.generation_file
.current()
.map_err(|_| anyhow!("failed to read enterprise login generation"))?
};
let flow = OauthLoginFlow::new(
request.credential_name,
request.issuer,
OAuthCredentialsStoreMode::Keyring,
request.keyring_backend_kind,
OAuthHttpContext {
http_headers: None,
env_http_headers: None,
http_client: request.http_client,
redirect_mode: request.redirect_mode,
},
&["openid".to_string(), "offline_access".to_string()],
Some(&codex_config::McpServerOAuthConfig {
client_id: Some(request.client_id.to_string()),
client_secret: request.client_secret.map(Into::into),
token_endpoint_auth_method: request.token_endpoint_auth_method,
..Default::default()
}),
OAuthLoginPurpose::EnterpriseIdp,
McpOAuthClientRegistration::Auto,
/*oauth_resource*/ None,
/*launch_browser*/ false,
request.callback_port,
request.callback_url,
/*global_callback_url*/ None,
request.timeout_secs,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|error| {
if error.downcast_ref::<EmaErrorDetail>().is_some() {
return EmaErrorDetail::from_error(&error);
}
EmaErrorDetail::from_error(&error.context(EmaErrorDetail::new(
"failed to start enterprise IdP authorization",
)))
})?;
// Keep the current attempt valid until replacement setup succeeds. A logout
// or another completed setup during this work must still invalidate this start.
let generation = async {
let guard = EnterpriseOAuthCredentialGuard::acquire(
request.credential_name,
request.issuer,
request.keyring_backend_kind,
)
.await?;
let current_generation = guard
.generation_file
.current()
.map_err(|_| anyhow!("failed to read enterprise login generation"))?;
if current_generation != observed_generation {
bail!("enterprise login changed during replacement setup");
}
guard
.generation_file
.replace()
.map_err(|_| anyhow!("failed to start enterprise login generation"))
}
.await;
let generation = match generation {
Ok(generation) => generation,
Err(error) => {
let callback_closed = flow.callback_closed();
drop(flow);
callback_closed.await;
return Err(error);
}
};
Ok(EnterpriseOAuthLoginHandle {
flow,
keyring_backend: request.keyring_backend_kind,
generation,
})
}
pub(crate) fn enterprise_callback_settings(
issuer: &str,
client_id: Option<&str>,
callback_url: Option<&str>,
callback_port: Option<u16>,
) -> Result<(IpAddr, Option<u16>)> {
validate_ema_oauth_endpoint(issuer, "enterprise IdP issuer")?;
if client_id.is_none_or(|client_id| client_id.trim().is_empty()) {
bail!("enterprise IdP login requires its registered client ID");
}
let (ip, registered_port) = if let Some(callback_url) = callback_url {
validate_ema_oauth_endpoint(callback_url, "enterprise IdP callback URL")?;
let callback = Url::parse(callback_url)?;
let ip = match (callback.scheme(), callback.host()) {
("http", Some(Host::Domain("localhost"))) => Ipv4Addr::LOCALHOST.into(),
("http", Some(Host::Ipv4(ip))) if ip.is_loopback() => ip.into(),
("http", Some(Host::Ipv6(ip))) if ip.is_loopback() => ip.into(),
_ => bail!("enterprise IdP callback URL must use an HTTP loopback address"),
};
(ip, callback.port())
} else {
(Ipv4Addr::LOCALHOST.into(), None)
};
if callback_port
.zip(registered_port)
.is_some_and(|(configured, registered)| configured != registered)
{
bail!("enterprise IdP callback URL and listener specify different ports");
}
Ok((ip, callback_port.or(registered_port)))
}
fn validate_enterprise_credentials(stored: &StoredOAuthTokens) -> Result<()> {
if !stored.has_refresh_token() {
bail!("enterprise IdP login did not return a refresh token");
}
let assertion = stored
.token_response
.0
.extra_fields()
.0
.get("id_token")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| anyhow!("enterprise IdP login did not return an OIDC identity assertion"))?;
validate_oidc_identity_assertion(
assertion,
stored.issuer.as_deref().unwrap_or(&stored.url),
&stored.client_id,
)
.map_err(|_| anyhow!("enterprise IdP returned an invalid OIDC identity assertion"))
}
pub(crate) async fn resolve_enterprise_authorization_manager(
issuer: &str,
http_client: Arc<dyn OAuthHttpClient>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<(AuthorizationManager, AuthorizationMetadata)> {
let (manager, mut metadata, _) = resolve_ema_idp_authorization_manager(
issuer,
Arc::new(EnterpriseOAuthHttpClient(http_client)),
client_secret,
token_endpoint_auth_method,
)
.await?;
if client_secret.is_some() {
// The SDK chooses Basic when both methods are advertised. Its login client
// must use the validated registration method, just like the EMA exchanges.
metadata.additional_fields.insert(
"token_endpoint_auth_methods_supported".to_owned(),
serde_json::json!([token_endpoint_auth_method.unwrap_or_default().as_str()]),
);
}
validate_authorization_server_endpoints(&metadata)?;
validate_ema_oauth_endpoint(
&metadata.authorization_endpoint,
"enterprise IdP authorization endpoint",
)?;
Ok((manager, metadata))
}
pub(crate) fn enterprise_authorization_url(auth_url: &str) -> Result<String> {
let mut url = Url::parse(auth_url)?;
let query = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(
url.query_pairs()
.filter(|(key, _)| key != "resource" && key != "prompt"),
)
.append_pair("prompt", "consent")
.finish();
url.set_query(Some(&query));
Ok(url.to_string())
}
/// rmcp supplies a resource indicator for MCP OAuth, but the independent OIDC
/// login must not request the IdP issuer as a protected-resource audience.
struct EnterpriseOAuthHttpClient(Arc<dyn OAuthHttpClient>);
impl OAuthHttpClient for EnterpriseOAuthHttpClient {
fn execute(&self, mut request: OAuthHttpRequest) -> OAuthHttpClientFuture<'_> {
if request.request.method() == Method::POST
&& request
.request
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
value.split(';').next().is_some_and(|mime| {
mime.trim()
.eq_ignore_ascii_case("application/x-www-form-urlencoded")
})
})
&& url::form_urlencoded::parse(request.request.body())
.any(|(key, value)| key == "grant_type" && value == "authorization_code")
{
let body = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(
url::form_urlencoded::parse(request.request.body())
.filter(|(key, _)| key != "resource"),
)
.finish();
*request.request.body_mut() = body.into_bytes();
request.request.headers_mut().remove(CONTENT_LENGTH);
}
self.0.execute(request)
}
}
/// Enterprise registration and host-owned login settings. The flow always uses
/// OpenID Connect, strict issuer validation, and keyring-only credential storage.
pub struct EnterpriseOAuthLoginRequest<'a> {
pub credential_name: &'a str,
pub issuer: &'a str,
pub client_id: &'a str,
pub client_secret: Option<&'a str>,
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
pub keyring_backend_kind: AuthKeyringBackendKind,
pub callback_port: Option<u16>,
pub callback_url: Option<&'a str>,
pub timeout_secs: Option<i64>,
pub http_client: Arc<dyn HttpClient>,
pub redirect_mode: StreamableHttpRedirectMode,
}
#[cfg(test)]
#[path = "enterprise_oauth_login_tests.rs"]
mod tests;

View File

@@ -0,0 +1,617 @@
//! Enterprise login exercises the real callback and keyring adapter in an isolated process.
use std::any::Any;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use keyring::credential::Credential;
use keyring::credential::CredentialApi;
use keyring::credential::CredentialBuilderApi;
use keyring::credential::CredentialPersistence;
use keyring::mock::MockCredential;
use oauth2::TokenResponse;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tracing_test::traced_test;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
const SECRET: &str = "enterprise-secret-sentinel";
const CLIENT_SECRET: &str = "client-secret-sentinel";
const CREDENTIAL_NAME: &str = "ema-idp:enterprise-secret-sentinel";
#[path = "enterprise_oauth_logout_tests.rs"]
mod logout;
async fn isolated_process(test_name: &str) -> Result<bool> {
const CHILD: &str = "CODEX_ENTERPRISE_LOGIN_TEST_CHILD";
if std::env::var_os(CHILD).is_some() {
return Ok(false);
}
let home = tempfile::tempdir()?;
let output = tokio::process::Command::new(std::env::current_exe()?)
.args(["--exact", test_name, "--nocapture"])
.env(CHILD, "1")
.env("CODEX_HOME", home.path())
.current_dir(home.path())
.output()
.await?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(true)
}
async fn login(
issuer: &str,
callback_url: Option<&str>,
auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<EnterpriseOAuthLoginHandle> {
perform_enterprise_oauth_login_return_url(EnterpriseOAuthLoginRequest {
client_secret: auth_method.map(|_| CLIENT_SECRET),
token_endpoint_auth_method: auth_method,
credential_name: CREDENTIAL_NAME,
issuer,
client_id: "enterprise-client",
keyring_backend_kind: AuthKeyringBackendKind::Direct,
callback_port: None,
callback_url,
timeout_secs: Some(5),
http_client: Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
redirect_mode: StreamableHttpRedirectMode::Legacy,
})
.await
}
async fn complete_login(issuer: &str) -> Result<EnterpriseOAuthCredentials> {
let handle = login(
issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await?;
callback(
&handle.authorization_url(),
issuer,
/*provider_error*/ false,
)
.await?;
handle.wait().await
}
async fn metadata(server: &MockServer, issuer: &str) {
Mock::given(method("GET")).and(path("/.well-known/oauth-authorization-server/idp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": issuer, "authorization_endpoint": format!("{issuer}/authorize?prompt=none"),
"token_endpoint": format!("{issuer}/token"), "token_endpoint_auth_methods_supported": ["none", "client_secret_basic", "client_secret_post"],
}))).mount(server).await;
}
async fn callback(authorization_url: &str, issuer: &str, provider_error: bool) -> Result<()> {
let query = Url::parse(authorization_url)?
.query_pairs()
.into_owned()
.collect::<HashMap<_, _>>();
assert_eq!(query.get("prompt").map(String::as_str), Some("consent"));
assert!(!query.contains_key("resource"));
let mut callback = Url::parse(&query["redirect_uri"])?;
let mut pairs = callback.query_pairs_mut();
if provider_error {
pairs
.append_pair("error", SECRET)
.append_pair("error_description", SECRET);
} else {
pairs
.append_pair("code", SECRET)
.append_pair("state", &query["state"])
.append_pair("iss", issuer);
}
drop(pairs);
let port = callback.port().expect("actual listener port");
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await?;
stream
.write_all(
format!(
"GET {}?{} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n",
callback.path(),
callback.query().expect("query")
)
.as_bytes(),
)
.await?;
stream.read_to_end(&mut Vec::new()).await?;
Ok(())
}
#[traced_test]
#[tokio::test]
async fn enterprise_callback_errors_and_sdk_logs_exclude_credentials() -> Result<()> {
if isolated_process(
"enterprise_oauth_login::tests::enterprise_callback_errors_and_sdk_logs_exclude_credentials",
)
.await?
{
return Ok(());
}
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &format!("https://{SECRET}.example/idp")).await;
let error = login(
&issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await
.err()
.expect("reject mismatched discovery issuer");
assert_eq!(
error.downcast_ref::<EmaErrorDetail>(),
Some(&EmaErrorDetail::new(
"failed to discover enterprise IdP authorization metadata"
))
);
assert!(!format!("{error} {error:?} {error:#}").contains(SECRET));
for (callback_error, token_success) in [(true, false), (false, false), (false, true)] {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &issuer).await;
let response = if token_success {
ResponseTemplate::new(200).set_body_json(json!({
"access_token": SECRET, "refresh_token": SECRET, "id_token": SECRET, "token_type": "Bearer",
}))
} else {
ResponseTemplate::new(400)
.set_body_json(json!({"error": "invalid_grant", "error_description": SECRET}))
};
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(response)
.expect(u64::from(!callback_error))
.mount(&server)
.await;
let login = login(
&issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await?;
callback(&login.authorization_url(), &issuer, callback_error).await?;
tracing::trace!(target: "rmcp::transport::auth", "SDK trace capture enabled");
let error = login.wait().await.err().expect("reject provider response");
assert!(!format!("{error} {error:?} {error:#}").contains(SECRET));
assert!(logs_contain("SDK trace capture enabled"));
assert!(!logs_contain(SECRET));
}
Ok(())
}
#[test]
fn enterprise_callback_requires_loopback() -> Result<()> {
let issuer = "https://idp.example";
let client_id = Some("enterprise-client");
for (callback, port, expected_ip, expected_port) in [
(None, None, "127.0.0.1", None),
(None, Some(8080), "127.0.0.1", Some(8080)),
(Some("http://localhost/callback"), None, "127.0.0.1", None),
(Some("http://127.0.0.2/callback"), None, "127.0.0.2", None),
(Some("http://[::1]/callback"), None, "::1", None),
(
Some("http://localhost:8080/callback"),
None,
"127.0.0.1",
Some(8080),
),
(
Some("http://localhost:8080/callback"),
Some(8080),
"127.0.0.1",
Some(8080),
),
] {
assert_eq!(
enterprise_callback_settings(issuer, client_id, callback, port)?,
(expected_ip.parse::<IpAddr>()?, expected_port),
);
}
for callback in [
"http://0.0.0.0/callback",
"http://[::]/callback",
"https://127.0.0.1/callback",
"http://remote.example/callback",
] {
assert!(
enterprise_callback_settings(
issuer,
client_id,
Some(callback),
/*callback_port*/ None
)
.is_err()
);
}
assert!(
enterprise_callback_settings(
issuer,
client_id,
Some("http://localhost:8080/callback"),
Some(9090),
)
.is_err()
);
Ok(())
}
#[traced_test]
#[tokio::test]
async fn enterprise_public_api_storage_and_privacy() -> Result<()> {
if isolated_process("enterprise_oauth_login::tests::enterprise_public_api_storage_and_privacy")
.await?
{
return Ok(());
}
let keyring = TestKeyring::default();
keyring::set_default_credential_builder(Box::new(keyring.clone()));
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &issuer).await;
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({"iss":issuer,"sub":"user","aud":"enterprise-client","exp":4102444800_u64})
.to_string()
)
);
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token":SECRET,"refresh_token":SECRET,"id_token":assertion,"token_type":"Bearer",
})))
.mount(&server)
.await;
// Callback, exchange and DefaultKeyringStore all run through public entrypoints.
use McpEmaTokenEndpointAuthMethod::ClientSecretBasic;
use McpEmaTokenEndpointAuthMethod::ClientSecretPost;
for (login_index, (callback_url, auth_method)) in [
("http://localhost/callback", None),
("http://127.0.0.1/callback", None),
("http://localhost/callback", Some(ClientSecretBasic)),
("http://127.0.0.1/callback", Some(ClientSecretPost)),
]
.into_iter()
.enumerate()
{
let login = login(&issuer, Some(callback_url), auth_method).await?;
let authorization_url = login.authorization_url();
assert!(!authorization_url.contains(CLIENT_SECRET));
let authorization_query = Url::parse(&authorization_url)?
.query_pairs()
.into_owned()
.collect::<HashMap<_, _>>();
callback(&authorization_url, &issuer, /*provider_error*/ false).await?;
let credentials = login.wait().await?;
let token_requests = server
.received_requests()
.await
.expect("recorded OAuth requests")
.into_iter()
.filter(|request| {
request.method == http::Method::POST && request.url.path() == "/idp/token"
})
.collect::<Vec<_>>();
assert_eq!(token_requests.len(), login_index + 1);
let token_request = &token_requests[login_index];
let mut token_form = url::form_urlencoded::parse(&token_request.body)
.into_owned()
.collect::<HashMap<_, _>>();
let authorization = token_request
.headers
.get("authorization")
.map(|value| value.to_str().unwrap());
let expected_basic = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD
.encode(format!("enterprise-client:{CLIENT_SECRET}"))
);
assert_eq!(
authorization,
(auth_method == Some(ClientSecretBasic)).then_some(expected_basic.as_str())
);
assert_eq!(
token_form.remove("client_secret").as_deref(),
(auth_method == Some(ClientSecretPost)).then_some(CLIENT_SECRET)
);
assert_eq!(
token_form.remove("client_id").as_deref(),
(auth_method != Some(ClientSecretBasic)).then_some("enterprise-client")
);
let verifier = oauth2::PkceCodeVerifier::new(
token_form.remove("code_verifier").expect("PKCE verifier"),
);
assert_eq!(
oauth2::PkceCodeChallenge::from_code_verifier_sha256(&verifier).as_str(),
authorization_query["code_challenge"],
);
assert_eq!(authorization_query["code_challenge_method"], "S256");
assert_eq!(
token_form,
HashMap::from([
("grant_type".to_string(), "authorization_code".to_string()),
("code".to_string(), SECRET.to_string()),
(
"redirect_uri".to_string(),
authorization_query["redirect_uri"].clone()
),
])
);
assert!(
keyring
.values
.lock()
.unwrap()
.values()
.all(|value| value.get_secret().is_err())
);
let attempt = tokio::sync::Mutex::new(Some("active"));
{
let mut authority = credentials
.commit_if(|| async { Some(attempt.lock().await) })
.await?;
assert!(
attempt.try_lock().is_err(),
"commit retains the attempt gate until the caller retires it"
);
*authority = None;
}
assert_eq!(*attempt.lock().await, None);
let stored = tracing::subscriber::with_default(
tracing::subscriber::NoSubscriber::default(),
|| {
crate::stored_oauth_credentials(
CREDENTIAL_NAME,
&issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
},
)?
.expect("stored grant");
assert!(!serde_json::to_string(&stored)?.contains(CLIENT_SECRET));
assert!(!logs_contain(CLIENT_SECRET));
assert_eq!(
stored
.token_response
.0
.refresh_token()
.map(|token| token.secret().as_str()),
Some(SECRET)
);
// Exercise the production lease and keyring snapshot without installing another
// test backend. Use a non-sensitive name so routine keyring-read traces are safe.
let mut lease_tokens = stored.clone();
lease_tokens.server_name = "ema-idp:lease-snapshot".to_string();
crate::save_oauth_tokens(
&lease_tokens.server_name,
&lease_tokens,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
.await?;
let snapshot = crate::stored_oauth_credential_snapshot(
&lease_tokens.server_name,
&issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?
.expect("keyring-backed snapshot");
let pinned = snapshot.clone().pin_ema_credentials().await?;
let accesses = keyring.accesses.load(Ordering::SeqCst);
keyring.fail.store(true, Ordering::SeqCst);
let leases = futures::future::try_join_all(
(0..32).map(|_| pinned.acquire_current_ema_credentials()),
)
.await?;
assert_eq!(keyring.accesses.load(Ordering::SeqCst), accesses);
drop(leases);
keyring.fail.store(false, Ordering::SeqCst);
// Even an identical replacement, or a failed write, revokes the old version.
for fail in [false, true] {
let pinned = snapshot.clone().pin_ema_credentials().await?;
keyring.fail.store(fail, Ordering::SeqCst);
let saved = crate::save_oauth_tokens(
&lease_tokens.server_name,
&lease_tokens,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
.await;
keyring.fail.store(false, Ordering::SeqCst);
assert_eq!(saved.is_err(), fail);
assert!(pinned.acquire_current_ema_credentials().await.is_err());
}
let pinned = snapshot.pin_ema_credentials().await?;
let first = pinned.acquire_current_ema_credentials().await?;
let second = pinned.acquire_current_ema_credentials().await?;
assert!(
tokio::time::timeout(
Duration::from_secs(5),
delete_enterprise_oauth_tokens(
&lease_tokens.server_name,
&issuer,
AuthKeyringBackendKind::Direct,
),
)
.await??
);
drop(first);
drop(second);
assert!(pinned.acquire_current_ema_credentials().await.is_err());
assert!(
delete_enterprise_oauth_tokens(
CREDENTIAL_NAME,
&issuer,
AuthKeyringBackendKind::Direct
)
.await?
);
}
// Cancellation while blocked on the actual credential lock cannot leave a
// detached persistence worker that writes after the other process releases it.
let canceled = complete_login(&issuer).await?;
let guard = EnterpriseOAuthCredentialGuard::acquire(
CREDENTIAL_NAME,
&issuer,
AuthKeyringBackendKind::Direct,
)
.await?;
let mut commit = Box::pin(canceled.commit_if(|| async { Some(()) }));
assert!(futures::poll!(&mut commit).is_pending());
drop(commit);
drop(guard);
assert!(
keyring
.values
.lock()
.unwrap()
.values()
.all(|value| value.get_secret().is_err())
);
// Failed replacement setup leaves the existing attempt valid.
let retained = complete_login(&issuer).await?;
assert!(
login(
&issuer,
Some(&format!("{}/callback", server.uri())),
/*auth_method*/ None
)
.await
.is_err(),
"an occupied registered callback port must not silently move"
);
retained.commit_if(|| async { Some(()) }).await?;
// A newer start fences a delayed callback even across Codex processes.
let old = complete_login(&issuer).await?;
complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await?;
assert!(old.commit_if(|| async { Some(()) }).await.is_err());
assert!(
keyring
.values
.lock()
.unwrap()
.values()
.any(|value| value.get_secret().is_ok())
);
// Inject raw account identifiers into the actual keyring adapter's error chain.
keyring.fail.store(true, Ordering::SeqCst);
let save_error = complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await
.unwrap_err();
let delete_error =
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await
.unwrap_err();
let save_error = save_error.context(EmaErrorDetail::new(
"enterprise sign-in credential commit failed",
));
assert_eq!(
EmaErrorDetail::from_error(&save_error).to_string(),
"failed to store enterprise credentials"
);
for error in [save_error, delete_error] {
assert!(!format!("{error} {error:?} {error:#}").contains(SECRET));
}
keyring.fail.store(false, Ordering::SeqCst);
let home = std::path::PathBuf::from(std::env::var("CODEX_HOME")?);
assert!(
!home.join(".credentials.json").exists(),
"enterprise storage never falls back to plaintext"
);
let locks = home.join("mcp-oauth-locks");
std::fs::rename(&locks, home.join("held-locks"))?;
std::fs::write(&locks, b"not a directory")?;
let lock_error =
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await
.unwrap_err();
assert!(!format!("{lock_error} {lock_error:?} {lock_error:#}").contains(SECRET));
assert!(!logs_contain(SECRET));
Ok(())
}
#[derive(Clone, Default)]
struct TestKeyring {
values: Arc<Mutex<HashMap<String, Arc<MockCredential>>>>,
fail: Arc<AtomicBool>,
accesses: Arc<AtomicUsize>,
}
struct TestCredential(Arc<MockCredential>);
impl CredentialApi for TestCredential {
fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
self.0.set_secret(secret)
}
fn get_secret(&self) -> keyring::Result<Vec<u8>> {
self.0.get_secret()
}
fn delete_credential(&self) -> keyring::Result<()> {
self.0.delete_credential()
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl CredentialBuilderApi for TestKeyring {
fn build(
&self,
_target: Option<&str>,
_service: &str,
user: &str,
) -> keyring::Result<Box<Credential>> {
self.accesses.fetch_add(1, Ordering::SeqCst);
if self.fail.load(Ordering::SeqCst) {
return Err(keyring::Error::Invalid("account".into(), user.into()));
}
Ok(Box::new(TestCredential(
self.values
.lock()
.unwrap()
.entry(user.into())
.or_default()
.clone(),
)))
}
fn as_any(&self) -> &dyn Any {
self
}
fn persistence(&self) -> CredentialPersistence {
CredentialPersistence::ProcessOnly
}
}

View File

@@ -0,0 +1,422 @@
//! Cross-process credential changes invalidate staged logins and cached EMA leases.
use std::fs;
use std::path::PathBuf;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use sha2::Digest;
use sha2::Sha256;
use tokio::sync::Notify;
use super::*;
#[tokio::test]
async fn failed_persistence_fences_old_snapshots_but_allows_fresh_pins() -> Result<()> {
if isolated_process("enterprise_oauth_login::tests::logout::failed_persistence_fences_old_snapshots_but_allows_fresh_pins").await? {
return Ok(());
}
let keyring = TestKeyring::default();
keyring::set_default_credential_builder(Box::new(keyring.clone()));
let issuer = "https://idp.example";
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({"iss":issuer,"sub":"user","aud":"enterprise-client","exp":4102444800_u64})
.to_string()
)
);
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": CREDENTIAL_NAME, "url": issuer, "issuer": issuer,
"client_id": "enterprise-client", "token_response": {
"access_token": SECRET, "refresh_token": SECRET, "id_token": assertion, "token_type": "Bearer"
}
}))?;
let mode = OAuthCredentialsStoreMode::Keyring;
let backend = AuthKeyringBackendKind::Direct;
crate::save_oauth_tokens(CREDENTIAL_NAME, &tokens, mode, backend).await?;
for operation in ["save", "delete"] {
let snapshot =
crate::stored_oauth_credential_snapshot(CREDENTIAL_NAME, issuer, mode, backend)?
.expect("stored grant")
.pin_ema_credentials()
.await?;
drop(snapshot.acquire_current_ema_credentials().await?);
// Fail the actual keyring mutation, after the public API advances the generation.
keyring
.values
.lock()
.unwrap()
.values()
.next()
.expect("credential")
.set_error(keyring::Error::PlatformFailure(Box::new(
std::io::Error::other("injected persistence failure"),
)));
let result = match operation {
"save" => crate::save_oauth_tokens(CREDENTIAL_NAME, &tokens, mode, backend).await,
"delete" => crate::delete_oauth_tokens(CREDENTIAL_NAME, issuer, mode, backend)
.await
.map(|_| ()),
_ => unreachable!(),
};
assert!(
result.is_err(),
"{operation} must report the storage failure"
);
assert!(
snapshot.acquire_current_ema_credentials().await.is_err(),
"{operation} must fence the old snapshot"
);
assert_eq!(stored(issuer)?, Some(tokens.clone()));
// A generation is not a deletion tombstone: a fresh connection may use the surviving grant.
let fresh =
crate::stored_oauth_credential_snapshot(CREDENTIAL_NAME, issuer, mode, backend)?
.expect("surviving grant")
.pin_ema_credentials()
.await?;
drop(fresh.acquire_current_ema_credentials().await?);
}
Ok(())
}
const TEST: &str =
"enterprise_oauth_login::tests::logout::logout_invalidates_pending_login_across_processes";
const LOGOUT_ISSUER: &str = "CODEX_ENTERPRISE_LOGOUT_TEST_ISSUER";
const REPLACE_CREDENTIAL: &str = "CODEX_ENTERPRISE_LOGOUT_TEST_REPLACE";
#[tokio::test]
async fn logout_invalidates_pending_login_across_processes() -> Result<()> {
if isolated_process(TEST).await? {
return Ok(());
}
let home = PathBuf::from(std::env::var("CODEX_HOME")?);
let keyring = FileKeyring(home.join("test-keyring"));
fs::create_dir_all(&keyring.0)?;
keyring::set_default_credential_builder(Box::new(keyring));
if let Ok(issuer) = std::env::var(LOGOUT_ISSUER) {
if std::env::var_os(REPLACE_CREDENTIAL).is_some() {
crate::save_oauth_tokens(
CREDENTIAL_NAME,
&stored(&issuer)?.expect("stored grant"),
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
.await?;
} else {
delete_enterprise_oauth_tokens(
CREDENTIAL_NAME,
&issuer,
AuthKeyringBackendKind::Direct,
)
.await?;
}
return Ok(());
}
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &issuer).await;
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({"iss":issuer,"sub":"user","aud":"enterprise-client","exp":4102444800_u64})
.to_string()
)
);
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token":SECRET,"refresh_token":SECRET,"id_token":assertion,"token_type":"Bearer",
})))
.mount(&server)
.await;
// A logout during provider setup must invalidate the in-flight start.
let paused_client = Arc::new(PausedSetupHttpClient {
inner: Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
should_pause: AtomicBool::new(true),
entered: Notify::new(),
release: Notify::new(),
});
let starting_client = Arc::clone(&paused_client);
let starting_issuer = issuer.clone();
let starting = tokio::spawn(async move {
perform_enterprise_oauth_login_return_url(EnterpriseOAuthLoginRequest {
client_secret: None,
token_endpoint_auth_method: None,
credential_name: CREDENTIAL_NAME,
issuer: &starting_issuer,
client_id: "enterprise-client",
keyring_backend_kind: AuthKeyringBackendKind::Direct,
callback_port: None,
callback_url: None,
timeout_secs: Some(5),
http_client: starting_client,
redirect_mode: StreamableHttpRedirectMode::Legacy,
})
.await
});
tokio::time::timeout(
std::time::Duration::from_secs(5),
paused_client.entered.notified(),
)
.await?;
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await?;
paused_client.release.notify_one();
let error = tokio::time::timeout(std::time::Duration::from_secs(5), starting)
.await??
.err()
.expect("logout must invalidate a start during provider setup");
assert_eq!(
error.to_string(),
"enterprise login changed during replacement setup"
);
// The first logout has no grant to delete. The second deletes the fresh grant
// from the previous iteration. Both must invalidate pending callbacks and staged grants.
for _ in 0..2 {
let pending = login(
&issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await?;
let staged = complete_login(&issuer).await?;
let output = tokio::process::Command::new(std::env::current_exe()?)
.args(["--exact", TEST, "--nocapture"])
.env(LOGOUT_ISSUER, &issuer)
.output()
.await?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(stored(&issuer)?.is_none());
// The logout process has exited; its invalidation must survive that exit.
assert!(staged.commit_if(|| async { Some(()) }).await.is_err());
assert!(stored(&issuer)?.is_none());
// A fresh login after logout remains usable, including for the same account.
complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await?;
let fresh = stored(&issuer)?.expect("fresh grant");
callback(
&pending.authorization_url(),
&issuer,
/*provider_error*/ false,
)
.await?;
assert!(
pending
.wait()
.await?
.commit_if(|| async { Some(()) })
.await
.is_err()
);
assert_eq!(stored(&issuer)?, Some(fresh));
}
// Even a byte-identical replacement in another process retires the cached
// version. Its next lease must fail after that process exits, as must logout.
for operation in ["replace", "delete"] {
let before = stored(&issuer)?;
let cached = crate::stored_oauth_credential_snapshot(
CREDENTIAL_NAME,
&issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?
.expect("keyring-backed snapshot")
.pin_ema_credentials()
.await?;
drop(cached.acquire_current_ema_credentials().await?);
let mut child = tokio::process::Command::new(std::env::current_exe()?);
child
.args(["--exact", TEST, "--nocapture"])
.env(LOGOUT_ISSUER, &issuer);
if operation == "replace" {
child.env(REPLACE_CREDENTIAL, "1");
}
let output = child.output().await?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(cached.acquire_current_ema_credentials().await.is_err());
assert_eq!(
stored(&issuer)?,
if operation == "replace" { before } else { None }
);
}
let stale = complete_login(&issuer).await?;
let generation_path = fs::read_dir(home.join("mcp-oauth-locks"))?
.filter_map(std::result::Result::ok)
.map(|entry| entry.path())
.find(|path| {
path.extension()
.is_some_and(|ext| ext == "enterprise-generation")
})
.expect("persistent generation");
fs::write(&generation_path, b"incomplete write")?;
assert!(stale.commit_if(|| async { Some(()) }).await.is_err());
assert!(
login(
&issuer, /*callback_url*/ None, /*auth_method*/ None
)
.await
.is_err()
);
// A lost marker never revives a pre-logout attempt or a pre-reset generation.
fs::remove_file(&generation_path)?;
let stale = complete_login(&issuer).await?;
fs::remove_file(&generation_path)?;
complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await?;
assert!(stale.commit_if(|| async { Some(()) }).await.is_err());
// Metadata failures are logout errors and must leave the stored grant intact.
let before = stored(&issuer)?;
let version_path = generation_path.with_extension("enterprise-credential-version");
let version = fs::read(&version_path)?;
fs::remove_file(&version_path)?;
fs::create_dir(&version_path)?;
let mode = OAuthCredentialsStoreMode::Keyring;
let backend = AuthKeyringBackendKind::Direct;
let mut replacement = before.clone().expect("stored grant");
replacement.client_id.push_str("-replacement");
let saved = crate::save_oauth_tokens(CREDENTIAL_NAME, &replacement, mode, backend).await;
assert!(saved.is_err());
assert_eq!(stored(&issuer)?, before);
let deleted = crate::delete_oauth_tokens(CREDENTIAL_NAME, &issuer, mode, backend).await;
assert!(deleted.is_err());
assert_eq!(stored(&issuer)?, before);
fs::remove_dir(&version_path)?;
fs::write(&version_path, version)?;
fs::remove_file(&generation_path)?;
fs::create_dir(&generation_path)?;
assert!(
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await
.is_err()
);
assert_eq!(stored(&issuer)?, before);
assert!(!home.join(".credentials.json").exists());
Ok(())
}
struct PausedSetupHttpClient {
inner: Arc<dyn HttpClient>,
should_pause: AtomicBool,
entered: Notify,
release: Notify,
}
impl PausedSetupHttpClient {
async fn pause_once(&self) {
if self.should_pause.swap(false, Ordering::SeqCst) {
self.entered.notify_one();
self.release.notified().await;
}
}
}
impl HttpClient for PausedSetupHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
async move {
self.pause_once().await;
self.inner.http_request(params).await
}
.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
async move {
self.pause_once().await;
self.inner.http_request_stream(params).await
}
.boxed()
}
}
fn stored(issuer: &str) -> Result<Option<StoredOAuthTokens>> {
crate::stored_oauth_credentials(
CREDENTIAL_NAME,
issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
}
// Only synthetic fixture credentials are persisted here. Every process still uses
// DefaultKeyringStore and the production credential lock, serializer and logout API.
struct FileKeyring(PathBuf);
struct FileCredential(PathBuf);
impl CredentialBuilderApi for FileKeyring {
fn build(
&self,
_target: Option<&str>,
_service: &str,
user: &str,
) -> keyring::Result<Box<Credential>> {
let name = format!("{:x}", Sha256::digest(user.as_bytes()));
Ok(Box::new(FileCredential(self.0.join(name))))
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl CredentialApi for FileCredential {
fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
fs::write(&self.0, secret).map_err(keyring_error)
}
fn get_secret(&self) -> keyring::Result<Vec<u8>> {
fs::read(&self.0).map_err(keyring_error)
}
fn delete_credential(&self) -> keyring::Result<()> {
fs::remove_file(&self.0).map_err(keyring_error)
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn keyring_error(error: std::io::Error) -> keyring::Error {
if error.kind() == std::io::ErrorKind::NotFound {
keyring::Error::NoEntry
} else {
keyring::Error::PlatformFailure(Box::new(error))
}
}

View File

@@ -0,0 +1,264 @@
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use rmcp::model::ClientRequest;
use rmcp::model::CustomNotification;
use rmcp::model::JsonRpcMessage;
use rmcp::model::RequestId;
use rmcp::model::ServerNotification;
use rmcp::service::RoleClient;
use rmcp::service::RxJsonRpcMessage;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::IntoTransport;
use rmcp::transport::Transport;
use tokio::sync::OwnedSemaphorePermit;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
use tracing::warn;
pub(crate) const MAX_EVENT_NOTIFICATION_BYTES: usize = 1024 * 1024;
const MAX_QUEUED_EVENT_NOTIFICATION_BYTES: usize = 2 * 1024 * 1024;
#[derive(Clone)]
pub(crate) struct EventNotificationSender {
notifications: mpsc::UnboundedSender<QueuedEventNotification>,
available_bytes: Arc<Semaphore>,
}
pub struct EventNotificationReceiver {
notifications: mpsc::UnboundedReceiver<QueuedEventNotification>,
available_bytes: Arc<Semaphore>,
}
struct QueuedEventNotification {
notification: CustomNotification,
_bytes: OwnedSemaphorePermit,
}
pub(crate) fn event_notification_channel() -> (EventNotificationSender, EventNotificationReceiver) {
let (notifications_tx, notifications_rx) = mpsc::unbounded_channel();
let available_bytes = Arc::new(Semaphore::new(MAX_QUEUED_EVENT_NOTIFICATION_BYTES));
(
EventNotificationSender {
notifications: notifications_tx,
available_bytes: Arc::clone(&available_bytes),
},
EventNotificationReceiver {
notifications: notifications_rx,
available_bytes,
},
)
}
impl EventNotificationSender {
fn send(&self, notification: CustomNotification, notification_bytes: usize) -> Result<(), ()> {
let bytes = u32::try_from(notification_bytes).map_err(|_| ())?;
let permit = Arc::clone(&self.available_bytes)
.try_acquire_many_owned(bytes)
.map_err(|_| ())?;
self.notifications
.send(QueuedEventNotification {
notification,
_bytes: permit,
})
.map_err(|_| ())
}
fn close(&self) {
self.available_bytes.close();
}
}
impl EventNotificationReceiver {
pub async fn recv(&mut self) -> Option<CustomNotification> {
self.notifications
.recv()
.await
.map(|queued| queued.notification)
}
}
impl Drop for EventNotificationReceiver {
fn drop(&mut self) {
self.available_bytes.close();
}
}
/// Consumes Plugin Runtime event notifications before rmcp can log their payloads.
pub(crate) fn capture_event_notifications<T, E, A>(
transport: T,
) -> impl Transport<RoleClient, Error = E> + 'static
where
T: IntoTransport<RoleClient, E, A>,
E: std::error::Error + Send + Sync + 'static,
{
EventNotificationTransport {
inner: transport.into_transport(),
routes: Arc::default(),
}
}
struct EventNotificationTransport<T> {
inner: T,
routes: Arc<Mutex<HashMap<RequestId, EventNotificationSender>>>,
}
impl<T> Transport<RoleClient> for EventNotificationTransport<T>
where
T: Transport<RoleClient> + 'static,
{
type Error = T::Error;
fn send(
&mut self,
mut message: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
let request_route = match &mut message {
JsonRpcMessage::Request(envelope) => match &mut envelope.request {
ClientRequest::CustomRequest(request) if request.method == "events/stream" => {
request
.extensions
.remove::<EventNotificationSender>()
.map(|sender| (envelope.id.clone(), sender))
}
_ => None,
},
JsonRpcMessage::Notification(envelope) => {
if let rmcp::model::ClientNotification::CancelledNotification(cancelled) =
&envelope.notification
&& let Some(request_id) = cancelled.params.request_id.as_ref()
&& let Some(route) = self
.routes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(request_id)
{
route.close();
}
None
}
JsonRpcMessage::Response(_) | JsonRpcMessage::Error(_) => None,
};
let route_id = request_route
.as_ref()
.map(|(request_id, _)| request_id.clone());
if let Some((request_id, sender)) = request_route
&& let Some(previous) = self
.routes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(request_id, sender)
{
previous.close();
}
let routes = Arc::clone(&self.routes);
let send = self.inner.send(message);
async move {
let result = send.await;
if result.is_err()
&& let Some(route_id) = route_id
&& let Some(route) = routes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&route_id)
{
route.close();
}
result
}
}
async fn receive(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
loop {
let message = self.inner.receive().await?;
if let Some(request_id) = response_id(&message) {
if let Some(route) = self
.routes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(request_id)
{
route.close();
}
return Some(message);
}
let JsonRpcMessage::Notification(envelope) = &message else {
return Some(message);
};
let ServerNotification::CustomNotification(notification) = &envelope.notification
else {
return Some(message);
};
if !notification.method.starts_with("notifications/events/") {
return Some(message);
}
let Some(subscription_id) =
rmcp::model::GetMeta::get_meta(notification).subscription_id()
else {
continue;
};
let route = self
.routes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&subscription_id)
.cloned();
let Some(route) = route else {
continue;
};
let notification_bytes = serde_json::to_vec(&message)
.map(|message| message.len())
.unwrap_or(usize::MAX);
if notification_bytes > MAX_EVENT_NOTIFICATION_BYTES {
warn!(
notification_bytes,
"discarding oversized MCP event notification"
);
continue;
}
if route
.send(notification.clone(), notification_bytes)
.is_err()
&& let Some(route) = self
.routes
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&subscription_id)
{
let _ = route.send(
CustomNotification::new(
"notifications/events/terminated",
/*params*/ None,
),
/*notification_bytes*/ 0,
);
route.close();
}
}
}
async fn close(&mut self) -> Result<(), Self::Error> {
let routes =
std::mem::take(&mut *self.routes.lock().unwrap_or_else(PoisonError::into_inner));
for route in routes.into_values() {
route.close();
}
self.inner.close().await
}
}
fn response_id(message: &RxJsonRpcMessage<RoleClient>) -> Option<&RequestId> {
match message {
JsonRpcMessage::Response(response) => Some(&response.id),
JsonRpcMessage::Error(error) => error.id.as_ref(),
JsonRpcMessage::Request(_) | JsonRpcMessage::Notification(_) => None,
}
}

View File

@@ -0,0 +1,527 @@
//! rmcp transport adapter for an executor-managed MCP stdio process.
//!
//! This module owns the lower-level byte translation after
//! `stdio_server_launcher` has already started a process through
//! `ExecBackend::start`. It does not choose where the MCP server runs and it
//! does not implement MCP lifecycle behavior. MCP protocol ownership stays in
//! `RmcpClient` and rmcp:
//!
//! 1. rmcp serializes a JSON-RPC message and calls [`Transport::send`].
//! 2. This transport appends the stdio newline delimiter and writes those bytes
//! to executor `process/write`.
//! 3. The executor writes the bytes to the child process stdin.
//! 4. The child writes newline-delimited JSON-RPC messages to stdout.
//! 5. The executor reports stdout bytes through pushed process events.
//! 6. This transport buffers stdout until it has one full line, deserializes
//! that line, and returns the rmcp message from [`Transport::receive`].
//!
//! Stderr is deliberately not part of the MCP byte stream. It is logged for
//! diagnostics only, matching the local stdio implementation.
use std::future::Future;
use std::io;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use bytes::BytesMut;
use codex_exec_server::ExecOutputStream;
use codex_exec_server::ExecProcess;
use codex_exec_server::ExecProcessEvent;
use codex_exec_server::ExecProcessEventReceiver;
use codex_exec_server::ProcessId;
use codex_exec_server::ProcessOutputChunk;
use codex_exec_server::WriteStatus;
use memchr::memchr;
use rmcp::service::RoleClient;
use rmcp::service::RxJsonRpcMessage;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::Transport;
use serde_json::to_vec;
use tokio::runtime::Handle;
use tokio::sync::Semaphore;
use tokio::sync::broadcast;
use tracing::debug;
use tracing::info;
use tracing::warn;
static PROCESS_COUNTER: AtomicUsize = AtomicUsize::new(1);
// Tool results can make valid MCP responses large, so keep the protocol
// ceiling well above ordinary messages while still bounding hostile input.
const MAX_MCP_STDOUT_LINE_BYTES: usize = 8 * 1024 * 1024;
// Stderr is diagnostic only and does not need the protocol stream's allowance.
const MAX_MCP_STDERR_LINE_BYTES: usize = 1024 * 1024;
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
struct LineBuffer {
bytes: BytesMut,
/// Prefix already scanned and known not to contain a newline.
scanned_len: usize,
/// Bytes after the last buffered newline.
pending_line_bytes: usize,
max_line_bytes: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct LineTooLong {
max_line_bytes: usize,
}
impl Default for LineBuffer {
fn default() -> Self {
Self::new(MAX_MCP_STDOUT_LINE_BYTES)
}
}
impl LineBuffer {
fn new(max_line_bytes: usize) -> Self {
Self {
bytes: BytesMut::new(),
scanned_len: 0,
pending_line_bytes: 0,
max_line_bytes,
}
}
fn extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), LineTooLong> {
let mut remaining = bytes;
while let Some(newline_index) = memchr(b'\n', remaining) {
if newline_index > self.max_line_bytes.saturating_sub(self.pending_line_bytes) {
self.discard_pending_line();
return Err(LineTooLong {
max_line_bytes: self.max_line_bytes,
});
}
let segment_len = newline_index + 1;
self.bytes.extend_from_slice(&remaining[..segment_len]);
self.pending_line_bytes = 0;
remaining = &remaining[segment_len..];
}
if remaining.len() > self.max_line_bytes.saturating_sub(self.pending_line_bytes) {
self.discard_pending_line();
return Err(LineTooLong {
max_line_bytes: self.max_line_bytes,
});
}
self.bytes.extend_from_slice(remaining);
self.pending_line_bytes += remaining.len();
Ok(())
}
fn discard_pending_line(&mut self) {
let complete_line_bytes = self.bytes.len().saturating_sub(self.pending_line_bytes);
self.bytes.truncate(complete_line_bytes);
self.scanned_len = self.scanned_len.min(complete_line_bytes);
self.pending_line_bytes = 0;
}
fn take_line(&mut self) -> Option<BytesMut> {
let Some(relative_index) = memchr(b'\n', &self.bytes[self.scanned_len..]) else {
self.scanned_len = self.bytes.len();
return None;
};
let newline_index = self.scanned_len + relative_index;
let mut line = self.bytes.split_to(newline_index + 1);
line.truncate(newline_index);
self.scanned_len = 0;
Some(line)
}
fn take_remaining(&mut self) -> Option<BytesMut> {
if self.bytes.is_empty() {
return None;
}
self.scanned_len = 0;
self.pending_line_bytes = 0;
Some(self.bytes.split())
}
fn clear(&mut self) {
self.bytes = BytesMut::new();
self.scanned_len = 0;
self.pending_line_bytes = 0;
}
}
// Remote public implementation.
/// A client-side rmcp transport backed by an executor-managed process.
///
/// The orchestrator owns this value and calls rmcp on it. The process it wraps
/// may be local or remote depending on the `ExecBackend` used to create it, but
/// for remote MCP stdio the process lives on the executor and all interaction
/// crosses the executor process RPC boundary.
pub(super) struct ExecutorProcessTransport {
/// Logical process handle returned by the executor process API.
///
/// `write` forwards stdin bytes. `terminate` stops the child when rmcp
/// closes the transport.
process: Arc<dyn ExecProcess>,
/// Prevents concurrent rmcp send futures from issuing overlapping stdin writes.
/// The single-slot semaphore gives mutex semantics while its permit can safely cross `.await`.
stdin_write_semaphore: Arc<Semaphore>,
/// Pushed output/lifecycle stream for the process.
///
/// The executor process API still supports retained-output reads, but MCP
/// stdio is naturally streaming. This receiver lets rmcp wait for stdout
/// chunks without issuing `process/read` after each output notification.
events: ExecProcessEventReceiver,
/// Human-readable program name used only in diagnostics.
program_name: String,
/// Buffered child stdout bytes that have not yet formed a complete
/// newline-delimited JSON-RPC message.
stdout: LineBuffer,
/// Buffered stderr bytes for diagnostic logging.
stderr: LineBuffer,
/// Whether the executor has reported process closure or a terminal
/// subscription failure. Once closed, any remaining partial stdout line is
/// flushed once and then rmcp receives EOF.
closed: bool,
/// Whether this transport already asked the executor to terminate the MCP
/// server process.
terminated: bool,
/// Highest executor process event sequence observed by this transport.
///
/// When the pushed event stream lags, use this as the retained-output read
/// cursor to recover missed stdout/stderr chunks from the executor.
last_seq: u64,
}
impl ExecutorProcessTransport {
pub(super) fn new(process: Arc<dyn ExecProcess>, program_name: String) -> Self {
// Subscribe before returning the transport to rmcp. Some test servers
// can emit output or exit quickly after `process/start`, and the
// process event log will replay anything that landed before this
// subscriber was attached.
let events = process.subscribe_events();
Self {
process,
stdin_write_semaphore: Arc::new(Semaphore::new(1)),
events,
program_name,
stdout: LineBuffer::default(),
stderr: LineBuffer::new(MAX_MCP_STDERR_LINE_BYTES),
closed: false,
terminated: false,
last_seq: 0,
}
}
pub(super) fn next_process_id() -> ProcessId {
// Process IDs are logical handles scoped to the executor connection,
// not OS pids. A monotonic client-side id is enough to avoid
// collisions between MCP servers started in the same session.
let index = PROCESS_COUNTER.fetch_add(1, Ordering::Relaxed);
ProcessId::from(format!("mcp-stdio-{index}"))
}
}
impl Transport<RoleClient> for ExecutorProcessTransport {
type Error = io::Error;
fn send(
&mut self,
item: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = std::result::Result<(), Self::Error>> + Send + 'static {
let process = Arc::clone(&self.process);
let stdin_write_semaphore = Arc::clone(&self.stdin_write_semaphore);
async move {
let _stdin_write_permit = stdin_write_semaphore
.acquire()
.await
.map_err(io::Error::other)?;
// rmcp hands us a structured JSON-RPC message. Stdio transport on
// the wire is JSON plus one newline delimiter.
let mut bytes = to_vec(&item).map_err(io::Error::other)?;
bytes.push(b'\n');
let response = process.write(bytes).await.map_err(io::Error::other)?;
match response.status {
WriteStatus::Accepted => Ok(()),
WriteStatus::UnknownProcess => {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "unknown process"))
}
WriteStatus::StdinClosed => {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "stdin closed"))
}
WriteStatus::Starting => Err(io::Error::new(
io::ErrorKind::WouldBlock,
"process is starting",
)),
}
}
}
fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<RoleClient>>> + Send {
self.receive_message()
}
async fn close(&mut self) -> std::result::Result<(), Self::Error> {
self.process.terminate().await.map_err(io::Error::other)?;
self.terminated = true;
Ok(())
}
}
impl ExecutorProcessTransport {
async fn receive_message(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
loop {
// rmcp stdio framing is line-oriented JSON. We first drain any
// complete line already buffered from an earlier process event.
if let Some(message) = self.take_stdout_message(/*allow_partial*/ self.closed) {
return Some(message);
}
if self.closed {
self.flush_stderr();
return None;
}
match self.events.recv().await {
Ok(ExecProcessEvent::Output(chunk)) => {
// The executor pushes raw process bytes. This is the only
// place where those bytes are split back into the stdout
// protocol stream and stderr diagnostics.
self.push_process_output_if_new(chunk);
}
Ok(ExecProcessEvent::Exited { seq, .. }) => {
self.note_seq(seq);
// Wait for `Closed` before ending the rmcp stream so any
// output flushed during process shutdown can still be
// decoded into JSON-RPC messages.
}
Ok(ExecProcessEvent::Closed { seq }) => {
self.note_seq(seq);
self.closed = true;
}
Ok(ExecProcessEvent::Failed(message)) => {
warn!(
"Remote MCP server process failed ({}): {message}",
self.program_name
);
self.closed = true;
}
Err(broadcast::error::RecvError::Lagged(skipped)) => {
warn!(
"Remote MCP server output stream lagged ({}): skipped {skipped} events",
self.program_name
);
if let Err(error) = self.recover_lagged_events().await {
warn!(
"Failed to recover remote MCP server output stream ({}): {error}",
self.program_name
);
self.closed = true;
}
}
Err(broadcast::error::RecvError::Closed) => {
self.closed = true;
}
}
}
}
fn note_seq(&mut self, seq: u64) {
self.last_seq = self.last_seq.max(seq);
}
fn should_accept_seq(&mut self, seq: u64) -> bool {
if seq <= self.last_seq {
return false;
}
self.last_seq = seq;
true
}
async fn recover_lagged_events(&mut self) -> io::Result<()> {
let response = self
.process
.read(
Some(self.last_seq),
/*max_bytes*/ None,
/*wait_ms*/ Some(0),
)
.await
.map_err(io::Error::other)?;
for chunk in response.chunks {
let expected_seq = self.last_seq.saturating_add(1);
if chunk.seq > expected_seq {
return Err(self.close_for_lost_output(expected_seq, chunk.seq));
}
self.push_process_output_if_new(chunk);
if self.closed {
return Ok(());
}
}
// Process reads include output chunks but not the sequenced `Exited`
// and `Closed` events. Account for those terminal events without
// allowing an evicted output chunk to be silently spliced into MCP.
let terminal_event_count = u64::from(response.exited) + u64::from(response.closed);
let next_output_seq = response.next_seq.saturating_sub(terminal_event_count);
let expected_seq = self.last_seq.saturating_add(1);
if next_output_seq > expected_seq {
return Err(self.close_for_lost_output(expected_seq, next_output_seq));
}
self.last_seq = self.last_seq.max(response.next_seq.saturating_sub(1));
if let Some(message) = response.failure {
warn!(
"Remote MCP server process failed ({}): {message}",
self.program_name
);
self.closed = true;
} else if response.closed {
self.closed = true;
}
Ok(())
}
fn close_for_lost_output(&mut self, expected_seq: u64, received_seq: u64) -> io::Error {
self.stdout.clear();
self.stderr.clear();
self.closed = true;
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"remote MCP server output stream lost process events: expected sequence {expected_seq}, received {received_seq}"
),
)
}
fn push_process_output_if_new(&mut self, chunk: ProcessOutputChunk) {
if !self.should_accept_seq(chunk.seq) {
return;
}
self.push_process_output(chunk);
}
fn push_process_output(&mut self, chunk: ProcessOutputChunk) {
let bytes = chunk.chunk.as_ref();
match chunk.stream {
// MCP stdio uses stdout as the protocol stream. PTY output is
// accepted defensively because the executor process API has a
// unified stream enum, but remote MCP starts with `tty=false`.
ExecOutputStream::Stdout | ExecOutputStream::Pty => {
if let Err(error) = self.stdout.extend_from_slice(bytes) {
self.close_for_oversized_line("stdout", error);
}
}
// Stderr is intentionally out-of-band. It should help debug server
// startup failures without entering rmcp framing.
ExecOutputStream::Stderr => {
if let Err(error) = self.push_stderr(bytes) {
self.stdout.clear();
self.close_for_oversized_line("stderr", error);
}
}
}
}
fn close_for_oversized_line(&mut self, stream_name: &str, error: LineTooLong) {
let max_line_bytes = error.max_line_bytes;
warn!(
"Remote MCP server {stream_name} line exceeds {max_line_bytes} bytes ({}); closing transport",
self.program_name
);
self.stderr.clear();
// Returning EOF makes rmcp drop the transport, whose Drop implementation
// terminates the executor-managed process.
self.closed = true;
}
fn take_stdout_message(&mut self, allow_partial: bool) -> Option<RxJsonRpcMessage<RoleClient>> {
// A normal MCP stdio server emits one JSON-RPC message per newline.
// If the process has already closed, accept a final unterminated line
// so EOF after a complete JSON object behaves like local rmcp's
// `decode_eof` handling.
loop {
let line = match self.stdout.take_line() {
Some(line) => line,
None if allow_partial => self.stdout.take_remaining()?,
None => return None,
};
let line = Self::trim_trailing_carriage_return(line);
match serde_json::from_slice(&line) {
Ok(message) => return Some(message),
Err(error) => {
debug!(
"Failed to parse remote MCP server message ({}): {error}",
self.program_name
);
}
}
}
}
fn push_stderr(&mut self, bytes: &[u8]) -> Result<(), LineTooLong> {
// Keep stderr line-oriented in logs so a chatty MCP server does not
// produce one log record per byte chunk.
self.stderr.extend_from_slice(bytes)?;
while let Some(line) = self.stderr.take_line() {
let line = Self::trim_trailing_carriage_return(line);
info!(
"MCP server stderr ({}): {}",
self.program_name,
String::from_utf8_lossy(&line)
);
}
Ok(())
}
fn flush_stderr(&mut self) {
let Some(line) = self.stderr.take_remaining() else {
return;
};
info!(
"MCP server stderr ({}): {}",
self.program_name,
String::from_utf8_lossy(&line)
);
}
fn trim_trailing_carriage_return(mut line: BytesMut) -> BytesMut {
if line.last() == Some(&b'\r') {
line.truncate(line.len() - 1);
}
line
}
}
#[cfg(test)]
#[path = "executor_process_transport_tests.rs"]
mod tests;
impl Drop for ExecutorProcessTransport {
fn drop(&mut self) {
if self.terminated {
return;
}
let process = Arc::clone(&self.process);
let program_name = self.program_name.clone();
let Ok(handle) = Handle::try_current() else {
warn!(
"Could not schedule remote MCP server process termination on drop ({}): no Tokio runtime is available",
self.program_name
);
return;
};
std::mem::drop(handle.spawn(async move {
if let Err(error) = process.terminate().await {
warn!(
"Failed to terminate remote MCP server process on drop ({program_name}): {error}"
);
}
}));
}
}

View File

@@ -0,0 +1,501 @@
use bytes::BytesMut;
use codex_exec_server::ExecOutputStream;
use codex_exec_server::ExecProcess;
use codex_exec_server::ExecProcessEventReceiver;
use codex_exec_server::ExecProcessFuture;
use codex_exec_server::ProcessId;
use codex_exec_server::ProcessOutputChunk;
use codex_exec_server::ProcessSignal;
use codex_exec_server::ReadResponse;
use codex_exec_server::WriteResponse;
use codex_exec_server::WriteStatus;
use pretty_assertions::assert_eq;
use rmcp::service::RoleClient;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::Transport;
use serde_json::json;
use std::io;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Poll;
use tokio::sync::watch;
use super::ExecutorProcessTransport;
use super::LineBuffer;
use super::LineTooLong;
use super::MAX_MCP_STDERR_LINE_BYTES;
use super::MAX_MCP_STDOUT_LINE_BYTES;
struct BlockingFirstWriteProcess {
process_id: ProcessId,
writes: StdMutex<Vec<Vec<u8>>>,
release_first_write: AtomicBool,
}
impl BlockingFirstWriteProcess {
fn writes(&self) -> Vec<Vec<u8>> {
self.writes.lock().expect("writes lock").clone()
}
}
impl ExecProcess for BlockingFirstWriteProcess {
fn process_id(&self) -> &ProcessId {
&self.process_id
}
fn subscribe_wake(&self) -> watch::Receiver<u64> {
watch::channel(0).1
}
fn subscribe_events(&self) -> ExecProcessEventReceiver {
ExecProcessEventReceiver::empty()
}
fn read(
&self,
_after_seq: Option<u64>,
_max_bytes: Option<usize>,
_wait_ms: Option<u64>,
) -> ExecProcessFuture<'_, ReadResponse> {
Box::pin(async { unreachable!("send test should not read process output") })
}
fn write(&self, chunk: Vec<u8>) -> ExecProcessFuture<'_, WriteResponse> {
let first_write = {
let mut writes = self.writes.lock().expect("writes lock");
writes.push(chunk);
writes.len() == 1
};
Box::pin(std::future::poll_fn(move |_| {
if first_write && !self.release_first_write.load(Ordering::Acquire) {
return Poll::Pending;
}
Poll::Ready(Ok(WriteResponse {
status: WriteStatus::Accepted,
}))
}))
}
fn signal(&self, _signal: ProcessSignal) -> ExecProcessFuture<'_, ()> {
Box::pin(async { Ok(()) })
}
fn terminate(&self) -> ExecProcessFuture<'_, ()> {
Box::pin(async { Ok(()) })
}
}
struct RetainedReadProcess {
process_id: ProcessId,
response: ReadResponse,
}
impl ExecProcess for RetainedReadProcess {
fn process_id(&self) -> &ProcessId {
&self.process_id
}
fn subscribe_wake(&self) -> watch::Receiver<u64> {
watch::channel(0).1
}
fn subscribe_events(&self) -> ExecProcessEventReceiver {
ExecProcessEventReceiver::empty()
}
fn read(
&self,
_after_seq: Option<u64>,
_max_bytes: Option<usize>,
_wait_ms: Option<u64>,
) -> ExecProcessFuture<'_, ReadResponse> {
Box::pin(async { Ok(self.response.clone()) })
}
fn write(&self, _chunk: Vec<u8>) -> ExecProcessFuture<'_, WriteResponse> {
Box::pin(async { unreachable!("recovery tests should not write process input") })
}
fn signal(&self, _signal: ProcessSignal) -> ExecProcessFuture<'_, ()> {
Box::pin(async { Ok(()) })
}
fn terminate(&self) -> ExecProcessFuture<'_, ()> {
Box::pin(async { Ok(()) })
}
}
fn recovered_output(seq: u64, stream: ExecOutputStream, bytes: &[u8]) -> ProcessOutputChunk {
ProcessOutputChunk {
seq,
stream,
chunk: bytes.to_vec().into(),
}
}
fn retained_read_response(chunks: Vec<ProcessOutputChunk>, next_seq: u64) -> ReadResponse {
ReadResponse {
chunks,
next_seq,
exited: false,
exit_code: None,
closed: false,
failure: None,
sandbox_denied: false,
}
}
#[tokio::test]
async fn serializes_concurrent_stdin_writes() {
let process = Arc::new(BlockingFirstWriteProcess {
process_id: ProcessId::from("mcp-stdio-test"),
writes: StdMutex::new(Vec::new()),
release_first_write: AtomicBool::new(false),
});
let mut transport =
ExecutorProcessTransport::new(process.clone(), "mcp-stdio-test".to_string());
let first_message: TxJsonRpcMessage<RoleClient> =
serde_json::from_value(json!({ "jsonrpc": "2.0", "id": 1, "method": "ping" }))
.expect("first MCP message should deserialize");
let second_message: TxJsonRpcMessage<RoleClient> =
serde_json::from_value(json!({ "jsonrpc": "2.0", "id": 2, "method": "ping" }))
.expect("second MCP message should deserialize");
// Drive both sends explicitly so task scheduling cannot hide an overlapping write.
let first_send = transport.send(first_message);
tokio::pin!(first_send);
assert!(matches!(futures::poll!(first_send.as_mut()), Poll::Pending));
assert_eq!(
process.writes(),
vec![b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n".to_vec()]
);
let second_send = transport.send(second_message);
tokio::pin!(second_send);
assert!(matches!(
futures::poll!(second_send.as_mut()),
Poll::Pending
));
assert_eq!(
process.writes(),
vec![b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n".to_vec()]
);
process.release_first_write.store(true, Ordering::Release);
assert!(matches!(
futures::poll!(first_send.as_mut()),
Poll::Ready(Ok(()))
));
assert!(matches!(
futures::poll!(second_send.as_mut()),
Poll::Ready(Ok(()))
));
assert_eq!(
process.writes(),
vec![
b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n".to_vec(),
b"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n".to_vec(),
]
);
}
#[tokio::test]
async fn rejects_lagged_recovery_when_retained_output_skips_a_sequence() {
let process = Arc::new(RetainedReadProcess {
process_id: ProcessId::from("mcp-stdio-lost-output"),
response: retained_read_response(
vec![recovered_output(
/*seq*/ 6,
ExecOutputStream::Stdout,
br#"{"jsonrpc":"2.0","id":1,"result":{}}"#,
)],
/*next_seq*/ 7,
),
});
let mut transport = ExecutorProcessTransport::new(process, "mcp-stdio-lost-output".to_string());
transport.last_seq = 4;
transport
.stdout
.extend_from_slice(br#"{"jsonrpc":"2.0","id":1,"result":""#)
.expect("partial stdout should fit");
transport
.stderr
.extend_from_slice(b"partial diagnostic")
.expect("partial stderr should fit");
let error = transport
.recover_lagged_events()
.await
.expect_err("evicted output must close the transport");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(
error.to_string(),
"remote MCP server output stream lost process events: expected sequence 5, received 6"
);
assert_eq!(transport.stdout, LineBuffer::default());
assert_eq!(transport.stderr, LineBuffer::new(MAX_MCP_STDERR_LINE_BYTES));
assert!(transport.closed);
}
#[tokio::test]
async fn rejects_lagged_recovery_when_all_missing_output_was_evicted() {
let process = Arc::new(RetainedReadProcess {
process_id: ProcessId::from("mcp-stdio-evicted-output"),
response: retained_read_response(Vec::new(), /*next_seq*/ 7),
});
let mut transport =
ExecutorProcessTransport::new(process, "mcp-stdio-evicted-output".to_string());
transport.last_seq = 4;
let error = transport
.recover_lagged_events()
.await
.expect_err("missing retained output must close the transport");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(
error.to_string(),
"remote MCP server output stream lost process events: expected sequence 5, received 7"
);
assert!(transport.closed);
}
#[tokio::test]
async fn recovers_contiguous_output_after_a_duplicate_replayed_event() {
let process = Arc::new(RetainedReadProcess {
process_id: ProcessId::from("mcp-stdio-duplicate-output"),
response: retained_read_response(
vec![
recovered_output(
/*seq*/ 4,
ExecOutputStream::Stdout,
b"duplicate output\n",
),
recovered_output(
/*seq*/ 5,
ExecOutputStream::Stdout,
b"recovered stdout\n",
),
recovered_output(
/*seq*/ 6,
ExecOutputStream::Stderr,
b"recovered stderr\n",
),
],
/*next_seq*/ 7,
),
});
let mut transport =
ExecutorProcessTransport::new(process, "mcp-stdio-duplicate-output".to_string());
transport.last_seq = 4;
transport
.recover_lagged_events()
.await
.expect("duplicate replay must not prevent recovery of contiguous output");
assert_eq!(
transport.stdout.take_line(),
Some(BytesMut::from(&b"recovered stdout"[..]))
);
assert_eq!(transport.stdout.take_line(), None);
assert_eq!(transport.stderr, LineBuffer::new(MAX_MCP_STDERR_LINE_BYTES));
assert_eq!(transport.last_seq, 6);
assert!(!transport.closed);
}
#[tokio::test]
async fn recovers_contiguous_output_and_accounts_for_terminal_events() {
let mut response = retained_read_response(
vec![
recovered_output(
/*seq*/ 5,
ExecOutputStream::Stdout,
b"recovered stdout\n",
),
recovered_output(
/*seq*/ 6,
ExecOutputStream::Stderr,
b"recovered stderr\n",
),
],
/*next_seq*/ 9,
);
response.exited = true;
response.exit_code = Some(0);
response.closed = true;
let process = Arc::new(RetainedReadProcess {
process_id: ProcessId::from("mcp-stdio-recovered-output"),
response,
});
let mut transport =
ExecutorProcessTransport::new(process, "mcp-stdio-recovered-output".to_string());
transport.last_seq = 4;
transport
.recover_lagged_events()
.await
.expect("contiguous retained output should remain recoverable");
assert_eq!(
transport.stdout.take_line(),
Some(BytesMut::from(&b"recovered stdout"[..]))
);
assert_eq!(transport.stderr, LineBuffer::new(MAX_MCP_STDERR_LINE_BYTES));
assert_eq!(transport.last_seq, 8);
assert!(transport.closed);
}
#[tokio::test]
async fn closes_on_an_unsequenced_process_failure_without_inventing_missing_output() {
let mut response = retained_read_response(Vec::new(), /*next_seq*/ 5);
response.exited = true;
response.closed = true;
response.failure = Some("executor disconnected".to_string());
let process = Arc::new(RetainedReadProcess {
process_id: ProcessId::from("mcp-stdio-failed-process"),
response,
});
let mut transport =
ExecutorProcessTransport::new(process, "mcp-stdio-failed-process".to_string());
transport.last_seq = 4;
transport
.recover_lagged_events()
.await
.expect("an unsequenced executor failure is not an output sequence gap");
assert_eq!(transport.last_seq, 4);
assert!(transport.closed);
}
#[test]
fn searches_only_new_bytes_after_partial_line() {
let mut buffer = LineBuffer::default();
buffer
.extend_from_slice(b"partial")
.expect("partial line should fit");
assert_eq!(buffer.take_line(), None);
assert_eq!(
buffer,
LineBuffer {
bytes: BytesMut::from(&b"partial"[..]),
scanned_len: 7,
pending_line_bytes: 7,
max_line_bytes: MAX_MCP_STDOUT_LINE_BYTES,
}
);
buffer
.extend_from_slice(b" line")
.expect("partial line should fit");
assert_eq!(buffer.take_line(), None);
assert_eq!(
buffer,
LineBuffer {
bytes: BytesMut::from(&b"partial line"[..]),
scanned_len: 12,
pending_line_bytes: 12,
max_line_bytes: MAX_MCP_STDOUT_LINE_BYTES,
}
);
buffer
.extend_from_slice(b"\nnext")
.expect("completed line should fit");
assert_eq!(
buffer.take_line(),
Some(BytesMut::from(&b"partial line"[..]))
);
assert_eq!(
buffer,
LineBuffer {
bytes: BytesMut::from(&b"next"[..]),
scanned_len: 0,
pending_line_bytes: 4,
max_line_bytes: MAX_MCP_STDOUT_LINE_BYTES,
}
);
}
#[test]
fn splits_multiple_lines_and_retains_partial_tail() {
let mut buffer = LineBuffer::default();
buffer
.extend_from_slice(b"first\nsecond\npartial")
.expect("lines should fit");
assert_eq!(buffer.take_line(), Some(BytesMut::from(&b"first"[..])));
assert_eq!(buffer.take_line(), Some(BytesMut::from(&b"second"[..])));
assert_eq!(buffer.take_line(), None);
assert_eq!(
buffer,
LineBuffer {
bytes: BytesMut::from(&b"partial"[..]),
scanned_len: 7,
pending_line_bytes: 7,
max_line_bytes: MAX_MCP_STDOUT_LINE_BYTES,
}
);
}
#[test]
fn takes_unterminated_remaining_bytes_at_eof() {
let mut buffer = LineBuffer::default();
buffer
.extend_from_slice(b"remaining")
.expect("remaining line should fit");
assert_eq!(buffer.take_line(), None);
assert_eq!(
buffer.take_remaining(),
Some(BytesMut::from(&b"remaining"[..]))
);
assert_eq!(buffer, LineBuffer::default());
}
#[test]
fn rejects_oversized_line_without_retaining_its_prefix() {
let mut buffer = LineBuffer::new(/*max_line_bytes*/ 5);
buffer
.extend_from_slice(b"12345")
.expect("line at the limit should fit");
assert_eq!(buffer.take_line(), None);
assert_eq!(
buffer.extend_from_slice(b"6"),
Err(LineTooLong { max_line_bytes: 5 })
);
assert_eq!(buffer, LineBuffer::new(/*max_line_bytes*/ 5));
}
#[test]
fn retains_complete_lines_before_an_oversized_line() {
let mut buffer = LineBuffer::new(/*max_line_bytes*/ 5);
assert_eq!(
buffer.extend_from_slice(b"first\n123456"),
Err(LineTooLong { max_line_bytes: 5 })
);
assert_eq!(buffer.take_line(), Some(BytesMut::from(&b"first"[..])));
assert_eq!(buffer.take_remaining(), None);
}
#[test]
fn accepts_input_larger_than_limit_when_each_line_is_bounded() {
let mut buffer = LineBuffer::new(/*max_line_bytes*/ 5);
buffer
.extend_from_slice(b"12345\nabcde\ntail")
.expect("each individual line should fit");
assert_eq!(buffer.take_line(), Some(BytesMut::from(&b"12345"[..])));
assert_eq!(buffer.take_line(), Some(BytesMut::from(&b"abcde"[..])));
assert_eq!(buffer.take_line(), None);
assert_eq!(buffer.take_remaining(), Some(BytesMut::from(&b"tail"[..])));
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,611 @@
use std::io::ErrorKind;
use codex_exec_server::HttpRedirectPolicy;
use http::HeaderMap;
use http::HeaderValue;
use http::header::AUTHORIZATION;
use pretty_assertions::assert_eq;
use super::HttpHeader;
use super::SseEventSizeLimit;
use super::StreamableHttpRedirectMode;
use super::mcp_redirect_policy;
use super::protocol_headers;
#[test]
fn protocol_headers_preserve_utf8_values() {
let mut headers = HeaderMap::new();
headers.insert(
"x-plugin-name",
HeaderValue::from_str("café").expect("valid HTTP field value"),
);
assert_eq!(
protocol_headers(&headers),
vec![HttpHeader {
name: "x-plugin-name".to_string(),
value: "café".to_string(),
value_env_var: None,
}]
);
}
#[test]
fn legacy_configured_headers_follow_redirects() {
assert_eq!(
mcp_redirect_policy(
StreamableHttpRedirectMode::Legacy,
&HeaderMap::new(),
/*has_configured_headers*/ true,
),
HttpRedirectPolicy::Follow
);
}
#[test]
fn agent_plugin_configured_headers_stop_redirects() {
assert_eq!(
mcp_redirect_policy(
StreamableHttpRedirectMode::AgentPluginV1,
&HeaderMap::new(),
/*has_configured_headers*/ true,
),
HttpRedirectPolicy::Stop
);
}
#[test]
fn requests_without_sensitive_headers_follow_redirects() {
assert_eq!(
mcp_redirect_policy(
StreamableHttpRedirectMode::AgentPluginV1,
&HeaderMap::new(),
/*has_configured_headers*/ false,
),
HttpRedirectPolicy::Follow
);
}
#[test]
fn authorization_redirects_depend_on_mode() {
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret"));
assert_eq!(
mcp_redirect_policy(
StreamableHttpRedirectMode::Legacy,
&headers,
/*has_configured_headers*/ false,
),
HttpRedirectPolicy::Follow
);
assert_eq!(
mcp_redirect_policy(
StreamableHttpRedirectMode::AgentPluginV1,
&headers,
/*has_configured_headers*/ false,
),
HttpRedirectPolicy::Stop
);
}
#[test]
fn runtime_assertions_stop_redirects_in_both_mcp_modes() {
for mode in [
StreamableHttpRedirectMode::Legacy,
StreamableHttpRedirectMode::AgentPluginV1,
] {
for (name, value) in [
("x-openai-agent-assertion", "1.protected.payload.signature"),
(
"authorization",
"AgentAssertion 1.protected.payload.signature",
),
] {
let mut headers = HeaderMap::new();
headers.insert(name, HeaderValue::from_static(value));
assert_eq!(
mcp_redirect_policy(mode, &headers, /*has_configured_headers*/ false),
HttpRedirectPolicy::Stop,
);
}
}
}
#[test]
fn lf_terminators_reset_the_event_limit() {
let mut limit = SseEventSizeLimit::new(Some(8));
limit
.observe(b"data: a\n\ndata: b\n\n")
.expect("LF-terminated events must have independent size limits");
assert_eq!((limit.retained_bytes, limit.line_bytes), (0, 0));
}
#[test]
fn carriage_return_terminators_reset_the_event_limit() {
let mut limit = SseEventSizeLimit::new(Some(8));
limit
.observe(b"data: a\r\rdata: b\r\r")
.expect("CR-terminated events must have independent size limits");
assert_eq!((limit.retained_bytes, limit.line_bytes), (0, 0));
}
#[test]
fn crlf_terminators_split_across_chunks_reset_the_event_limit() {
let mut limit = SseEventSizeLimit::new(Some(8));
limit
.observe(b"data: a\r")
.expect("a CR must finish the first event field");
limit
.observe(b"\n\r")
.expect("a split CRLF must not finish another field");
limit
.observe(b"\ndata: b\r")
.expect("the blank CRLF must reset the first event");
limit
.observe(b"\n\r\n")
.expect("the second split CRLF event must remain within the limit");
assert_eq!((limit.retained_bytes, limit.line_bytes), (0, 0));
}
#[test]
fn event_at_the_exact_size_limit_is_accepted() {
let mut limit = SseEventSizeLimit::new(Some(9));
limit
.observe(b"data: ab\n\n")
.expect("an event at the exact limit must be accepted");
assert_eq!((limit.retained_bytes, limit.line_bytes), (0, 0));
}
#[test]
fn completed_keepalive_comments_do_not_accumulate() {
let mut limit = SseEventSizeLimit::new(Some(6));
limit
.observe(&b": ping\n".repeat(/*n*/ 64))
.expect("completed keepalive comments must not accumulate");
assert_eq!((limit.retained_bytes, limit.line_bytes), (0, 0));
}
#[test]
fn split_keepalive_comments_are_discarded_only_when_complete() {
let mut limit = SseEventSizeLimit::new(Some(6));
limit
.observe(b": pi")
.expect("an incomplete comment within the limit must be retained");
assert_eq!((limit.retained_bytes, limit.line_bytes), (0, 4));
limit
.observe(b"ng\n: ping\n")
.expect("only completed comments may be excluded from the limit");
assert_eq!((limit.retained_bytes, limit.line_bytes), (0, 0));
}
#[test]
fn comments_do_not_reset_accumulated_event_data() {
let mut limit = SseEventSizeLimit::new(Some(14));
limit
.observe(b"data: a\n")
.expect("the first data field must fit");
limit
.observe(b": ping\n")
.expect("a completed comment must not count as event data");
let error = limit
.observe(b"data: b\n")
.expect_err("a comment must not reset previously retained data");
assert_eq!(
(error.kind(), error.to_string()),
(
ErrorKind::InvalidData,
"MCP response body exceeds 14 bytes".to_string(),
)
);
}
#[test]
fn an_unterminated_comment_remains_size_limited() {
let mut limit = SseEventSizeLimit::new(Some(6));
limit
.observe(b": ping")
.expect("a comment at the exact limit must be accepted");
let error = limit
.observe(b"!")
.expect_err("an unterminated comment must not bypass the limit");
assert_eq!(
(error.kind(), error.to_string()),
(
ErrorKind::InvalidData,
"MCP response body exceeds 6 bytes".to_string(),
)
);
}
#[test]
fn multiline_data_counts_parser_inserted_newlines() {
let mut limit = SseEventSizeLimit::new(Some(18));
let error = limit
.observe(b"data: aaa\ndata: bbb\n\n")
.expect_err("joined multiline event data must remain size limited");
assert_eq!(
(error.kind(), error.to_string()),
(
ErrorKind::InvalidData,
"MCP response body exceeds 18 bytes".to_string(),
)
);
}
#[test]
fn legacy_sse_streams_remain_unlimited() {
let mut limit = SseEventSizeLimit::new(/*maximum_bytes*/ None);
limit
.observe(&[b'x'; 128])
.expect("legacy SSE streams must not gain a message limit");
assert_eq!(
(
limit.retained_bytes,
limit.line_bytes,
limit.line_is_comment,
limit.previous_was_carriage_return,
limit.failed,
),
(0, 0, false, false, false)
);
}
#[test]
fn rejected_events_remain_rejected() {
let mut limit = SseEventSizeLimit::new(Some(8));
limit
.observe(b"data: abc")
.expect_err("an oversized event must be rejected");
let error = limit
.observe(b"")
.expect_err("a rejected event must not be resumed");
assert_eq!(
(error.kind(), error.to_string()),
(
ErrorKind::InvalidData,
"oversized MCP SSE event was already rejected".to_string(),
)
);
}
#[test]
fn size_accounting_saturates_without_overflow() {
let mut limit = SseEventSizeLimit::new(Some(usize::MAX - 1));
limit.retained_bytes = usize::MAX - 2;
limit.line_bytes = 1;
let error = limit
.observe(b"x")
.expect_err("saturating counts must still reject an oversized event");
assert_eq!((error.kind(), limit.failed), (ErrorKind::InvalidData, true));
}
struct AsyncRequestAuth {
requests: std::sync::atomic::AtomicUsize,
}
impl crate::AuthProviderResolver for AsyncRequestAuth {
fn resolve<'a>(
&'a self,
_headers: &'a HeaderMap,
) -> futures::future::BoxFuture<'a, Result<codex_api::SharedAuthProvider, codex_api::AuthError>>
{
Box::pin(async move {
tokio::task::yield_now().await;
let id = self
.requests
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(std::sync::Arc::new(SelectedRequestAuth(id)) as codex_api::SharedAuthProvider)
})
}
}
struct SelectedRequestAuth(usize);
impl codex_api::AuthProvider for SelectedRequestAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
headers.remove("x-openai-agent-assertion");
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("AgentAssertion proof-{}", self.0)).unwrap(),
);
Ok(())
}
fn apply_auth_headers(&self, mut headers: HeaderMap) -> codex_api::AuthHeadersFuture<'_> {
Box::pin(async move {
self.add_auth_headers(&mut headers)?;
Ok(headers)
})
}
}
#[tokio::test]
async fn requests_await_auth_and_stop_assertion_redirects() -> anyhow::Result<()> {
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::StreamExt;
use rmcp::transport::streamable_http_client::StreamableHttpClient;
use std::collections::HashMap;
use std::sync::Arc;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(202))
.expect(2)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(200).insert_header("content-type", "text/event-stream"))
.expect(2)
.mount(&server)
.await;
Mock::given(method("DELETE"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/redirect"))
.respond_with(
ResponseTemplate::new(307)
.insert_header("location", format!("{}/leaked", server.uri())),
)
.expect(1)
.mount(&server)
.await;
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer stale"));
headers.insert(
"x-openai-agent-assertion",
HeaderValue::from_static("stale-proof"),
);
let adapter = super::StreamableHttpClientAdapter::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
headers,
Some(Arc::new(AsyncRequestAuth {
requests: Default::default(),
})),
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
Default::default(),
);
let uri: Arc<str> = format!("{}/mcp", server.uri()).into();
let notification: rmcp::model::ClientJsonRpcMessage =
serde_json::from_value(serde_json::json!({
"jsonrpc": "2.0", "method": "notifications/initialized",
}))?;
for _ in 0..2 {
adapter
.post_message(
uri.clone(),
notification.clone(),
/*session_id*/ None,
/*auth_token*/ None,
HashMap::new(),
)
.await?;
}
for _ in 0..2 {
let mut stream = adapter
.get_stream(
uri.clone(),
Some("session-a".into()),
/*last_event_id*/ None,
/*auth_token*/ None,
HashMap::new(),
)
.await?;
assert!(stream.next().await.is_none());
}
adapter
.delete_session(
uri,
"session-a".into(),
/*auth_token*/ None,
HashMap::new(),
)
.await?;
assert!(
adapter
.post_message(
format!("{}/redirect", server.uri()).into(),
notification,
/*session_id*/ None,
/*auth_token*/ None,
HashMap::new()
)
.await
.is_err()
);
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 6);
for (id, request) in requests.iter().enumerate() {
assert_eq!(
request.headers["authorization"],
format!("AgentAssertion proof-{id}")
);
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
assert_ne!(request.url.path(), "/leaked");
}
server.verify().await;
Ok(())
}
#[tokio::test]
async fn automatic_event_stream_reconnect_refreshes_request_auth() -> anyhow::Result<()> {
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use rmcp::model::ClientCapabilities;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequestParams;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &wiremock::Request| {
let body: serde_json::Value = request.body_json().unwrap();
let result = match body["method"].as_str() {
Some("initialize") => json!({
"protocolVersion": body["params"]["protocolVersion"],
"capabilities": {"tools": {}},
"serverInfo": {"name": "reconnect-test", "version": "1"},
}),
Some("tools/call") => json!({
"content": [], "structuredContent": {"echo": "after reconnect"},
}),
_ => return ResponseTemplate::new(202),
};
ResponseTemplate::new(200)
.insert_header("mcp-session-id", "session-a")
.set_body_json(json!({"jsonrpc": "2.0", "id": body["id"], "result": result}))
})
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(
ResponseTemplate::new(200).set_body_raw(
concat!(
"retry: 1\nid: event-1\nevent: message\ndata: ",
r#"{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}"#,
"\n\n",
)
.as_bytes(),
"text/event-stream",
),
)
.up_to_n_times(1)
.with_priority(1)
.mount(&server)
.await;
// Leave the reconnect pending until shutdown instead of starting a tight EOF loop.
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(
ResponseTemplate::new(200)
.insert_header("content-type", "text/event-stream")
.set_delay(Duration::from_secs(60)),
)
.with_priority(2)
.mount(&server)
.await;
let client = crate::RmcpClient::new_streamable_http_client(
"reconnect-test",
&format!("{}/mcp", server.uri()),
/*bearer_token*/ None,
/*http_headers*/ None,
/*env_http_headers*/ None,
Default::default(),
Default::default(),
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
Some(Arc::new(AsyncRequestAuth {
requests: Default::default(),
})),
)
.await?;
client
.initialize(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("codex-test", "1"),
),
Some(Duration::from_secs(5)),
Box::new(|_, _| Box::pin(async { anyhow::bail!("unexpected elicitation") })),
)
.await?;
// The server ends the stream. Only the protocol engine, not the test, reopens it.
let streams = tokio::time::timeout(Duration::from_secs(10), async {
loop {
let streams: Vec<_> = server
.received_requests()
.await
.unwrap()
.into_iter()
.filter(|request| request.method == "GET")
.collect();
if streams.len() >= 2 {
break streams;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await?;
assert_eq!(streams[0].headers["mcp-session-id"], "session-a");
assert_eq!(streams[1].headers["last-event-id"], "event-1");
assert_ne!(
streams[0].headers["authorization"],
streams[1].headers["authorization"]
);
for request in &streams {
assert!(
request.headers["authorization"]
.to_str()?
.starts_with("AgentAssertion proof-")
);
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
}
let result = client
.call_tool(
"echo".to_string(),
Some(json!({"message": "after reconnect"})),
|_| Ok(None),
Some(Duration::from_secs(5)),
)
.await?;
assert_eq!(
result.structured_content,
Some(json!({"echo": "after reconnect"}))
);
client.shutdown().await;
Ok(())
}

View File

@@ -0,0 +1,222 @@
//! Restricts MCP HTTP redirects to the configured server's origin.
//!
//! MCP requests can carry sensitive headers and tool-call bodies. Following a
//! cross-origin redirect would send them to another server or an internal
//! service, so this transport validates each redirect before following it.
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::FutureExt;
use futures::future::BoxFuture;
use http::HeaderValue;
use http::StatusCode;
use url::Url;
const MAX_REDIRECTS: usize = 10;
pub(crate) struct SameOriginRedirectHttpClient {
inner: Arc<dyn HttpClient>,
}
enum RedirectResponse {
Buffered(HttpRequestResponse),
Streaming(HttpRequestResponse, HttpResponseBodyStream),
}
impl SameOriginRedirectHttpClient {
pub(crate) fn new(inner: Arc<dyn HttpClient>) -> Self {
Self { inner }
}
async fn execute(
&self,
mut params: HttpRequestParams,
) -> Result<RedirectResponse, ExecServerError> {
// Inspect each Location ourselves before the underlying client can send
// sensitive request data to the redirect destination.
params.redirect_policy = HttpRedirectPolicy::Stop;
let mut current_url = Url::parse(&params.url)
.map_err(|error| ExecServerError::HttpRequest(error.to_string()))?;
let original_origin = current_url.origin();
// Redirect hops share the original timeout instead of restarting it.
let deadline = params
.timeout_ms
.map(|timeout_ms| Instant::now() + Duration::from_millis(timeout_ms));
let mut redirects = 0;
loop {
if let Some(deadline) = deadline {
let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
return Err(ExecServerError::HttpRequest(
"MCP HTTP request timed out".to_string(),
));
};
params.timeout_ms = Some(
u64::try_from(remaining.as_millis())
.unwrap_or(u64::MAX)
.max(1),
);
}
let result = if params.stream_response {
let (response, stream) = self.inner.http_request_stream(params.clone()).await?;
RedirectResponse::Streaming(response, stream)
} else {
RedirectResponse::Buffered(self.inner.http_request(params.clone()).await?)
};
let response = match &result {
RedirectResponse::Buffered(response) | RedirectResponse::Streaming(response, _) => {
response
}
};
let status = StatusCode::from_u16(response.status).ok();
if !matches!(
status,
Some(
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::SEE_OTHER
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT
)
) {
return Ok(result);
}
let Some(location) = response
.headers
.iter()
.find(|header| header.name.eq_ignore_ascii_case("location"))
.map(|header| header.value.as_str())
else {
return Ok(result);
};
let next_url = current_url
.join(location)
.map_err(|error| ExecServerError::HttpRequest(error.to_string()))?;
// Compare every hop with the configured origin so redirect chains
// cannot escape it through a later cross-origin Location.
if next_url.origin() != original_origin {
return Err(ExecServerError::HttpRequest(
"MCP HTTP redirect to a different origin is not allowed".to_string(),
));
}
// A hostname can resolve to a different address on the next HTTP
// connection. HTTPS authenticates the hostname; localhost and IP
// literals do not depend on attacker-controlled DNS.
if next_url.scheme() == "http"
&& matches!(next_url.host(), Some(url::Host::Domain(host)) if host != "localhost")
{
return Err(ExecServerError::HttpRequest(
"MCP HTTP redirects for non-loopback hostnames require HTTPS".to_string(),
));
}
if redirects >= MAX_REDIRECTS {
return Err(ExecServerError::HttpRequest(
"MCP HTTP request exceeded the redirect limit".to_string(),
));
}
// Preserve normal HTTP behavior: 307/308 retain the method and body;
// 303 and legacy 301/302 POST redirects switch to a bodyless GET.
let drop_body = matches!(
status,
Some(StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND)
) && params.method.eq_ignore_ascii_case("POST")
|| status == Some(StatusCode::SEE_OTHER);
if drop_body {
if !params.method.eq_ignore_ascii_case("HEAD") {
params.method = "GET".to_string();
}
params.body = None;
params.headers.retain(|header| {
![
"content-type",
"content-length",
"content-encoding",
"transfer-encoding",
]
.iter()
.any(|name| header.name.eq_ignore_ascii_case(name))
});
}
// HTTPS keeps application proxy credentials inside the tunnel to
// the already-validated origin. Plaintext routes can change across
// requests, so their proxy credentials must never be replayed.
params.headers.retain(|header| {
(current_url.scheme() == "https"
|| !header.name.eq_ignore_ascii_case("proxy-authorization"))
&& !header.name.eq_ignore_ascii_case("referer")
});
let mut referer = current_url.clone();
let _ = referer.set_username("");
let _ = referer.set_password(None);
referer.set_fragment(None);
if HeaderValue::from_str(referer.as_str()).is_ok() {
params.headers.push(HttpHeader {
name: "referer".to_string(),
value: referer.to_string(),
value_env_var: None,
});
}
params.url = next_url.to_string();
current_url = next_url;
redirects += 1;
}
}
}
impl HttpClient for SameOriginRedirectHttpClient {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
async move {
params.stream_response = false;
if params.redirect_policy == HttpRedirectPolicy::Stop {
return self.inner.http_request(params).await;
}
match self.execute(params).await? {
RedirectResponse::Buffered(response) => Ok(response),
RedirectResponse::Streaming(_, _) => Err(ExecServerError::Protocol(
"MCP buffered HTTP request returned a streamed response".to_string(),
)),
}
}
.boxed()
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
async move {
params.stream_response = true;
if params.redirect_policy == HttpRedirectPolicy::Stop {
return self.inner.http_request_stream(params).await;
}
match self.execute(params).await? {
RedirectResponse::Streaming(response, stream) => Ok((response, stream)),
RedirectResponse::Buffered(_) => Err(ExecServerError::Protocol(
"MCP streamed HTTP request returned a buffered response".to_string(),
)),
}
}
.boxed()
}
}
#[cfg(test)]
#[path = "http_client_redirect_tests.rs"]
mod tests;

View File

@@ -0,0 +1,391 @@
use std::sync::Arc;
use std::sync::Mutex;
use codex_exec_server::Environment;
use codex_exec_server::HttpHeader;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
use crate::http_headers::with_http_headers_helper;
use super::*;
const PROXY_HEADERS_HELPER: &str = if cfg!(windows) {
r#"echo {"Proxy-Authorization":"Bearer proxy-token"}"#
} else {
r#"printf '{"Proxy-Authorization":"Bearer proxy-token"}'"#
};
fn request(url: impl Into<String>) -> HttpRequestParams {
HttpRequestParams {
method: "POST".to_string(),
url: url.into(),
headers: Vec::new(),
body: Some(b"sensitive-body".to_vec().into()),
timeout_ms: Some(5_000),
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "redirect-test".to_string(),
stream_response: false,
}
}
fn headers<const N: usize>(headers: [(&str, &str); N]) -> Vec<HttpHeader> {
headers
.into_iter()
.map(|(name, value)| HttpHeader {
name: name.to_string(),
value: value.to_string(),
value_env_var: None,
})
.collect()
}
#[derive(Default)]
struct RecordingRedirectHttpClient {
requests: Mutex<Vec<HttpRequestParams>>,
delay: Duration,
loop_redirects: bool,
}
impl HttpClient for RecordingRedirectHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
let mut requests = self.requests.lock().expect("request recorder lock");
let redirect = requests.is_empty() || self.loop_redirects;
let delay = self.delay;
requests.push(params);
async move {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
Ok(HttpRequestResponse {
status: if redirect { 307 } else { 200 },
headers: if redirect {
headers([("location", "/final")])
} else {
Vec::new()
},
body: Vec::new().into(),
})
}
.boxed()
}
fn http_request_stream(
&self,
_params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
async {
Err(ExecServerError::HttpRequest(
"unexpected streaming request".to_string(),
))
}
.boxed()
}
}
#[tokio::test]
async fn plaintext_hostname_redirects_are_rejected_before_dns_can_rebind() -> anyhow::Result<()> {
for (url, expected_error) in [
(
"http://mcp.example/start",
Some("non-loopback hostnames require HTTPS"),
),
("http://localhost/start", None),
("http://127.0.0.1/start", None),
("http://[::1]/start", None),
("https://mcp.example/start", None),
] {
let recorder = Arc::new(RecordingRedirectHttpClient::default());
let client = SameOriginRedirectHttpClient::new(recorder.clone());
let response = client
.http_request(HttpRequestParams {
headers: headers([("authorization", "Bearer sensitive-token")]),
..request(url)
})
.await;
if let Some(expected_error) = expected_error {
let error = response.expect_err("plaintext hostname redirects must fail");
assert!(error.to_string().contains(expected_error), "{error}");
} else {
assert_eq!(response?.status, 200);
}
let requests = recorder.requests.lock().expect("request recorder lock");
assert_eq!(requests.len(), if expected_error.is_some() { 1 } else { 2 });
}
Ok(())
}
#[tokio::test]
async fn same_origin_redirects_enforce_shared_timeout_and_hop_limit() {
for (delay, timeout_ms, expected_error, expected_requests) in [
(Duration::from_millis(100), 175, "timed out", 2),
(Duration::ZERO, 5_000, "redirect limit", MAX_REDIRECTS + 1),
] {
let recorder = Arc::new(RecordingRedirectHttpClient {
delay,
loop_redirects: true,
..Default::default()
});
let client = SameOriginRedirectHttpClient::new(recorder.clone());
let error = client
.http_request(HttpRequestParams {
method: "GET".to_string(),
body: None,
timeout_ms: Some(timeout_ms),
..request("https://mcp.example/loop")
})
.await
.expect_err("redirect loops must respect both limits");
assert!(error.to_string().contains(expected_error), "{error}");
let requests = recorder.requests.lock().expect("request recorder lock");
assert_eq!(requests.len(), expected_requests);
}
}
#[tokio::test]
async fn same_origin_redirects_preserve_method_body_and_headers() -> anyhow::Result<()> {
for (method, redirect_status, redirected_method) in [
("POST", 301, "GET"),
("POST", 302, "GET"),
("POST", 303, "GET"),
("HEAD", 303, "HEAD"),
("POST", 307, "POST"),
("GET", 307, "GET"),
("DELETE", 307, "DELETE"),
("POST", 308, "POST"),
] {
let server = MockServer::start().await;
Mock::given(path("/start"))
.respond_with(
ResponseTemplate::new(redirect_status).insert_header("location", "/final"),
)
.expect(1)
.mount(&server)
.await;
Mock::given(path("/final"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
let client =
SameOriginRedirectHttpClient::new(Environment::default_for_tests().get_http_client());
let expected_content_length = b"sensitive-body".len().to_string();
let mut params = HttpRequestParams {
method: method.to_string(),
headers: headers([
("x-api-key", "sensitive-key"),
("proxy-authorization", "sensitive-proxy-credentials"),
("referer", "https://stale.example/"),
]),
body: (method == "POST").then(|| b"sensitive-body".to_vec().into()),
stream_response: method != "DELETE",
..request(format!("{}/start", server.uri()))
};
if method == "POST" {
params.headers.extend(headers([
("content-type", "application/json"),
("content-encoding", "identity"),
("content-length", &expected_content_length),
]));
}
let status = if method == "DELETE" {
client.http_request(params).await?.status
} else {
client.http_request_stream(params).await?.0.status
};
assert_eq!(status, 200);
let requests = server.received_requests().await.expect("recorded requests");
let redirected = &requests[1];
let expected_referer = format!("{}/start", server.uri());
let body_preserved = redirected_method == "POST";
for (name, expected) in [
("x-api-key", Some("sensitive-key")),
("proxy-authorization", None),
("referer", Some(expected_referer.as_str())),
("content-type", body_preserved.then_some("application/json")),
("content-encoding", body_preserved.then_some("identity")),
(
"content-length",
body_preserved.then_some(expected_content_length.as_str()),
),
] {
assert_eq!(
redirected
.headers
.get(name)
.and_then(|value| value.to_str().ok()),
expected,
"unexpected redirected {name} header"
);
}
assert_eq!(
(redirected.method.as_str(), redirected.body.as_slice()),
(
redirected_method,
if body_preserved {
b"sensitive-body".as_slice()
} else {
b"".as_slice()
}
)
);
}
Ok(())
}
#[tokio::test]
async fn https_redirects_preserve_configured_and_helper_proxy_authorization() -> anyhow::Result<()>
{
for helper_enabled in [false, true] {
let recorder = Arc::new(RecordingRedirectHttpClient::default());
let inner: Arc<dyn HttpClient> = recorder.clone();
let directory = tempfile::tempdir()?;
let url = "https://mcp.example/start";
let inner = if helper_enabled {
with_http_headers_helper(
inner,
url,
PROXY_HEADERS_HELPER,
directory.path().to_path_buf(),
)?
} else {
inner
};
let client = SameOriginRedirectHttpClient::new(inner);
let response = client
.http_request(HttpRequestParams {
headers: if helper_enabled {
Vec::new()
} else {
headers([("Proxy-Authorization", "Bearer proxy-token")])
},
..request(url)
})
.await?;
let requests = recorder.requests.lock().expect("request recorder lock");
assert_eq!(
(
response.status,
requests.len(),
requests[1].url.as_str(),
requests[1]
.headers
.iter()
.find(|header| header.name.eq_ignore_ascii_case("proxy-authorization"))
.map(|header| header.value.as_str()),
),
(
200,
2,
"https://mcp.example/final",
Some("Bearer proxy-token"),
),
);
}
Ok(())
}
#[tokio::test]
async fn plaintext_helper_redirects_block_mcp_but_preserve_oauth_stop() -> anyhow::Result<()> {
for (request_id, redirect_policy) in [
("mcp-request-1", HttpRedirectPolicy::Follow),
("oauth-request-1", HttpRedirectPolicy::Stop),
] {
let server = MockServer::start().await;
Mock::given(path("/start"))
.respond_with(ResponseTemplate::new(307).insert_header("location", "/final"))
.expect(1)
.mount(&server)
.await;
let directory = tempfile::tempdir()?;
let url = format!("{}/start", server.uri());
let helper = with_http_headers_helper(
Environment::default_for_tests().get_http_client(),
&url,
PROXY_HEADERS_HELPER,
directory.path().to_path_buf(),
)?;
let client = SameOriginRedirectHttpClient::new(helper);
let response = client
.http_request_stream(HttpRequestParams {
request_id: request_id.to_string(),
redirect_policy,
stream_response: true,
..request(url)
})
.await;
match (redirect_policy, response) {
(HttpRedirectPolicy::Stop, Ok((response, _))) => assert_eq!(response.status, 307),
(HttpRedirectPolicy::Follow, Err(error)) => {
assert!(error.to_string().contains("Proxy-Authorization"));
}
_ => panic!("unexpected plaintext proxy-credential redirect behavior"),
}
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}
Ok(())
}
#[tokio::test]
async fn cross_origin_redirects_never_reach_their_destination() -> anyhow::Result<()> {
for status in [307, 308] {
for method in ["POST", "GET", "DELETE"] {
let destination = MockServer::start().await;
let server = MockServer::start().await;
Mock::given(path("/start"))
.respond_with(
ResponseTemplate::new(status)
.insert_header("location", format!("{}/private", destination.uri())),
)
.expect(1)
.mount(&server)
.await;
let client = SameOriginRedirectHttpClient::new(
Environment::default_for_tests().get_http_client(),
);
let params = HttpRequestParams {
method: method.to_string(),
headers: headers([("x-api-key", "sensitive-key")]),
body: (method == "POST").then(|| b"sensitive-body".to_vec().into()),
stream_response: method != "DELETE",
..request(format!("{}/start", server.uri()))
};
let error = if method == "DELETE" {
client
.http_request(params)
.await
.expect_err("cross-origin DELETE redirect must fail")
} else {
match client.http_request_stream(params).await {
Ok(_) => panic!("cross-origin {method} redirect must fail"),
Err(error) => error,
}
};
assert!(
error.to_string().contains("different origin"),
"cross-origin {method} redirect must explain its rejection: {error}"
);
assert!(destination.received_requests().await.unwrap().is_empty());
}
}
Ok(())
}

View File

@@ -0,0 +1,570 @@
use std::collections::HashSet;
use std::fmt;
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::path::Path;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::time::Duration;
use anyhow::Result;
use anyhow::anyhow;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
#[cfg(unix)]
use codex_utils_pty::process_group::kill_process_group;
use futures::FutureExt;
use futures::future::BoxFuture;
use futures::future::Shared;
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use serde::Deserialize;
use serde::de::MapAccess;
use serde::de::Visitor;
use tokio::io::AsyncReadExt;
use tokio::process::Child;
use tokio::process::Command;
use tokio::time::Instant;
use url::Origin;
use url::Url;
use crate::utils::create_env_for_mcp_server;
use crate::www_authenticate::insufficient_scope_challenge;
const HELPER_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_HELPER_OUTPUT_BYTES: usize = 64 * 1024;
type CachedHeaders = Shared<BoxFuture<'static, std::result::Result<Arc<HeaderMap>, Arc<str>>>>;
struct HttpHeadersProvider {
server_origin: Origin,
command: String,
cwd: PathBuf,
cache: Mutex<HeadersCache>,
}
struct HeadersCache {
// Identifies a cohort of rejected requests, not a credential version. Advance even after
// failed or unchanged refreshes so concurrent rejections share one helper invocation.
refresh_epoch: u64,
current: CachedHeaders,
refresh: Option<CachedHeaders>,
}
struct RequestHeaders {
refresh_epoch: u64,
values: Arc<HeaderMap>,
}
struct HttpHeadersClient {
inner: Arc<dyn HttpClient>,
provider: HttpHeadersProvider,
}
struct HelperProcess {
child: Child,
#[cfg(unix)]
process_group_id: u32,
#[cfg(windows)]
job: codex_utils_pty::JobObject,
}
struct RawHeaderEntries {
// Keep raw entries because ordinary map deserialization collapses exact duplicate keys.
entries: Vec<(String, String)>,
has_exact_duplicate: bool,
}
struct RawHeaderEntriesVisitor;
impl<'de> Visitor<'de> for RawHeaderEntriesVisitor {
type Value = RawHeaderEntries;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a JSON object of string header names and values")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut entries = Vec::with_capacity(map.size_hint().unwrap_or_default());
let mut names = HashSet::new();
let mut has_exact_duplicate = false;
while let Some((name, value)) = map.next_entry::<String, String>()? {
has_exact_duplicate |= !names.insert(name.clone());
entries.push((name, value));
}
Ok(RawHeaderEntries {
entries,
has_exact_duplicate,
})
}
}
impl<'de> Deserialize<'de> for RawHeaderEntries {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_map(RawHeaderEntriesVisitor)
}
}
impl Drop for HelperProcess {
fn drop(&mut self) {
#[cfg(unix)]
let _ = kill_process_group(self.process_group_id);
#[cfg(windows)]
let _ = self.job.terminate();
let _ = self.child.start_kill();
}
}
impl HttpHeadersProvider {
fn new(server_url: &str, command: &str, cwd: PathBuf) -> Result<Self> {
let command = command.to_string();
let cached = Self::helper_attempt(command.clone(), cwd.clone());
Ok(Self {
server_origin: Url::parse(server_url)?.origin(),
command,
cwd,
cache: Mutex::new(HeadersCache {
refresh_epoch: 0,
current: cached,
refresh: None,
}),
})
}
fn helper_attempt(command: String, cwd: PathBuf) -> CachedHeaders {
async move {
// Keep helper cleanup running after caller cancellation; dropping the set aborts it.
let mut tasks = tokio::task::JoinSet::new();
tasks.spawn(async move {
run_helper(&command, &cwd)
.await
.map(Arc::new)
.map_err(|error| Arc::<str>::from(error.to_string()))
});
tasks
.join_next()
.await
.ok_or_else(|| Arc::<str>::from("MCP HTTP headers helper task was unavailable"))?
.map_err(|_| Arc::<str>::from("MCP HTTP headers helper task failed"))?
}
.boxed()
.shared()
}
async fn headers(&self) -> Result<RequestHeaders, ExecServerError> {
let (refresh_epoch, current) = {
let cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
(cache.refresh_epoch, cache.current.clone())
};
current
.await
.map(|values| RequestHeaders {
refresh_epoch,
values,
})
.map_err(|error| ExecServerError::HttpRequest(error.to_string()))
}
async fn refresh(&self, rejected_epoch: u64) -> Result<Arc<HeaderMap>, ExecServerError> {
let attempt = {
let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
if cache.refresh_epoch != rejected_epoch {
cache.current.clone()
} else {
cache
.refresh
.get_or_insert_with(|| {
Self::helper_attempt(self.command.clone(), self.cwd.clone())
})
.clone()
}
};
let result = attempt.clone().await;
let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
if cache.refresh_epoch == rejected_epoch
&& cache
.refresh
.as_ref()
.is_some_and(|refresh| refresh.ptr_eq(&attempt))
{
cache.refresh_epoch = rejected_epoch.saturating_add(/*rhs*/ 1);
if result.is_ok() {
cache.current = attempt;
}
cache.refresh = None;
}
result.map_err(|error| ExecServerError::HttpRequest(error.to_string()))
}
}
/// Refreshes helper headers once after a same-origin POST returns 401/403, retrying only
/// when helper-provided values change. OAuth challenges survive failed or unchanged refreshes.
/// Helper Authorization is used only when the request has no explicit bearer/OAuth credential.
/// The helper is a short-lived process; independently managed daemons remain caller-owned.
pub fn with_http_headers_helper(
inner: Arc<dyn HttpClient>,
server_url: &str,
command: &str,
cwd: PathBuf,
) -> Result<Arc<dyn HttpClient>> {
let provider = HttpHeadersProvider::new(server_url, command, cwd)?;
Ok(Arc::new(HttpHeadersClient { inner, provider }))
}
impl HttpHeadersClient {
async fn prepare_request(
&self,
params: HttpRequestParams,
) -> Result<(HttpRequestParams, Option<RequestHeaders>, Option<Instant>), ExecServerError> {
let Ok(url) = Url::parse(&params.url) else {
return Ok((params, None, None));
};
if self.provider.server_origin != url.origin() {
return Ok((params, None, None));
}
let deadline = params
.timeout_ms
.map(|timeout_ms| Instant::now() + Duration::from_millis(timeout_ms));
let headers = match deadline {
Some(deadline) => tokio::time::timeout_at(deadline, self.provider.headers())
.await
.map_err(|_| {
ExecServerError::HttpRequest("HTTP request timed out".to_string())
})??,
None => self.provider.headers().await?,
};
let params = self.apply_headers(params, &headers.values, deadline)?;
Ok((params, Some(headers), deadline))
}
fn apply_headers(
&self,
mut params: HttpRequestParams,
headers: &HeaderMap,
deadline: Option<Instant>,
) -> Result<HttpRequestParams, ExecServerError> {
// TODO: Follow same-origin redirects once later hops cannot leak helper headers.
params.redirect_policy = HttpRedirectPolicy::Stop;
for (name, value) in headers {
// Explicit bearer tokens, MCP OAuth and token-endpoint client authentication win.
if name == http::header::AUTHORIZATION
&& params
.headers
.iter()
.any(|header| header.name.eq_ignore_ascii_case("authorization"))
{
continue;
}
params
.headers
.retain(|header| !header.name.eq_ignore_ascii_case(name.as_str()));
params.headers.push(HttpHeader {
name: name.to_string(),
value: std::str::from_utf8(value.as_bytes())
.map_err(|error| ExecServerError::HttpRequest(error.to_string()))?
.to_string(),
value_env_var: None,
});
}
if let Some(deadline) = deadline {
let remaining = deadline.saturating_duration_since(Instant::now());
params.timeout_ms = Some(
u64::try_from(remaining.as_millis())
.unwrap_or(u64::MAX)
.max(1),
);
}
Ok(params)
}
fn reject_proxy_authorization_redirect(
response: &HttpRequestResponse,
) -> Result<(), ExecServerError> {
if (300..400).contains(&response.status)
&& response
.headers
.iter()
.any(|header| header.name.eq_ignore_ascii_case("location"))
{
return Err(ExecServerError::HttpRequest(
"MCP HTTP redirect cannot safely replay Proxy-Authorization credentials"
.to_string(),
));
}
Ok(())
}
async fn retry_request(
&self,
params: HttpRequestParams,
rejected: RequestHeaders,
deadline: Option<Instant>,
response: &HttpRequestResponse,
) -> Option<HttpRequestParams> {
if !matches!(response.status, 401 | 403)
|| response.status == 403 && insufficient_scope_challenge(&response.headers).is_some()
{
return None;
}
// A rejection may be an OAuth challenge, so preserve it if the helper cannot improve it.
let refreshed = match deadline {
Some(deadline) => {
tokio::time::timeout_at(deadline, self.provider.refresh(rejected.refresh_epoch))
.await
.ok()?
.ok()?
}
None => self.provider.refresh(rejected.refresh_epoch).await.ok()?,
};
// Header names are user-defined. Compare effective helper values, excluding an
// Authorization that would be overridden, without treating JSON key order as a change.
let explicit_authorization = params
.headers
.iter()
.any(|header| header.name.eq_ignore_ascii_case("authorization"));
let differs = |left: &HeaderMap, right: &HeaderMap| {
left.iter().any(|(name, value)| {
(!explicit_authorization || name != http::header::AUTHORIZATION)
&& right.get(name) != Some(value)
})
};
if !differs(&rejected.values, &refreshed) && !differs(&refreshed, &rejected.values) {
return None;
}
self.apply_headers(params, &refreshed, deadline).ok()
}
async fn request<'a, T>(
&'a self,
params: HttpRequestParams,
send: impl Fn(HttpRequestParams) -> BoxFuture<'a, Result<T, ExecServerError>>,
response_headers: impl Fn(&T) -> &HttpRequestResponse,
) -> Result<T, ExecServerError> {
// OAuth validates redirect responses itself; only intercept MCP replay.
let mcp_redirect_was_stopped = params.redirect_policy == HttpRedirectPolicy::Stop
&& !params.request_id.starts_with("oauth-request-");
let original_headers = params
.method
.eq_ignore_ascii_case("POST")
.then(|| params.headers.clone());
let (params, headers, deadline) = self.prepare_request(params).await?;
let original = original_headers
.filter(|_| headers.is_some())
.map(|headers| {
let mut original = params.clone();
original.headers = headers;
original
});
let needs_redirect_check = |params: &HttpRequestParams| {
mcp_redirect_was_stopped
&& Url::parse(&params.url).is_ok_and(|url| url.scheme() == "http")
&& params
.headers
.iter()
.any(|header| header.name.eq_ignore_ascii_case("proxy-authorization"))
};
let prevent_proxy_authorization_redirect = needs_redirect_check(&params);
let response = send(params).await?;
if prevent_proxy_authorization_redirect {
Self::reject_proxy_authorization_redirect(response_headers(&response))?;
}
if let (Some(original), Some(headers)) = (original, headers)
&& let Some(retry) = self
.retry_request(original, headers, deadline, response_headers(&response))
.await
{
drop(response);
let prevent_proxy_authorization_redirect = needs_redirect_check(&retry);
let response = send(retry).await?;
if prevent_proxy_authorization_redirect {
Self::reject_proxy_authorization_redirect(response_headers(&response))?;
}
return Ok(response);
}
Ok(response)
}
}
impl HttpClient for HttpHeadersClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
self.request(
params,
|params| self.inner.http_request(params),
|response| response,
)
.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
self.request(
params,
|params| self.inner.http_request_stream(params),
|response| &response.0,
)
.boxed()
}
}
async fn run_helper(command: &str, cwd: &Path) -> Result<HeaderMap> {
#[cfg(windows)]
let shell = std::env::var_os("COMSPEC").unwrap_or_else(|| "cmd.exe".into());
#[cfg(not(windows))]
let shell = "sh";
// Match the repository's existing shell-command convention. The command is ordinary
// configuration and may be visible in local process metadata; credentials belong in the
// JSON output rather than in the command text.
let mut process = Command::new(shell);
#[cfg(windows)]
{
process.args(["/Q", "/D", "/C"]);
process.as_std_mut().raw_arg(format!(r#""{command}""#));
}
#[cfg(not(windows))]
process.args(["-c", command]);
#[cfg(unix)]
process.process_group(0);
process
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.current_dir(cwd)
// Match local MCP subprocess policy; arbitrary ambient variables are not inherited.
.env_clear()
.envs(create_env_for_mcp_server(/*extra_env*/ None, &[])?)
.kill_on_drop(true);
#[cfg(windows)]
let (child, job) = {
let job = codex_utils_pty::JobObject::create_without_breakaway()
.map_err(|error| anyhow!("MCP HTTP headers helper containment failed: {error}"))?;
let child = job
.spawn_contained(&mut process)
.map_err(|error| anyhow!("MCP HTTP headers helper failed to start: {error}"))?;
(child, job)
};
#[cfg(not(windows))]
let child = process
.spawn()
.map_err(|error| anyhow!("MCP HTTP headers helper failed to start: {error}"))?;
let mut process = HelperProcess {
#[cfg(unix)]
process_group_id: child
.id()
.ok_or_else(|| anyhow!("MCP HTTP headers helper process id was unavailable"))?,
child,
#[cfg(windows)]
job,
};
let output = tokio::time::timeout(HELPER_TIMEOUT, async {
let stdout = process
.child
.stdout
.take()
.ok_or_else(|| anyhow!("MCP HTTP headers helper stdout was unavailable"))?;
let mut output = Vec::new();
stdout
.take((MAX_HELPER_OUTPUT_BYTES + 1) as u64)
.read_to_end(&mut output)
.await?;
if output.len() > MAX_HELPER_OUTPUT_BYTES {
return Err(anyhow!("MCP HTTP headers helper output exceeds 64 KiB"));
}
let status = process.child.wait().await?;
if !status.success() {
return Err(anyhow!(
"MCP HTTP headers helper exited with status {status}"
));
}
Ok(output)
})
.await
.map_err(|_| anyhow!("MCP HTTP headers helper timed out after 10 seconds"))??;
parse_helper_output(output)
}
fn parse_helper_output(stdout: Vec<u8>) -> Result<HeaderMap> {
let stdout = String::from_utf8(stdout)
.map_err(|_| anyhow!("MCP HTTP headers helper wrote non-UTF-8 data"))?;
let mut deserializer = serde_json::Deserializer::from_str(stdout.trim());
let headers = RawHeaderEntries::deserialize(&mut deserializer)
.and_then(|headers| {
deserializer.end()?;
Ok(headers)
})
.map_err(|_| anyhow!("MCP HTTP headers helper must output a JSON object of strings"))?;
if headers.has_exact_duplicate {
return Err(anyhow!(
"MCP HTTP headers helper returned duplicate header names"
));
}
let mut parsed = HeaderMap::with_capacity(headers.entries.len());
for (name, value) in headers.entries {
let name = HeaderName::from_bytes(name.as_bytes())
.map_err(|_| anyhow!("MCP HTTP headers helper returned an invalid header name"))?;
// Helper values replace same-name configured headers, except explicit Authorization.
// Google IAP uses Proxy-Authorization alongside application Authorization. For HTTPS MCP
// URLs it is sent through the forward-proxy tunnel to IAP, not used as CONNECT auth.
if matches!(
name.as_str(),
"accept"
| "connection"
| "content-encoding"
| "content-length"
| "content-type"
| "host"
| "keep-alive"
| "last-event-id"
| "mcp-protocol-version"
| "mcp-session-id"
| "origin"
| "proxy-connection"
| "referer"
| "te"
| "trailer"
| "transfer-encoding"
| "upgrade"
) {
return Err(anyhow!(
"MCP HTTP headers helper returned a reserved header"
));
}
if parsed.contains_key(&name) {
return Err(anyhow!(
"MCP HTTP headers helper returned duplicate header names"
));
}
let value = HeaderValue::from_str(&value)
.map_err(|_| anyhow!("MCP HTTP headers helper returned an invalid header value"))?;
parsed.insert(name, value);
}
Ok(parsed)
}
#[cfg(test)]
#[path = "http_headers_tests.rs"]
mod tests;

View File

@@ -0,0 +1,579 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn helper_output_errors_do_not_echo_secrets() {
for output in [
br#"{"Host":"secret"}"#.as_slice(),
br#"{"secret":"secret","secret":"secret"}"#.as_slice(),
br#"{"secret":"secret","Secret":"secret"}"#.as_slice(),
] {
let error = parse_helper_output(output.to_vec()).expect_err("invalid helper output");
assert!(!error.to_string().contains("secret"));
}
}
#[cfg(unix)]
#[tokio::test]
async fn helper_attempt_is_shared_after_cancellation() {
use tempfile::tempdir;
let temp = tempdir().expect("temporary helper directory");
let cwd = temp
.path()
.canonicalize()
.expect("canonical helper directory");
let cancelled_invocations = cwd.join("cancelled-invocations");
let cancelled_finished = cwd.join("cancelled-helper-finished");
let cancelled = HttpHeadersProvider::new(
"https://example.com",
&format!(
"test \"$(pwd)\" = '{0}'; test -n \"$HOME\"; test -n \"$PATH\"; \
printf x >> '{1}'; sleep 0.2; printf x > '{2}'; \
printf '{{\"X-Gateway\":\"token\"}}'",
cwd.display(),
cancelled_invocations.display(),
cancelled_finished.display(),
),
cwd.clone(),
)
.expect("cancelled provider");
assert!(
tokio::time::timeout(Duration::from_millis(20), cancelled.headers())
.await
.is_err()
);
// Observe the helper finishing without polling the cancelled attempt again.
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
while !cancelled_finished.exists() {
tokio::time::sleep(Duration::from_millis(/*millis*/ 10)).await;
}
})
.await
.expect("cancelled helper finished independently");
assert!(cancelled.headers().await.is_ok());
assert_eq!(
std::fs::read_to_string(&cancelled_invocations).expect("cancelled invocation count"),
"x"
);
std::fs::remove_file(&cancelled_finished).expect("reset helper completion marker");
let headers = cancelled.headers().await.expect("cached headers");
assert!(
tokio::time::timeout(
Duration::from_millis(/*millis*/ 20),
cancelled.refresh(headers.refresh_epoch)
)
.await
.is_err()
);
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
while !cancelled_finished.exists() {
tokio::time::sleep(Duration::from_millis(/*millis*/ 10)).await;
}
})
.await
.expect("cancelled refresh finished independently");
assert_eq!(
cancelled.refresh(headers.refresh_epoch).await.unwrap(),
headers.values
);
assert_eq!(
std::fs::read_to_string(cancelled_invocations).expect("refresh invocation count"),
"xx"
);
let dropped_started = cwd.join("dropped-helper-started");
let dropped_finished = cwd.join("dropped-helper-finished");
let dropped = HttpHeadersProvider::new(
"https://example.com",
&format!(
"sleep 0.6; printf '%s\\n' \"$$\" > '{}'; sleep 30; printf x > '{}'",
dropped_started.display(),
dropped_finished.display(),
),
cwd,
)
.expect("dropped provider");
// A slow spawn must not race cancellation. Wait for the helper's PID before
// dropping the caller future, leaving the provider as the attempt's owner.
let dropped_pid = tokio::time::timeout(Duration::from_secs(5), async {
tokio::select! {
_ = dropped.headers() => panic!("helper completed before cancellation"),
pid = async {
loop {
match std::fs::read_to_string(&dropped_started) {
Ok(pid) if pid.ends_with('\n') => {
break pid.trim().parse::<libc::pid_t>().expect("helper PID");
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => panic!("failed to read helper PID: {error}"),
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
} => pid,
}
})
.await
.expect("helper started before cancellation");
assert!(dropped_pid > 0);
drop(dropped);
// Observe cleanup before HELPER_TIMEOUT or the helper's sleep could finish.
tokio::time::timeout(Duration::from_secs(2), async {
loop {
// SAFETY: signal 0 only checks whether the known child PID exists.
let result = unsafe {
libc::kill(dropped_pid, /* sig */ 0)
};
if result == -1 {
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::ESRCH)
);
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("dropping the provider terminated the helper");
assert!(!dropped_finished.exists());
}
#[tokio::test]
async fn nonzero_helper_exit_is_cached() {
let temp = tempfile::tempdir().expect("temporary helper directory");
let failed_invocations = temp.path().join("failed-invocations");
let command = if cfg!(windows) {
format!(
r#"echo x>>"{0}" & echo {{"X-Gateway":"valid"}} & exit /b 23"#,
failed_invocations.display()
)
} else {
format!(
"echo x >> '{0}'; printf '{{\"X-Gateway\":\"valid\"}}'; exit 23",
failed_invocations.display()
)
};
let failed = HttpHeadersProvider::new(
"https://example.com/mcp",
&command,
temp.path().to_path_buf(),
)
.expect("failed provider");
let first = failed.headers().await.err().expect("failed helper");
let second = failed.headers().await.err().expect("cached failure");
assert_eq!(first.to_string(), second.to_string());
let invocations = std::fs::read_to_string(failed_invocations).expect("failed invocation count");
assert_eq!(invocations.lines().count(), 1);
}
#[cfg(unix)]
#[tokio::test]
async fn failed_refresh_is_shared_without_replacing_credentials() {
let temp = tempfile::tempdir().expect("temporary helper directory");
let invocations = temp.path().join("invocations");
let command = format!(
"printf x >> '{0}'; count=$(wc -c < '{0}'); \
if [ \"$count\" -gt 1 ]; then exit 23; fi; \
printf '{{\"X-Gateway\":\"token\"}}'",
invocations.display(),
);
let provider = HttpHeadersProvider::new(
"https://example.com/mcp",
&command,
temp.path().to_path_buf(),
)
.expect("headers provider");
let original = provider.headers().await.expect("initial helper headers");
assert!(provider.refresh(original.refresh_epoch).await.is_err());
let stale = provider.refresh(original.refresh_epoch).await.unwrap();
assert_eq!(stale, original.values);
let next = provider.headers().await.expect("preserved credentials");
assert_eq!(next.values, original.values);
assert!(provider.refresh(next.refresh_epoch).await.is_err());
assert_eq!(std::fs::read_to_string(invocations).unwrap(), "xxx");
}
#[cfg(unix)]
#[tokio::test]
async fn connection_headers_are_cached_and_origin_bound() {
use axum::Router;
use axum::http::StatusCode;
use axum::response::Redirect;
use axum::routing::get;
use axum::routing::post;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use std::sync::Arc;
use tempfile::tempdir;
use tokio::net::TcpListener;
async fn handle(headers: axum::http::HeaderMap) -> StatusCode {
assert_eq!(
headers.get("proxy-authorization"),
Some(&HeaderValue::from_static("Bearer token"))
);
assert_eq!(
headers.get("x-label"),
Some(&HeaderValue::from_bytes("café".as_bytes()).unwrap())
);
StatusCode::NO_CONTENT
}
let temp = tempdir().expect("temporary helper directory");
let invocation_file = temp.path().join("invocations");
let cross_listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind cross-origin server");
let cross_url = format!("http://{}/start", cross_listener.local_addr().unwrap());
tokio::spawn(async move {
axum::serve(
cross_listener,
Router::new()
.route("/start", get(|| async { Redirect::temporary("/final") }))
.route("/final", get(|| async { StatusCode::NO_CONTENT })),
)
.await
.expect("serve cross-origin requests");
});
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind test server");
let url = format!("http://{}/mcp", listener.local_addr().unwrap());
let redirect_url = cross_url.clone();
let app = Router::new().route("/mcp", post(handle)).route(
"/redirect",
get(move || std::future::ready(Redirect::temporary(&redirect_url))),
);
tokio::spawn(async move {
axum::serve(listener, app)
.await
.expect("serve test requests");
});
let command = format!(
"printf x >> '{}'; printf '{{\"Proxy-Authorization\":\"Bearer token\",\"X-Label\":\"café\"}}'",
invocation_file.display(),
);
let inner: Arc<dyn HttpClient> = Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
)));
let client = with_http_headers_helper(inner, &url, &command, temp.path().to_path_buf())
.expect("headers helper client");
let request = |session: &str| HttpRequestParams {
method: "POST".to_string(),
url: url.clone(),
headers: Vec::new(),
body: None,
timeout_ms: Some(5_000),
redirect_policy: HttpRedirectPolicy::Follow,
request_id: session.to_string(),
stream_response: true,
};
let mut cross_request = request("cross-origin");
cross_request.method = "GET".to_string();
cross_request.url = cross_url;
assert_eq!(
client.http_request(cross_request).await.unwrap().status,
204
);
assert!(!invocation_file.exists());
let mut redirect_request = request("redirect");
redirect_request.method = "GET".to_string();
redirect_request.url = url.replace("/mcp", "/redirect");
assert_eq!(
client.http_request(redirect_request).await.unwrap().status,
307
);
let (left, right) = tokio::join!(
client.http_request_stream(request("session-a")),
client.http_request_stream(request("session-b"))
);
assert_eq!(left.expect("left request").0.status, 204);
assert_eq!(right.expect("right request").0.status, 204);
assert_eq!(
std::fs::read_to_string(&invocation_file).expect("helper invocation count"),
"x"
);
}
#[cfg(unix)]
#[tokio::test]
async fn concurrent_rejected_posts_share_one_headers_refresh() {
use axum::Router;
use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::post;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use tempfile::tempdir;
use tokio::net::TcpListener;
use tokio::sync::Barrier;
for (rejection, credential_header) in [
(StatusCode::UNAUTHORIZED, "Proxy-Authorization"),
(StatusCode::FORBIDDEN, "x-litellm-api-key"),
(StatusCode::UNAUTHORIZED, "Authorization"),
] {
let temp = tempdir().expect("temporary helper directory");
let invocations = temp.path().join("invocations");
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/mcp", listener.local_addr().unwrap());
let barrier = Arc::new(Barrier::new(/*n*/ 2));
let app =
Router::new()
.route(
"/mcp",
post(
move |State(barrier): State<Arc<Barrier>>,
headers: HeaderMap,
body: String| async move {
assert_eq!(body, "original request body");
assert_eq!(
headers.get("mcp-session-id"),
Some(&HeaderValue::from_static("existing-session"))
);
match headers[credential_header].to_str().unwrap() {
"Bearer token-1" => {
barrier.wait().await;
rejection
}
"Bearer token-2" => {
assert_eq!(headers["x-helper-only"], "configured");
StatusCode::NO_CONTENT
}
unexpected => panic!("unexpected test credential: {unexpected}"),
}
},
),
)
.with_state(barrier);
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let command = format!(
"printf x >> '{0}'; count=$(wc -c < '{0}'); count=$((count)); \
if [ \"$count\" -eq 1 ]; then \
printf '{{\"{credential_header}\":\"Bearer token-1\",\"X-Helper-Only\":\"stale\"}}'; \
else printf '{{\"{credential_header}\":\"Bearer token-%s\"}}' \"$count\"; fi",
invocations.display(),
);
let inner: Arc<dyn HttpClient> = Arc::new(RouteAwareHttpClient::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
));
let client = with_http_headers_helper(inner, &url, &command, temp.path().to_path_buf())
.expect("headers helper client");
let request = |request_id: &str| HttpRequestParams {
method: "POST".to_string(),
url: url.clone(),
headers: vec![
HttpHeader {
name: "X-Helper-Only".to_string(),
value: "configured".to_string(),
value_env_var: None,
},
HttpHeader {
name: "mcp-session-id".to_string(),
value: "existing-session".to_string(),
value_env_var: None,
},
],
body: Some(b"original request body".to_vec().into()),
timeout_ms: Some(5_000),
redirect_policy: HttpRedirectPolicy::Follow,
request_id: request_id.to_string(),
stream_response: true,
};
let (left, right) = tokio::join!(
client.http_request(request("left")),
client.http_request_stream(request("right")),
);
assert_eq!(left.expect("left request").status, 204);
assert_eq!(right.expect("right request").0.status, 204);
assert_eq!(
std::fs::read_to_string(invocations).expect("helper invocation count"),
"xx"
);
}
}
#[cfg(unix)]
#[tokio::test]
async fn helper_refresh_preserves_oauth_challenges_and_retries_at_most_once() {
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use tempfile::tempdir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
let unchanged = "printf '{\"Proxy-Authorization\":\"Bearer token\"}'";
let changed = "printf '{\"Proxy-Authorization\":\"Bearer token-%s\"}' \"$count\"";
let failed = "if [ \"$count\" -gt 1 ]; then exit 23; fi; printf '{\"Proxy-Authorization\":\"Bearer token\"}'";
let ignored_authorization = "if [ \"$count\" -eq 1 ]; then \
printf '{\"Authorization\":\"old\",\"X-A\":\"a\",\"X-B\":\"b\"}'; \
else printf '{\"X-B\":\"b\",\"X-A\":\"a\",\"Authorization\":\"new\"}'; fi";
for streamed in [false, true] {
for (helper_output, status, expected_mcp_requests) in [
(unchanged, 401, 1),
(failed, 401, 1),
(changed, 401, 2),
(changed, 403, 1),
(ignored_authorization, 401, 1),
] {
let (challenge, expected_helper_invocations) = if status == 403 {
(
r#"Bearer error="insufficient_scope", scope="tools:write""#,
"x",
)
} else {
(r#"Bearer realm="oauth""#, "xx")
};
let temp = tempdir().expect("temporary helper directory");
let invocations = temp.path().join("invocations");
let server = MockServer::start().await;
let url = format!("{}/mcp", server.uri());
Mock::given(method("POST"))
.and(header("authorization", "Bearer oauth-token"))
.respond_with(
ResponseTemplate::new(status)
.insert_header("www-authenticate", challenge)
.set_body_string("original OAuth challenge"),
)
.expect(expected_mcp_requests)
.mount(&server)
.await;
let command = format!(
"printf x >> '{0}'; count=$(wc -c < '{0}'); {helper_output}",
invocations.display(),
);
let inner: Arc<dyn HttpClient> = Arc::new(RouteAwareHttpClient::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
));
let client = with_http_headers_helper(inner, &url, &command, temp.path().to_path_buf())
.expect("headers helper client");
let params = HttpRequestParams {
method: "POST".to_string(),
url: url.clone(),
headers: vec![HttpHeader {
name: "aUtHoRiZaTiOn".to_string(),
value: "Bearer oauth-token".to_string(),
value_env_var: None,
}],
body: None,
timeout_ms: Some(5_000),
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "oauth-challenge".to_string(),
stream_response: streamed,
};
let (response, body) = if streamed {
let (response, mut body) = client
.http_request_stream(params)
.await
.expect("original OAuth response");
let mut bytes = Vec::new();
while let Some(chunk) = body.recv().await.expect("response body chunk") {
bytes.extend(chunk);
}
(response, bytes)
} else {
let response = client
.http_request(params)
.await
.expect("original OAuth response");
let bytes = response.body.clone().into_inner();
(response, bytes)
};
assert_eq!(response.status, status);
assert!(response.headers.iter().any(|header| {
header.name.eq_ignore_ascii_case("www-authenticate") && header.value == challenge
}));
assert_eq!(body, b"original OAuth challenge");
assert_eq!(
std::fs::read_to_string(invocations).expect("helper invocation count"),
expected_helper_invocations
);
}
}
}
#[cfg(unix)]
#[tokio::test]
async fn refresh_retry_rechecks_deadline_and_redirects() {
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
let temp = tempfile::tempdir().expect("helper directory");
let command = "if [ -e invoked ]; then printf '{\"Proxy-Authorization\":\"Bearer fresh\"}'; else touch invoked; printf '{}'; fi";
let client = HttpHeadersClient {
inner: Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
provider: HttpHeadersProvider::new(
"http://example.com/mcp",
command,
temp.path().to_path_buf(),
)
.expect("provider"),
};
let requests = Mutex::new(Vec::new());
let error = client
.request(
HttpRequestParams {
method: "POST".to_string(),
url: "http://example.com/mcp".to_string(),
headers: Vec::new(),
body: Some(b"original request".to_vec().into()),
timeout_ms: Some(5_000),
redirect_policy: HttpRedirectPolicy::Stop,
request_id: "mcp-request".to_string(),
stream_response: false,
},
|params| {
let mut requests = requests.lock().expect("requests lock");
let status = if requests.is_empty() { 401 } else { 307 };
requests.push(params);
async move {
tokio::time::sleep(Duration::from_millis(/*millis*/ 20)).await;
Ok(HttpRequestResponse {
status,
headers: vec![HttpHeader {
name: "Location".to_string(),
value: "http://example.com/redirected".to_string(),
value_env_var: None,
}],
body: Vec::new().into(),
})
}
.boxed()
},
|response| response,
)
.await
.expect_err("refreshed proxy redirect must fail");
assert!(
error
.to_string()
.contains("cannot safely replay Proxy-Authorization")
);
let requests = requests.into_inner().expect("recorded requests");
let [original, retry] = requests.as_slice() else {
panic!("expected exactly two requests");
};
assert!(retry.timeout_ms < original.timeout_ms);
let mut expected_retry = original.clone();
expected_retry.timeout_ms = retry.timeout_ms;
expected_retry.headers = vec![HttpHeader {
name: "proxy-authorization".to_string(),
value: "Bearer fresh".to_string(),
value_env_var: None,
}];
assert_eq!(retry, &expected_retry);
}

View File

@@ -0,0 +1,21 @@
use codex_api::AuthError;
use codex_api::SharedAuthProvider;
use futures::future::BoxFuture;
use http::HeaderMap;
/// Select request-scoped auth for each HTTP operation on a long-lived MCP connection.
pub trait AuthProviderResolver: Send + Sync {
fn resolve<'a>(
&'a self,
headers: &'a HeaderMap,
) -> BoxFuture<'a, Result<SharedAuthProvider, AuthError>>;
}
impl AuthProviderResolver for SharedAuthProvider {
fn resolve<'a>(
&'a self,
_headers: &'a HeaderMap,
) -> BoxFuture<'a, Result<SharedAuthProvider, AuthError>> {
Box::pin(async move { Ok(self.clone()) })
}
}

View File

@@ -0,0 +1,14 @@
use std::io;
use futures::future::BoxFuture;
use tokio::io::DuplexStream;
/// Recreates a fresh in-process MCP byte stream whenever the client needs one.
///
/// Implementations are expected to start the paired server side before
/// returning the client stream. The factory is retained by [`crate::RmcpClient`]
/// so reconnects can rebuild the transport without knowing which built-in
/// server produced it.
pub trait InProcessTransportFactory: Send + Sync {
fn open(&self) -> BoxFuture<'static, io::Result<DuplexStream>>;
}

View File

@@ -0,0 +1,121 @@
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_http_client;
mod ema_identity;
mod ema_resource;
mod enterprise_oauth_login;
mod event_notification_transport;
mod executor_process_transport;
mod http_client_adapter;
mod http_client_redirect;
mod http_headers;
mod http_request_auth;
mod in_process_transport;
mod local_stdio_io;
mod local_stdio_transport;
mod logging_client_handler;
mod oauth;
mod oauth_callback;
mod oauth_client_credentials;
mod oauth_client_registration;
mod oauth_http_client;
mod oauth_refresh_mode;
mod ordered_byte_transport;
mod perform_oauth_login;
mod program_resolver;
mod protocol_mode;
mod request_cancellation;
mod request_input;
mod rmcp_client;
mod service_error;
mod startup_error;
mod stdio_server_launcher;
mod tool_list_changes;
mod trace_context;
mod user_verification;
mod utils;
mod www_authenticate;
pub use auth_status::McpAuthState;
pub use auth_status::McpLoginRequirement;
pub use auth_status::OAuthDiscoveryTimeout;
pub use auth_status::StreamableHttpOAuthDiscovery;
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::EmaCredentialKind;
pub use ema_auth_policy::EmaErrorDetail;
pub use ema_auth_policy::EmaInvalidGrantSource;
pub use ema_auth_policy::EmaTokenSourceError;
pub use ema_auth_policy::validate_ema_auth_resource;
pub use ema_exchange::EmaAccessToken;
pub use ema_http_client::EmaAuthenticatedHttpClient;
pub use ema_http_client::EmaRequestAuthority;
pub use ema_http_client::EmaTokenSource;
pub use ema_identity::EmaIdpIdentity;
pub use ema_identity::EmaIdpIdentityRequest;
pub use ema_identity::account_oidc_identity_is_usable;
pub use ema_identity::account_oidc_issuer_hint;
pub use ema_identity::resolve_ema_account_idp_identity;
pub use ema_identity::resolve_ema_idp_identity;
pub use ema_identity::stored_ema_identity_is_usable;
pub use enterprise_oauth_login::EnterpriseOAuthCredentialGuard;
pub use enterprise_oauth_login::EnterpriseOAuthCredentials;
pub use enterprise_oauth_login::EnterpriseOAuthLoginHandle;
pub use enterprise_oauth_login::EnterpriseOAuthLoginRequest;
pub use enterprise_oauth_login::delete_enterprise_oauth_tokens;
pub use enterprise_oauth_login::perform_enterprise_oauth_login_return_url;
pub use event_notification_transport::EventNotificationReceiver;
pub use http_client_adapter::StreamableHttpRedirectMode;
pub use http_headers::with_http_headers_helper;
pub use http_request_auth::AuthProviderResolver;
pub use in_process_transport::InProcessTransportFactory;
pub use oauth::EmaCredentialLease;
pub use oauth::EmaCredentialSnapshot;
pub use oauth::StoredOAuthCredentialSnapshot;
pub use oauth::StoredOAuthTokens;
pub use oauth::WrappedOAuthTokenResponse;
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 oauth_refresh_mode::McpOAuthRefreshMode;
pub use perform_oauth_login::OAuthProviderError;
pub use perform_oauth_login::OauthLoginHandle;
pub use perform_oauth_login::perform_oauth_login;
pub use perform_oauth_login::perform_oauth_login_return_url;
pub use perform_oauth_login::perform_oauth_login_silent;
pub use perform_oauth_login::perform_oauth_login_with_callback_input;
pub use protocol_mode::McpProtocolMode;
pub use request_cancellation::RequestScope;
pub use rmcp::model::ElicitationAction;
pub use rmcp_client::CancellableEventStreamRequest;
pub use rmcp_client::Elicitation;
pub use rmcp_client::ElicitationResponse;
pub use rmcp_client::ListToolsWithConnectorIdResult;
pub use rmcp_client::RmcpClient;
pub use rmcp_client::SendElicitation;
pub use rmcp_client::StreamableHttpBearerToken;
pub use rmcp_client::ToolWithConnectorId;
pub use service_error::is_retryable_transport_error;
pub use service_error::mcp_error;
pub use service_error::request_error_code;
pub use service_error::request_timeout_error;
pub use startup_error::is_authentication_required_error;
pub use stdio_server_launcher::ExecutorStdioServerLauncher;
pub use stdio_server_launcher::LocalStdioServerLauncher;
pub use stdio_server_launcher::StdioServerLauncher;
pub use tool_list_changes::ToolListRevision;
pub use user_verification::UserVerificationReason;

View File

@@ -0,0 +1,63 @@
//! Platform-specific pipe ownership beneath the shared MCP framing layer.
use std::io;
use codex_utils_pty::Child;
use codex_utils_pty::Command;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub(super) type Stdin = tokio::net::windows::named_pipe::NamedPipeServer;
#[cfg(windows)]
pub(super) type Stdout = tokio::net::windows::named_pipe::NamedPipeServer;
#[cfg(windows)]
pub(super) type Stderr = tokio::net::windows::named_pipe::NamedPipeServer;
#[cfg(not(windows))]
pub(super) type Stdin = tokio::process::ChildStdin;
#[cfg(not(windows))]
pub(super) type Stdout = tokio::process::ChildStdout;
#[cfg(not(windows))]
pub(super) type Stderr = tokio::process::ChildStderr;
pub(super) struct LocalStdio {
pub(super) child: Child,
pub(super) stdin: Stdin,
pub(super) stdout: Stdout,
pub(super) stderr: Option<Stderr>,
}
pub(super) fn spawn(command: Command) -> io::Result<LocalStdio> {
#[cfg(windows)]
{
let mut command = command;
let pipes = windows::Stdio::configure(&mut command)?;
Ok(LocalStdio {
child: command.spawn()?,
stdin: pipes.stdin,
stdout: pipes.stdout,
stderr: Some(pipes.stderr),
})
}
#[cfg(not(windows))]
{
let mut child = command.spawn()?;
let stdin = child
.stdin
.take()
.ok_or_else(|| io::Error::other("MCP server stdin was not piped"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| io::Error::other("MCP server stdout was not piped"))?;
let stderr = child.stderr.take();
Ok(LocalStdio {
child,
stdin,
stdout,
stderr,
})
}
}

View File

@@ -0,0 +1,137 @@
//! IOCP-backed MCP pipes with private, preconnected child endpoints.
use std::fs::File;
use std::fs::OpenOptions;
use std::io;
use std::os::windows::fs::OpenOptionsExt;
use std::ptr;
use codex_utils_pty::ChildStdin;
use codex_utils_pty::Command;
use tokio::net::windows::named_pipe::NamedPipeServer;
use tokio::net::windows::named_pipe::PipeMode;
use tokio::net::windows::named_pipe::ServerOptions;
use uuid::Uuid;
use windows_sys::Win32::Foundation::GENERIC_WRITE;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::SDDL_REVISION_1;
use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::SECURITY_IDENTIFICATION;
use windows_sys::Win32::Storage::FileSystem::SECURITY_SQOS_PRESENT;
pub(super) struct Stdio {
pub(super) stdin: NamedPipeServer,
pub(super) stdout: NamedPipeServer,
pub(super) stderr: NamedPipeServer,
}
impl Stdio {
pub(super) fn configure(command: &mut Command) -> io::Result<Self> {
let security = PipeSecurity::new()?;
let (stdin, child_stdin) = connected_pipe(Direction::ChildReads, &security)?;
let (stdout, child_stdout) = connected_pipe(Direction::ChildWrites, &security)?;
let (stderr, child_stderr) = connected_pipe(Direction::ChildWrites, &security)?;
command
.stdin(ChildStdin::File(child_stdin.into()))
.stdout_handle(child_stdout.into())
.stderr_handle(child_stderr.into());
Ok(Self {
stdin,
stdout,
stderr,
})
}
}
enum Direction {
ChildReads,
ChildWrites,
}
fn connected_pipe(
direction: Direction,
security: &PipeSecurity,
) -> io::Result<(NamedPipeServer, File)> {
let name = format!(r"\\.\pipe\codex-mcp-{}", Uuid::new_v4().simple());
let mut options = ServerOptions::new();
options
.pipe_mode(PipeMode::Byte)
.first_pipe_instance(true)
.max_instances(1)
.reject_remote_clients(true);
let mut client = OpenOptions::new();
client.security_qos_flags(SECURITY_IDENTIFICATION | SECURITY_SQOS_PRESENT);
match direction {
Direction::ChildReads => {
options.access_inbound(false).access_outbound(true);
client.read(true);
}
Direction::ChildWrites => {
options.access_inbound(true).access_outbound(false);
// Helpers can query the blocking mode of their stdout and stderr pipes.
client.access_mode(GENERIC_WRITE | FILE_READ_ATTRIBUTES);
}
}
let mut attributes = SECURITY_ATTRIBUTES {
nLength: u32::try_from(size_of::<SECURITY_ATTRIBUTES>()).map_err(io::Error::other)?,
lpSecurityDescriptor: security.0,
bInheritHandle: 0,
};
// SAFETY: attributes and its owned descriptor stay live through CreateNamedPipeW.
// The kernel copies the descriptor; the returned pipe owns its separate handle.
let server = unsafe {
options.create_with_security_attributes_raw(&name, ptr::from_mut(&mut attributes).cast())
}?;
let child = client.open(&name)?;
// The child endpoint is already connected. Complete registration on the
// launcher's blocking thread before the child is allowed to execute.
tokio::runtime::Handle::current().block_on(server.connect())?;
Ok((server, child))
}
struct PipeSecurity(PSECURITY_DESCRIPTOR);
impl PipeSecurity {
fn new() -> io::Result<Self> {
// Only the pipe owner and SYSTEM can open the single local instance.
let sddl: Vec<u16> = "D:P(A;;GA;;;SY)(A;;GA;;;OW)"
.encode_utf16()
.chain(std::iter::once(0))
.collect();
let mut descriptor = ptr::null_mut();
// SAFETY: sddl is NUL-terminated and descriptor is a valid writable out
// pointer. On success Windows transfers a LocalFree-owned allocation.
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
SDDL_REVISION_1,
&mut descriptor,
ptr::null_mut(),
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(Self(descriptor))
}
}
impl Drop for PipeSecurity {
fn drop(&mut self) {
// SAFETY: this is the sole owner of the successful SDDL conversion's
// allocation; no pipe creation call retains a pointer to it.
if !unsafe { LocalFree(self.0) }.is_null() {
tracing::warn!(
"Failed to release MCP pipe security descriptor: {}",
io::Error::last_os_error()
);
}
}
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod tests;

View File

@@ -0,0 +1,37 @@
//! Checks the access rights of the synchronous pipe endpoint inherited by a helper.
#![cfg(test)]
use std::io;
use std::os::windows::io::AsRawHandle;
use std::ptr;
use windows_sys::Win32::System::Pipes::GetNamedPipeHandleStateW;
use super::Direction;
use super::PipeSecurity;
use super::connected_pipe;
#[test]
fn child_can_read_output_pipe_mode() -> io::Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
let _guard = runtime.enter();
let (_server, child) = connected_pipe(Direction::ChildWrites, &PipeSecurity::new()?)?;
let mut mode = 0;
// SAFETY: the file owns a live pipe handle and mode is writable for the call.
if unsafe {
GetNamedPipeHandleStateW(
child.as_raw_handle(),
&mut mode,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
/*nmaxusernamesize*/ 0,
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(())
}

View File

@@ -0,0 +1,294 @@
//! Protocol framing and child lifetime for locally spawned MCP servers.
//!
//! Process creation is platform-specific; protocol selection and shutdown are shared.
use std::future::Future;
use std::io;
use std::time::Duration;
use futures::FutureExt;
use rmcp::model::ClientRequest;
use rmcp::model::ErrorCode;
use rmcp::model::JsonRpcMessage;
use rmcp::model::RequestId;
use rmcp::model::ServerResult;
use rmcp::service::RoleClient;
use rmcp::service::RxJsonRpcMessage;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::Transport;
use rmcp::transport::async_rw::AsyncRwTransport;
use tokio::io::AsyncRead;
use tokio::sync::oneshot;
use crate::bounded_stdio_transport::BoundedStdioTransport;
use crate::local_stdio_io::LocalStdio;
use crate::local_stdio_io::Stderr;
use crate::local_stdio_io::Stdin;
use crate::protocol_mode::McpProtocolMode;
use codex_utils_pty::Child;
pub(super) struct LocalStdioTransport {
child: Option<Box<Child>>,
transport: StdioTransport,
discovery: Option<Discovery>,
}
pub(super) enum DiscoveryOutcome {
Reply,
RetryLegacy,
Late {
reply: Box<RxJsonRpcMessage<RoleClient>>,
after_reoffer: bool,
},
}
struct Discovery {
finished: Option<oneshot::Sender<DiscoveryOutcome>>,
outcome: Option<DiscoveryOutcome>,
retry_at: Option<tokio::time::Instant>,
probe_id: Option<RequestId>,
initialize_id: Option<RequestId>,
}
impl Drop for Discovery {
fn drop(&mut self) {
// A version re-offer can supersede an earlier reply. Publish only when startup ends.
if let Some(tx) = self.finished.take()
&& let Some(outcome) = self.outcome.take()
{
let _ = tx.send(outcome);
}
}
}
impl Discovery {
/// Track discovery replies and skip messages that do not answer the active handshake.
fn handle_reply(&mut self, message: &mut Option<RxJsonRpcMessage<RoleClient>>) -> bool {
let Some(reply) = message.as_ref() else {
self.outcome.get_or_insert(DiscoveryOutcome::RetryLegacy);
return false;
};
let (id, modern) = match reply {
JsonRpcMessage::Response(response) => (
Some(&response.id),
matches!(response.result, ServerResult::DiscoverResult(_)),
),
JsonRpcMessage::Error(error) => (
error.id.as_ref(),
matches!(
error.error.code,
ErrorCode::UNSUPPORTED_PROTOCOL_VERSION
| ErrorCode::HEADER_MISMATCH
| ErrorCode::MISSING_REQUIRED_CLIENT_CAPABILITY
),
),
_ => return false,
};
let matches_id = |sent: &RequestId| match (sent, id) {
(RequestId::Number(sent), Some(RequestId::String(received))) => {
received.parse::<i64>().ok() == Some(*sent)
}
(_, Some(received)) => sent == received,
(_, None) => false,
};
let legacy = self.initialize_id.is_some();
let matches_probe = self.probe_id.as_ref().is_some_and(matches_id);
let idless = self.probe_id.is_some() && id.is_none();
if legacy
&& (matches_probe || idless)
&& matches!(reply, JsonRpcMessage::Error(error) if error.error.code == ErrorCode::METHOD_NOT_FOUND)
{
// If initialize also fails, try it as the first request on a fresh helper.
self.outcome.get_or_insert(DiscoveryOutcome::RetryLegacy);
}
// With one request rmcp accepts an ID-less error. With two, only a modern
// protocol error can be classified as a discovery reply without an ID.
if matches_probe || (idless && (!legacy || modern)) {
self.probe_id = None;
if legacy {
// Auto sent initialize before receiving the reply to its earlier probe.
if !modern && matches!(reply, JsonRpcMessage::Error(_)) {
return true;
}
// Stop the obsolete initialize and let the caller classify the reply.
self.outcome = message.take().map(|reply| DiscoveryOutcome::Late {
reply: Box::new(reply),
after_reoffer: matches!(self.outcome, Some(DiscoveryOutcome::Reply)),
});
return false;
}
if modern {
self.retry_at = None;
self.outcome = Some(DiscoveryOutcome::Reply);
}
} else if self.probe_id.is_some()
&& id.is_some()
&& !self.initialize_id.as_ref().is_some_and(matches_id)
{
// rmcp would abort the handshake before reading the reply to discover or initialize.
return true;
} else if legacy && matches!(reply, JsonRpcMessage::Response(_)) {
// Once initialize wins, rmcp owns the session and can ignore the obsolete probe.
self.probe_id = None;
self.retry_at = None;
self.outcome = Some(DiscoveryOutcome::Reply);
}
false
}
}
enum StdioTransport {
/// Preserve rmcp's existing framing for servers using the initialize handshake.
Legacy(AsyncRwTransport<RoleClient, Box<dyn AsyncRead + Unpin + Send>, Stdin>),
/// Bound frames and skip messages unknown to the client during 2026-07-28 discovery.
Modern(BoundedStdioTransport),
Closed,
}
impl LocalStdioTransport {
pub(super) fn new(
stdio: LocalStdio,
program_name: String,
protocol_mode: McpProtocolMode,
) -> (Self, Option<Stderr>) {
let LocalStdio {
child,
stdin,
stdout,
stderr,
} = stdio;
let transport = match protocol_mode {
McpProtocolMode::Legacy => {
StdioTransport::Legacy(AsyncRwTransport::new(Box::new(stdout), stdin))
}
McpProtocolMode::V20260728 | McpProtocolMode::DiscoverLocalStdio => {
StdioTransport::Modern(BoundedStdioTransport::new(stdin, stdout, program_name))
}
};
(
Self {
child: Some(Box::new(child)),
transport,
discovery: None,
},
stderr,
)
}
pub(super) fn watch_discovery(
&mut self,
timeout: Option<Duration>,
) -> oneshot::Receiver<DiscoveryOutcome> {
let (tx, rx) = oneshot::channel();
self.discovery = Some(Discovery {
finished: Some(tx),
outcome: None,
// Aim for three seconds of discovery. Reserve at least a quarter of short
// timeouts and half of longer ones for a fresh initialize.
retry_at: timeout.and_then(|limit| {
let probe_timeout = Duration::from_secs(3).clamp(limit / 2, limit - limit / 4);
tokio::time::Instant::now().checked_add(probe_timeout)
}),
probe_id: None,
initialize_id: None,
});
rx
}
#[cfg(unix)]
pub(super) fn take_child(&mut self) -> Option<Box<Child>> {
self.child.take()
}
}
impl Transport<RoleClient> for LocalStdioTransport {
type Error = io::Error;
fn send(
&mut self,
item: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = io::Result<()>> + Send + 'static {
if self.discovery.as_ref().is_some_and(|probe| {
probe
.finished
.as_ref()
.is_none_or(oneshot::Sender::is_closed)
}) {
self.discovery = None;
}
if let Some(probe) = &mut self.discovery
&& let JsonRpcMessage::Request(request) = &item
&& matches!(request.request, ClientRequest::DiscoverRequest(_))
{
probe.probe_id = Some(request.id.clone());
}
if let Some(probe) = &mut self.discovery
&& let JsonRpcMessage::Request(request) = &item
&& matches!(request.request, ClientRequest::InitializeRequest(_))
&& matches!(self.transport, StdioTransport::Modern(_))
{
let StdioTransport::Modern(transport) =
std::mem::replace(&mut self.transport, StdioTransport::Closed)
else {
unreachable!();
};
match transport.into_legacy_pipes() {
Ok((stdout, stdin)) => {
probe.initialize_id = Some(request.id.clone());
self.transport = StdioTransport::Legacy(AsyncRwTransport::new(stdout, stdin));
}
Err(error) => return futures::future::err(error).boxed(),
}
}
match &mut self.transport {
StdioTransport::Legacy(transport) => transport.send(item).boxed(),
StdioTransport::Modern(transport) => transport.send(item).boxed(),
StdioTransport::Closed => futures::future::err(io::Error::new(
io::ErrorKind::BrokenPipe,
"MCP stdin closed",
))
.boxed(),
}
}
async fn receive(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
loop {
let receive = async {
match &mut self.transport {
StdioTransport::Legacy(transport) => transport.receive().await,
StdioTransport::Modern(transport) => transport.receive().await,
StdioTransport::Closed => None,
}
};
let mut message = match self.discovery.as_ref().and_then(|probe| probe.retry_at) {
Some(retry_at) => tokio::time::timeout_at(retry_at, receive)
.await
.unwrap_or_default(),
None => receive.await,
};
if self
.discovery
.as_mut()
.is_some_and(|probe| probe.handle_reply(&mut message))
{
continue;
}
return message;
}
}
async fn close(&mut self) -> io::Result<()> {
match &mut self.transport {
StdioTransport::Legacy(transport) => transport.close().await?,
StdioTransport::Modern(transport) => transport.close().await?,
StdioTransport::Closed => {}
}
let Some(child) = &mut self.child else {
return Ok(());
};
match tokio::time::timeout(Duration::from_secs(3), child.wait()).await {
Ok(status) => status.map(|_| ()),
Err(_) => child.kill().await,
}
}
}

View File

@@ -0,0 +1,141 @@
use std::sync::Arc;
use rmcp::ClientHandler;
use rmcp::RoleClient;
use rmcp::model::CancelledNotificationParam;
use rmcp::model::ClientConfig;
use rmcp::model::ElicitRequestParams;
use rmcp::model::ElicitResult;
#[allow(deprecated)]
use rmcp::model::LoggingLevel;
#[allow(deprecated)]
use rmcp::model::LoggingMessageNotificationParam;
use rmcp::model::ProgressNotificationParam;
use rmcp::model::ResourceUpdatedNotificationParam;
use rmcp::service::NotificationContext;
use rmcp::service::RequestContext;
use tracing::debug;
use tracing::error;
use tracing::info;
use tracing::warn;
use crate::rmcp_client::Elicitation;
use crate::rmcp_client::SendElicitation;
#[derive(Clone)]
pub(crate) struct LoggingClientHandler {
client_info: ClientConfig,
send_elicitation: Arc<SendElicitation>,
}
impl LoggingClientHandler {
pub(crate) fn new(client_info: ClientConfig, send_elicitation: SendElicitation) -> Self {
Self {
client_info,
send_elicitation: Arc::new(send_elicitation),
}
}
}
impl ClientHandler for LoggingClientHandler {
async fn create_elicitation(
&self,
request: ElicitRequestParams,
context: RequestContext<RoleClient>,
) -> Result<ElicitResult, rmcp::ErrorData> {
(self.send_elicitation)(context.id, Elicitation::Mcp(request))
.await
.map(Into::into)
.map_err(|err| rmcp::ErrorData::internal_error(err.to_string(), None))
}
async fn on_cancelled(
&self,
params: CancelledNotificationParam,
_context: NotificationContext<RoleClient>,
) {
info!(
"MCP server cancelled request (request_id: {:?}, reason: {:?})",
params.request_id, params.reason
);
}
async fn on_progress(
&self,
params: ProgressNotificationParam,
_context: NotificationContext<RoleClient>,
) {
info!(
"MCP server progress notification (token: {:?}, progress: {}, total: {:?}, message: {:?})",
params.progress_token, params.progress, params.total, params.message
);
}
async fn on_resource_updated(
&self,
params: ResourceUpdatedNotificationParam,
_context: NotificationContext<RoleClient>,
) {
info!("MCP server resource updated (uri: {})", params.uri);
}
async fn on_resource_list_changed(&self, _context: NotificationContext<RoleClient>) {
info!("MCP server resource list changed");
}
async fn on_tool_list_changed(&self, _context: NotificationContext<RoleClient>) {
info!("MCP server tool list changed");
}
async fn on_prompt_list_changed(&self, _context: NotificationContext<RoleClient>) {
info!("MCP server prompt list changed");
}
fn get_info(&self) -> ClientConfig {
self.client_info.clone()
}
#[allow(deprecated)]
async fn on_logging_message(
&self,
params: LoggingMessageNotificationParam,
_context: NotificationContext<RoleClient>,
) {
let LoggingMessageNotificationParam {
level,
logger,
data,
..
} = params;
let logger = logger.as_deref();
match level {
LoggingLevel::Emergency
| LoggingLevel::Alert
| LoggingLevel::Critical
| LoggingLevel::Error => {
error!(
"MCP server log message (level: {:?}, logger: {:?}, data: {})",
level, logger, data
);
}
LoggingLevel::Warning => {
warn!(
"MCP server log message (level: {:?}, logger: {:?}, data: {})",
level, logger, data
);
}
LoggingLevel::Notice | LoggingLevel::Info => {
info!(
"MCP server log message (level: {:?}, logger: {:?}, data: {})",
level, logger, data
);
}
LoggingLevel::Debug => {
debug!(
"MCP server log message (level: {:?}, logger: {:?}, data: {})",
level, logger, data
);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,444 @@
//! Adapts Codex's pinned credential storage to RMCP-owned OAuth refreshes.
//!
//! Attach this store only after `AuthorizationManager::initialize_from_store` completes
//! against an in-memory store. Initialization may save tokenless client credentials, which
//! this refresh adapter does not support.
//!
//! Ordinary token reads use the cached credentials. Refresh-guard acquisition rereads
//! the pinned store before RMCP exchanges the token and saves the result. Codex
//! preparation rechecks freshness under that guard before asking RMCP to refresh.
//! Saves and clears require an active guard; no store operation reacquires the lock.
//! The runtime snapshot advances only for credentials compatible with this connection,
//! so replacement logins still cause a rebuild.
//! Synchronous store operations run off the Tokio workers so caller deadlines remain pollable.
//! Blocking mutations retain the caller's transaction guard even if their await is cancelled.
//! Definitive refresh rejection removes only refresh capability, retaining the existing record
//! format and access token. Shared direct-keyring entries are retired only in this runtime until
//! cross-home locking exists. A local rejected snapshot also prevents reuse after a write failure.
use std::sync::Arc;
use std::sync::Weak;
use anyhow::Context;
use anyhow::Result;
use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use futures::future::BoxFuture;
use oauth2::Scope;
use oauth2::TokenResponse;
use rmcp::transport::auth::AuthError;
use rmcp::transport::auth::AuthorizationManager;
use rmcp::transport::auth::CredentialRefreshGuard;
use rmcp::transport::auth::CredentialStore;
use rmcp::transport::auth::StoredCredentials;
use tokio::sync::Mutex;
use tracing::warn;
use crate::oauth_client_credentials::OAuthClientCredentials;
use crate::oauth_http_client::PROACTIVE_REFRESH_TIMEOUT;
use super::RefreshCredentialLock;
use super::ResolvedOAuthCredentialStore;
use super::StoredOAuthTokens;
use super::WrappedOAuthTokenResponse;
use super::normalized_oauth_credentials;
use super::refresh_expires_in_from_timestamp;
use super::refresh_transaction::REFRESH_REQUEST_TIMEOUT;
use super::resolved_store::Backend;
use super::token_needs_refresh;
use super::validate_refresh_token_issuer;
#[derive(Clone)]
pub(crate) struct OAuthCredentialStore<K = DefaultKeyringStore> {
inner: Arc<OAuthCredentialStoreInner<K>>,
held_refresh_guard: Option<Arc<RefreshCredentialLock>>,
}
struct OAuthCredentialStoreInner<K> {
server_name: String,
url: String,
client_id: String,
issuer: Option<String>,
store: ResolvedOAuthCredentialStore,
keyring: K,
oauth_config: Option<McpServerOAuthConfig>,
last_credentials: Mutex<Option<StoredOAuthTokens>>,
rejected_credentials: Mutex<Option<StoredOAuthTokens>>,
refresh_guard: Mutex<Weak<RefreshCredentialLock>>,
}
impl<K: KeyringStore + Clone + 'static> OAuthCredentialStore<K> {
pub(crate) fn new(
tokens: StoredOAuthTokens,
store: ResolvedOAuthCredentialStore,
keyring: K,
oauth_config: Option<McpServerOAuthConfig>,
) -> Self {
Self {
inner: Arc::new(OAuthCredentialStoreInner {
server_name: tokens.server_name.clone(),
url: tokens.url.clone(),
client_id: tokens.client_id.clone(),
issuer: tokens.bound_issuer().map(str::to_owned),
store,
keyring,
oauth_config,
last_credentials: Mutex::new(Some(tokens)),
rejected_credentials: Mutex::new(None),
refresh_guard: Mutex::new(Weak::new()),
}),
held_refresh_guard: None,
}
}
pub(crate) async fn refresh_if_needed(&self, manager: &mut AuthorizationManager) -> Result<()> {
let guard = self.acquire_transaction_guard().await?;
let tokens = self
.inner
.last_credentials
.lock()
.await
.clone()
.ok_or(AuthError::AuthorizationRequired)?;
if !token_needs_refresh(tokens.expires_at) {
return Ok(());
}
let metadata = manager.resolve_metadata().await?.metadata;
validate_refresh_token_issuer(&metadata, &tokens)?;
manager.set_metadata(metadata);
manager.configure_client_id(&tokens.client_id)?;
OAuthClientCredentials::resolve(self.inner.oauth_config.as_ref())?.configure_for_refresh(
manager,
&self.inner.url,
&tokens.client_id,
)?;
// Reuse the guard for RMCP's exchange and save after the locked freshness check.
manager.set_credential_store(Self {
inner: Arc::clone(&self.inner),
held_refresh_guard: Some(guard),
});
let result = PROACTIVE_REFRESH_TIMEOUT
.scope(REFRESH_REQUEST_TIMEOUT, manager.refresh_token())
.await;
manager.set_credential_store(self.clone());
match result {
Ok(_) => Ok(()),
Err(AuthError::TokenRefreshRejected(_)) => Err(AuthError::AuthorizationRequired.into()),
Err(error) => Err(error.into()),
}
}
pub(crate) async fn stored_credentials(&self) -> Option<StoredOAuthTokens> {
normalized_oauth_credentials(self.inner.last_credentials.lock().await.as_ref())
}
pub(crate) async fn acquire_transaction_guard(
&self,
) -> Result<Arc<RefreshCredentialLock>, AuthError> {
let guard = Arc::new(
RefreshCredentialLock::acquire_for_server(&self.inner.server_name, &self.inner.url)
.await
.map_err(credential_store_error)?,
);
let inner = Arc::clone(&self.inner);
let tokens = tokio::task::spawn_blocking(move || {
inner
.store
.load(&inner.keyring, &inner.server_name, &inner.url)
})
.await
.context("OAuth credential load task failed")
.map_err(credential_store_error)?
.map_err(credential_store_error)?
.ok_or(AuthError::AuthorizationRequired)?;
if normalized_oauth_credentials(Some(&tokens))
== *self.inner.rejected_credentials.lock().await
{
return Err(AuthError::AuthorizationRequired);
}
self.validate_connection(&tokens)?;
*self.inner.last_credentials.lock().await = Some(tokens);
*self.inner.refresh_guard.lock().await = Arc::downgrade(&guard);
Ok(guard)
}
fn validate_connection(&self, tokens: &StoredOAuthTokens) -> Result<(), AuthError> {
if tokens.client_id != self.inner.client_id
|| tokens.bound_issuer() != self.inner.issuer.as_deref()
|| tokens.has_refresh_token() && tokens.bound_issuer().is_none()
{
warn!(
server_name = %self.inner.server_name,
"stored OAuth credentials no longer match this connection's client and issuer; authorization must be rebuilt"
);
return Err(AuthError::AuthorizationRequired);
}
if !tokens.has_refresh_token() && !tokens.access_token_is_usable_without_refresh() {
return Err(AuthError::TokenExpired);
}
Ok(())
}
}
// Spell out RMCP's object-safe boxed-future interface without introducing async-trait here.
impl<K: KeyringStore + Clone + 'static> CredentialStore for OAuthCredentialStore<K> {
fn load<'life0, 'async_trait>(
&'life0 self,
) -> BoxFuture<'async_trait, Result<Option<StoredCredentials>, AuthError>>
where
'life0: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
Ok(self
.inner
.last_credentials
.lock()
.await
.as_ref()
.map(rmcp_credentials))
})
}
fn save<'life0, 'async_trait>(
&'life0 self,
credentials: StoredCredentials,
) -> BoxFuture<'async_trait, Result<(), AuthError>>
where
'life0: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
let mut token_response = credentials
.token_response
.ok_or(AuthError::AuthorizationRequired)?;
// Codex stores granted scopes in the token response rather than a separate field.
if token_response.scopes().is_none() && !credentials.granted_scopes.is_empty() {
token_response.set_scopes(Some(
credentials
.granted_scopes
.into_iter()
.map(Scope::new)
.collect(),
));
}
// The SDK's receipt time, rather than the time this save completes, owns expiry.
if credentials.token_received_at.is_none() {
token_response.set_expires_in(None);
}
let expires_at = credentials.token_received_at.and_then(|received_at| {
token_response.expires_in().map(|expires_in| {
received_at
.saturating_mul(1000)
.saturating_add(u64::try_from(expires_in.as_millis()).unwrap_or(u64::MAX))
})
});
let tokens = StoredOAuthTokens {
server_name: self.inner.server_name.clone(),
url: self.inner.url.clone(),
issuer: credentials.issuer,
client_id: credentials.client_id,
token_response: WrappedOAuthTokenResponse(token_response),
expires_at,
};
self.validate_connection(&tokens)?;
let inner = Arc::clone(&self.inner);
let guard = self
.inner
.refresh_guard
.lock()
.await
.upgrade()
.context("OAuth credential mutation requires an active refresh guard")
.map_err(credential_store_error)?;
let tokens = tokio::task::spawn_blocking(move || -> Result<StoredOAuthTokens> {
let _guard = guard;
inner.store.save_with_refresh_telemetry(
&inner.keyring,
&inner.server_name,
&tokens,
)?;
Ok(tokens)
})
.await
.context("OAuth credential save task failed")
.map_err(credential_store_error)?
.map_err(credential_store_error)?;
*self.inner.last_credentials.lock().await = Some(tokens);
Ok(())
})
}
fn clear<'life0, 'async_trait>(&'life0 self) -> BoxFuture<'async_trait, Result<(), AuthError>>
where
'life0: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
let inner = Arc::clone(&self.inner);
let guard = self
.inner
.refresh_guard
.lock()
.await
.upgrade()
.context("OAuth credential mutation requires an active refresh guard")
.map_err(credential_store_error)?;
tokio::task::spawn_blocking(move || -> Result<()> {
let _guard = guard;
inner
.store
.delete(&inner.keyring, &inner.server_name, &inner.url)?;
Ok(())
})
.await
.context("OAuth credential removal task failed")
.map_err(credential_store_error)?
.map_err(credential_store_error)
})
}
fn on_refresh_token_rejected<'life0, 'life1, 'async_trait>(
&'life0 self,
credentials: &'life1 StoredCredentials,
) -> BoxFuture<'async_trait, Result<(), AuthError>>
where
'life0: 'async_trait,
'life1: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
let guard = self
.inner
.refresh_guard
.lock()
.await
.upgrade()
.context("OAuth credential mutation requires an active refresh guard")
.map_err(credential_store_error)?;
let credentials = credentials.clone();
let inner = Arc::clone(&self.inner);
// Own both cache retirement and persistence: cancellation must not leave a reusable
// cached token after the durable mutation, or release the guard before either finishes.
tokio::spawn(async move {
let Some(expected) =
normalized_oauth_credentials(inner.last_credentials.lock().await.as_ref())
else {
return Ok(());
};
let mut attempted = credentials
.token_response
.ok_or(AuthError::AuthorizationRequired)?;
attempted.set_expires_in(None);
if credentials.client_id != expected.client_id
|| credentials.issuer != expected.issuer
|| WrappedOAuthTokenResponse(attempted) != expected.token_response
{
return Ok(());
}
*inner.rejected_credentials.lock().await = Some(expected.clone());
let mut retired = expected.clone();
retired.token_response.0.set_refresh_token(None);
*inner.last_credentials.lock().await = Some(retired.clone());
if inner.store.backend == Backend::Keyring(AuthKeyringBackendKind::Direct)
&& !inner.server_name.starts_with("ema-idp:")
{
// Ordinary direct-keyring entries are shared across CODEX_HOMEs, but their
// refresh locks are not. Do not risk overwriting another home's newer login.
// Enterprise entries include the home in their key and remain protected.
warn!(
server_name = %inner.server_name,
"rejected MCP OAuth refresh token retired only in this connection; shared direct-keyring storage lacks cross-home coordination"
);
return Ok(());
}
let store_inner = Arc::clone(&inner);
let result = tokio::task::spawn_blocking(move || -> Result<()> {
let _guard = guard;
// The aggregate-store transaction also excludes legacy persistors that
// do not participate in the per-credential refresh guard.
store_inner.store.retire_refresh_token_if_matches(
&store_inner.keyring,
&store_inner.server_name,
&store_inner.url,
&expected,
)
})
.await
.context("OAuth rejected credential mutation task failed")
.map_err(credential_store_error)
.and_then(|result| result.map_err(credential_store_error));
// This task can outlive its caller, so report failures here without logging
// backend error text that may contain credential material.
if result.is_err() {
warn!(
server_name = %inner.server_name,
"failed to persist rejected MCP OAuth refresh token retirement"
);
}
result
})
.await
// RMCP logs callback errors. Neither backend diagnostics nor task panic text
// may cross that boundary, even though the owned task reports failure safely.
.unwrap_or_else(|_| {
Err(AuthError::CredentialStoreError(
"OAuth rejection task failed".to_string(),
))
})
.map_err(|_| {
AuthError::CredentialStoreError(
"failed to retire rejected MCP OAuth refresh token".to_string(),
)
})
})
}
fn acquire_refresh_guard<'life0, 'async_trait>(
&'life0 self,
) -> BoxFuture<'async_trait, Result<Option<CredentialRefreshGuard>, AuthError>>
where
'life0: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
let guard = match &self.held_refresh_guard {
Some(guard) => Arc::clone(guard),
None => self.acquire_transaction_guard().await?,
};
Ok(Some(CredentialRefreshGuard::new(guard)))
})
}
}
fn credential_store_error(error: anyhow::Error) -> AuthError {
AuthError::CredentialStoreError(format!("{error:#}"))
}
fn rmcp_credentials(tokens: &StoredOAuthTokens) -> StoredCredentials {
let mut tokens = tokens.clone();
refresh_expires_in_from_timestamp(&mut tokens);
let token_received_at = tokens.expires_at.map(|expires_at| {
let remaining = tokens.token_response.0.expires_in().unwrap_or_default();
// Reconstruct the receipt time from the authority's deadline; a second clock read
// could otherwise extend the grant if this task paused between the two reads.
expires_at.saturating_sub(u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX)) / 1000
});
if token_received_at.is_none() {
tokens.token_response.0.set_expires_in(None);
}
let token_response = tokens.token_response.0;
let granted_scopes = token_response
.scopes()
.map(|scopes| scopes.iter().map(|scope| scope.to_string()).collect())
.unwrap_or_default();
StoredCredentials::new(
tokens.client_id,
Some(token_response),
granted_scopes,
token_received_at,
)
.with_issuer(tokens.issuer)
}

View File

@@ -0,0 +1,279 @@
//! Pin enterprise credentials to a non-secret version advanced by cooperating writers.
//! Exchanges reread the pinned keyring record and reject changes made outside this protocol.
use std::future::Future;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use tracing::instrument::WithSubscriber;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaErrorDetail;
use crate::ema_auth_policy::ema_reauthentication_required;
use crate::ema_claims::OidcClaims;
use crate::ema_claims::oidc_identity;
use crate::oauth::EnterpriseOAuthGeneration;
use crate::oauth::EnterpriseOAuthGenerationFile;
use crate::oauth::EnterpriseOAuthGenerationKind;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::ResolvedOAuthCredentialStore;
use crate::oauth::StoredOAuthCredentialSnapshot;
use crate::oauth::StoredOAuthTokens;
use crate::oauth::invalidate_enterprise_credential_version;
/// One validated keyring record and its cross-process credential version.
#[derive(Clone)]
pub struct EmaCredentialSnapshot {
snapshot: StoredOAuthCredentialSnapshot,
version: EnterpriseOAuthGeneration,
}
/// A credential snapshot admitted by a short generation check.
/// Logout may replace the grant while an admitted exchange finishes.
pub struct EmaCredentialLease {
pub(crate) credentials: StoredOAuthCredentialSnapshot,
}
// Discard storage and lock error chains: keyring backends can include the stable
// account/workspace key. Keep only the sanitized authentication classification.
fn sanitize_ema_credential_error(error: anyhow::Error, message: &'static str) -> anyhow::Error {
match error.downcast::<EmaAuthFailure>() {
Ok(failure) => anyhow::Error::new(failure).context(message),
Err(_) => EmaErrorDetail::new(message).into(),
}
}
impl std::fmt::Debug for EmaCredentialLease {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EmaCredentialLease").finish_non_exhaustive()
}
}
pub(crate) fn stored_oidc_identity(tokens: &StoredOAuthTokens) -> Result<OidcClaims> {
let assertion = tokens
.token_response
.0
.extra_fields()
.0
.get("id_token")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
ema_reauthentication_required(
"enterprise IdP session has no OIDC ID token; sign in again",
)
})?;
// The ID token binds the login identity. Its expiry does not determine
// whether the IdP will accept the independently valid refresh token.
oidc_identity(assertion, &tokens.url, &tokens.client_id).map_err(|error| {
ema_reauthentication_required("stored enterprise IdP identity is invalid; sign in again")
.context(error.to_string())
})
}
impl StoredOAuthCredentialSnapshot {
/// Bind the record and its version under one lease, validating any earlier snapshot read.
pub async fn pin_ema_credentials(self) -> Result<EmaCredentialSnapshot> {
self.pin_ema_credentials_in(&DefaultKeyringStore).await
}
async fn pin_ema_credentials_in<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
) -> Result<EmaCredentialSnapshot> {
if !self.credentials.server_name.starts_with("ema-idp:") {
bail!("enterprise credentials require the enterprise namespace");
}
let lock = RefreshCredentialLock::acquire_for_server(
&self.credentials.server_name,
&self.credentials.url,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
let keyring_store = keyring_store.clone();
tokio::task::spawn_blocking(move || {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
self.load_ema_credentials(&keyring_store)?;
let versions = EnterpriseOAuthGenerationFile::open(
&self.credentials.server_name,
&self.credentials.url,
EnterpriseOAuthGenerationKind::Credential,
&lock,
)?;
let version = match versions.current()? {
Some(version) => version,
None => versions.replace()?,
};
Ok(EmaCredentialSnapshot {
snapshot: self,
version,
})
})
})
.await
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"enterprise credential pinning task failed"
))
})?
.map_err(|error: anyhow::Error| {
sanitize_ema_credential_error(error, "failed to pin enterprise credentials")
})
}
}
impl EmaCredentialSnapshot {
/// Validate the pinned version under the credential lock without reading the keyring.
pub async fn acquire_current_ema_credentials(&self) -> Result<EmaCredentialLease> {
let credential_lock = RefreshCredentialLock::acquire_for_server(
&self.snapshot.credentials.server_name,
&self.snapshot.credentials.url,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
let pinned = self.clone();
tokio::task::spawn_blocking(move || {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
let credentials = pinned.snapshot.credentials();
let versions = EnterpriseOAuthGenerationFile::open(
&credentials.server_name,
&credentials.url,
EnterpriseOAuthGenerationKind::Credential,
&credential_lock,
)?;
if versions.current()?.as_ref() != Some(&pinned.version) {
return Err(ema_reauthentication_required(
"enterprise credentials changed; reconnect",
));
}
Ok(EmaCredentialLease {
credentials: pinned.snapshot,
})
})
})
.await
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"enterprise credential validation task failed"
))
})?
.map_err(|error: anyhow::Error| {
sanitize_ema_credential_error(error, "failed to validate enterprise credentials")
})
}
/// Exclusively lock and delete a rejected grant only if its pinned record is still current.
pub async fn invalidate_ema_credentials_if_current(
&self,
is_current: impl Future<Output = bool> + Send,
) -> Result<()> {
self.invalidate_ema_credentials_if_current_in(&DefaultKeyringStore, is_current)
.await
}
async fn invalidate_ema_credentials_if_current_in<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
is_current: impl Future<Output = bool> + Send,
) -> Result<()> {
let credential_lock = RefreshCredentialLock::acquire_for_server(
&self.snapshot.credentials.server_name,
&self.snapshot.credentials.url,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
if !is_current.await {
return Ok(());
}
let cancelled = tokio_util::sync::CancellationToken::new();
let _cancel_on_drop = cancelled.clone().drop_guard();
let pinned = self.clone();
let keyring_store = keyring_store.clone();
tokio::task::spawn_blocking(move || {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
let snapshot = &pinned.snapshot;
let previous = snapshot.credentials();
let versions = EnterpriseOAuthGenerationFile::open(
&previous.server_name,
&previous.url,
EnterpriseOAuthGenerationKind::Credential,
&credential_lock,
)?;
if versions.current()?.as_ref() != Some(&pinned.version) {
return Ok(());
}
if let Some(mut latest) =
snapshot
.store
.load(&keyring_store, &previous.server_name, &previous.url)?
{
latest.token_response.0.set_expires_in(None);
if latest == *previous && !cancelled.is_cancelled() {
invalidate_enterprise_credential_version(
&previous.server_name,
&previous.url,
&credential_lock,
)?;
snapshot.store.delete(
&keyring_store,
&previous.server_name,
&previous.url,
)?;
}
}
Ok(())
})
})
.await
.map_err(|_| anyhow!("enterprise credential invalidation task failed"))?
.map_err(|error: anyhow::Error| {
sanitize_ema_credential_error(error, "failed to invalidate enterprise credentials")
})
}
}
impl StoredOAuthCredentialSnapshot {
/// Reread only the pinned keyring authority; a changed record rejects the exchange.
pub(crate) fn load_ema_credentials<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
) -> Result<StoredOAuthTokens> {
if self.store == ResolvedOAuthCredentialStore::file() {
bail!("enterprise IdP credentials require keyring storage");
}
let previous = &self.credentials;
let mut latest =
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
self.store
.load(keyring_store, &previous.server_name, &previous.url)
})
.map_err(|_| anyhow!("failed to read enterprise IdP credentials from keyring"))?
.ok_or_else(|| {
ema_reauthentication_required(
"enterprise IdP credentials were removed; sign in again",
)
})?;
// There is no refresh-token rotation writer in the supported EMA profile.
// Pin the whole atomic login record, not just the claims of its ID token.
latest.token_response.0.set_expires_in(None);
if latest != *previous
|| previous.bound_issuer() != Some(previous.url.as_str())
|| !latest.has_refresh_token()
{
return Err(ema_reauthentication_required(
"enterprise IdP identity changed; sign in again and reconnect",
));
}
stored_oidc_identity(&latest)?;
Ok(latest)
}
}
#[cfg(test)]
#[path = "ema_identity_tests.rs"]
mod tests;

View File

@@ -0,0 +1,414 @@
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_config::types::AuthKeyringBackendKind;
use codex_keyring_store::CredentialStoreError;
use codex_keyring_store::KeyringStore;
use codex_keyring_store::tests::MockKeyringStore;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use serde_json::json;
use tracing_test::traced_test;
use super::*;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::compute_store_key;
use crate::oauth::test_support::TempCodexHome;
#[derive(Clone, Debug, Default)]
struct TracingKeyringStore(MockKeyringStore);
impl KeyringStore for TracingKeyringStore {
fn load(
&self,
service: &str,
account: &str,
) -> std::result::Result<Option<String>, CredentialStoreError> {
tracing::trace!(account, "reading enterprise keyring entry");
self.0.load(service, account)
}
fn save(
&self,
service: &str,
account: &str,
value: &str,
) -> std::result::Result<(), CredentialStoreError> {
self.0.save(service, account, value)
}
fn delete(
&self,
service: &str,
account: &str,
) -> std::result::Result<bool, CredentialStoreError> {
tracing::trace!(account, "deleting enterprise keyring entry");
self.0.delete(service, account)
}
}
#[tokio::test]
async fn invalidation_rereads_under_exclusive_lock_and_preserves_newer_grants() -> Result<()> {
let _home = TempCodexHome::new();
for replacement in [
None,
Some("refresh_token"),
Some("client_id"),
Some("version"),
] {
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": "ema-idp:rejected-grant", "url": "https://idp.example",
"issuer": "https://idp.example", "client_id": "client",
"token_response": {
"access_token": "unused", "token_type": "Bearer", "refresh_token": "old-grant"
},
}))?;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let keyring = MockKeyringStore::default();
let writer =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let versions = EnterpriseOAuthGenerationFile::open(
&tokens.server_name,
&tokens.url,
EnterpriseOAuthGenerationKind::Credential,
&writer,
)?;
let snapshot = EmaCredentialSnapshot {
snapshot: StoredOAuthCredentialSnapshot::new(tokens.clone(), store),
version: versions.replace()?,
};
store.save(&keyring, &tokens.server_name, &tokens)?;
let mut invalidation = Box::pin(
snapshot.invalidate_ema_credentials_if_current_in(&keyring, std::future::ready(true)),
);
assert!(invalidation.as_mut().now_or_never().is_none());
assert_eq!(
store.load(&keyring, &tokens.server_name, &tokens.url)?,
Some(tokens.clone())
);
// A login that wins the lock may change any part of the atomic credential record.
let mut latest = tokens.clone();
match replacement {
Some("refresh_token") => latest
.token_response
.0
.set_refresh_token(Some(oauth2::RefreshToken::new("new-grant".to_string()))),
Some("client_id") => latest.client_id = "new-client".to_string(),
// An identical token response can still belong to a newer login.
Some("version") => {
invalidate_enterprise_credential_version(&tokens.server_name, &tokens.url, &writer)?
}
None => {}
Some(_) => unreachable!(),
}
store.save(&keyring, &tokens.server_name, &latest)?;
drop(writer);
invalidation.await?;
assert_eq!(
store.load(&keyring, &tokens.server_name, &tokens.url)?,
replacement.map(|_| latest),
);
let _reader =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
assert_eq!(
versions.current()?.as_ref() != Some(&snapshot.version),
replacement.is_none() || replacement == Some("version"),
"invalidation advances the version only when deleting its own grant",
);
}
Ok(())
}
fn versioned_tokens() -> Result<StoredOAuthTokens> {
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({
"iss":"https://idp.example", "aud":"client", "sub":"user", "exp":4102444800_u64,
})
.to_string()
),
);
Ok(serde_json::from_value(json!({
"server_name":"ema-idp:versioned", "url":"https://idp.example",
"issuer":"https://idp.example", "client_id":"client",
"token_response": {
"access_token":"unused", "token_type":"Bearer",
"refresh_token":"enterprise-refresh", "id_token":assertion,
},
}))?)
}
#[tokio::test]
async fn cached_credentials_require_the_current_version_after_waiting_for_a_writer() -> Result<()> {
let home = TempCodexHome::new();
for change in ["replacement", "missing", "corrupt"] {
let tokens = versioned_tokens()?;
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
store.save(&keyring, &tokens.server_name, &tokens)?;
let snapshot = StoredOAuthCredentialSnapshot::new(tokens.clone(), store)
.pin_ema_credentials_in(&keyring)
.await?;
let version_path = std::fs::read_dir(home.path().join("mcp-oauth-locks"))?
.filter_map(std::result::Result::ok)
.map(|entry| entry.path())
.find(|path| {
path.extension()
.is_some_and(|ext| ext == "enterprise-credential-version")
})
.expect("credential version");
let writer =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let mut acquisition = Box::pin(snapshot.acquire_current_ema_credentials());
assert!(acquisition.as_mut().now_or_never().is_none());
match change {
"replacement" => {
invalidate_enterprise_credential_version(&tokens.server_name, &tokens.url, &writer)?
}
"missing" => std::fs::remove_file(&version_path)?,
"corrupt" => std::fs::write(&version_path, b"incomplete write")?,
_ => unreachable!(),
}
drop(writer);
let error = acquisition
.await
.expect_err("cached grant must not survive a change");
if change != "corrupt" {
assert_eq!(
error.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::ReauthenticationRequired),
"{change}"
);
}
assert_eq!(
store.load(&keyring, &tokens.server_name, &tokens.url)?,
Some(tokens)
);
std::fs::remove_file(version_path)?;
}
Ok(())
}
#[tokio::test]
async fn pinning_does_not_bind_a_stale_record_to_a_new_credential_version() -> Result<()> {
let _home = TempCodexHome::new();
let tokens = versioned_tokens()?;
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
store.save(&keyring, &tokens.server_name, &tokens)?;
let snapshot = StoredOAuthCredentialSnapshot::new(tokens.clone(), store);
let writer =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let mut pinning = Box::pin(snapshot.pin_ema_credentials_in(&keyring));
assert!(pinning.as_mut().now_or_never().is_none());
let mut replacement = tokens;
replacement
.token_response
.0
.set_refresh_token(Some(oauth2::RefreshToken::new(
"replacement-grant".to_string(),
)));
invalidate_enterprise_credential_version(&replacement.server_name, &replacement.url, &writer)?;
store.save(&keyring, &replacement.server_name, &replacement)?;
drop(writer);
assert!(pinning.await.is_err());
let current = StoredOAuthCredentialSnapshot::new(replacement, store)
.pin_ema_credentials_in(&keyring)
.await?;
current.acquire_current_ema_credentials().await?;
Ok(())
}
#[tokio::test]
async fn admitted_credentials_do_not_block_a_new_pin() -> Result<()> {
let _home = TempCodexHome::new();
let tokens = versioned_tokens()?;
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
store.save(&keyring, &tokens.server_name, &tokens)?;
let snapshot = StoredOAuthCredentialSnapshot::new(tokens, store);
let pinned = snapshot.clone().pin_ema_credentials_in(&keyring).await?;
let _active_request = pinned.acquire_current_ema_credentials().await?;
let concurrent = tokio::time::timeout(
std::time::Duration::from_secs(1),
snapshot.pin_ema_credentials_in(&keyring),
)
.await??;
assert!(concurrent.version == pinned.version);
Ok(())
}
#[tokio::test]
async fn keyring_failure_does_not_reuse_the_pinned_refresh_token() -> Result<()> {
let _home = TempCodexHome::new();
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": "ema-idp:keyring-failure",
"url": "https://idp.example",
"issuer": "https://idp.example",
"client_id": "client",
"token_response": {
"access_token": "unused",
"token_type": "Bearer",
"refresh_token": "stale-refresh",
},
}))?;
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
let _lock = RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let snapshot = StoredOAuthCredentialSnapshot::new(
tokens,
ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct),
);
let keyring = MockKeyringStore::default();
keyring.set_error(
&key,
keyring::Error::Invalid("backend".into(), "unavailable".into()),
);
let error = snapshot
.load_ema_credentials(&keyring)
.expect_err("keyring failure must be terminal");
assert!(
error
.to_string()
.contains("failed to read enterprise IdP credentials from keyring")
);
Ok(())
}
#[traced_test]
#[tokio::test]
async fn enterprise_credential_errors_and_keyring_traces_hide_account_key() -> Result<()> {
let home = TempCodexHome::new();
let sentinel = "private-workspace-sentinel";
let mut tokens = versioned_tokens()?;
tokens.server_name = format!("ema-idp:{sentinel}");
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let keyring = TracingKeyringStore::default();
let snapshot = StoredOAuthCredentialSnapshot::new(tokens.clone(), store);
tracing::trace!("enterprise keyring privacy test capture enabled");
assert!(logs_contain(
"enterprise keyring privacy test capture enabled"
));
keyring
.0
.set_error(&key, keyring::Error::Invalid("account".into(), key.clone()));
let error = snapshot
.load_ema_credentials(&keyring)
.expect_err("backend read must fail");
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
keyring
.0
.set_error(&key, keyring::Error::Invalid("account".into(), key.clone()));
let error = snapshot
.clone()
.pin_ema_credentials_in(&keyring)
.await
.err()
.expect("backend pin must fail");
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
assert_eq!(error.downcast_ref::<EmaAuthFailure>(), None);
let keyring = TracingKeyringStore::default();
let removed = snapshot
.clone()
.pin_ema_credentials_in(&keyring)
.await
.err()
.expect("removed grant must fail");
assert_eq!(
removed.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::ReauthenticationRequired),
);
assert!(!format!("{removed} {removed:?} {removed:#}").contains(sentinel));
store.save(&keyring, &tokens.server_name, &tokens)?;
let pinned = snapshot.clone().pin_ema_credentials_in(&keyring).await?;
keyring
.0
.set_error(&key, keyring::Error::Invalid("account".into(), key.clone()));
let error = pinned
.invalidate_ema_credentials_if_current_in(&keyring, std::future::ready(true))
.await
.unwrap_err();
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
let successful_keyring = TracingKeyringStore::default();
store.save(&successful_keyring, &tokens.server_name, &tokens)?;
snapshot
.clone()
.pin_ema_credentials_in(&successful_keyring)
.await?
.invalidate_ema_credentials_if_current_in(&successful_keyring, std::future::ready(true))
.await?;
assert_eq!(successful_keyring.0.saved_value(&key), None);
let lock_dir = home.path().join("mcp-oauth-locks");
std::fs::rename(&lock_dir, home.path().join("held-locks"))?;
std::fs::write(&lock_dir, b"not a directory")?;
for error in [
snapshot
.pin_ema_credentials_in(&keyring)
.await
.err()
.expect("lock must fail"),
pinned.acquire_current_ema_credentials().await.unwrap_err(),
pinned
.invalidate_ema_credentials_if_current_in(&keyring, std::future::ready(true))
.await
.unwrap_err(),
] {
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
}
assert!(!logs_contain(sentinel));
Ok(())
}
#[test]
fn ordinary_oauth_names_cannot_alias_enterprise_credential_keys() -> Result<()> {
let _home = TempCodexHome::new();
let issuer = "https://idp.example";
let enterprise_name = "ema-idp:synthetic-identity";
let ordinary: codex_config::McpServerConfig = serde_json::from_value(json!({
"url": issuer,
"oauth": {"client_id": "idp-client"},
}))?;
let ordinary_name = ordinary.oauth_credential_name(enterprise_name);
pretty_assertions::assert_ne!(
compute_store_key(&ordinary_name, issuer)?,
compute_store_key(enterprise_name, issuer)?,
"an ordinary server name must not select the enterprise credential namespace"
);
let legacy_key = compute_store_key("ordinary-server", issuer)?;
let legacy_hash = legacy_key.split_once('|').expect("legacy key separator").1;
pretty_assertions::assert_eq!(
compute_store_key(&ordinary_name, issuer)?,
format!("{enterprise_name}|{legacy_hash}"),
"escaping the reserved prefix preserves the pre-EMA ordinary credential key"
);
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let enterprise_tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": enterprise_name, "url": issuer, "issuer": issuer,
"client_id": "idp-client", "token_response": {
"access_token": "unused", "token_type": "Bearer", "refresh_token": "enterprise-refresh"
}
}))?;
store.save(&keyring, enterprise_name, &enterprise_tokens)?;
let mut ordinary_tokens = enterprise_tokens.clone();
ordinary_tokens.server_name = ordinary_name.to_string();
store.save(&keyring, &ordinary_name, &ordinary_tokens)?;
assert!(store.delete(&keyring, &ordinary_name, issuer)?);
pretty_assertions::assert_eq!(
store.load(&keyring, enterprise_name, issuer)?,
Some(enterprise_tokens),
"ordinary OAuth save/logout must not overwrite or remove the enterprise entry"
);
Ok(())
}

View File

@@ -0,0 +1,114 @@
//! Persistent, non-secret fences for login attempts and cached enterprise credentials.
//! Separate generations preserve pending-login semantics when a stored grant changes.
//! All reads and writes require the credential lock; missing state never admits old authority.
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Seek;
use std::io::Write;
use anyhow::Result;
use anyhow::ensure;
use codex_utils_home_dir::find_codex_home;
use oauth2::CsrfToken;
use sha2::Digest;
use sha2::Sha256;
use super::RefreshCredentialLock;
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct EnterpriseOAuthGeneration([u8; 32]);
pub(crate) enum EnterpriseOAuthGenerationKind {
LoginAttempt,
Credential,
}
pub(crate) struct EnterpriseOAuthGenerationFile {
file: File,
}
impl EnterpriseOAuthGenerationFile {
pub(crate) fn open(
credential_name: &str,
issuer: &str,
kind: EnterpriseOAuthGenerationKind,
_lock: &RefreshCredentialLock,
) -> Result<Self> {
let key = super::compute_store_key(credential_name, issuer)?;
let suffix = match kind {
EnterpriseOAuthGenerationKind::LoginAttempt => "enterprise-generation",
EnterpriseOAuthGenerationKind::Credential => "enterprise-credential-version",
};
let name = format!("{:x}.{suffix}", Sha256::digest(key.as_bytes()));
let path = find_codex_home()?.join("mcp-oauth-locks").join(name);
let mut options = OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
}
let file = options.open(path)?;
ensure!(
file.metadata()?.is_file(),
"invalid enterprise generation file"
);
Ok(Self { file })
}
pub(crate) fn current(&self) -> Result<Option<EnterpriseOAuthGeneration>> {
let mut file = &self.file;
file.rewind()?;
match file.metadata()?.len() {
0 => Ok(None),
32 => {
let mut generation = [0; 32];
file.read_exact(&mut generation)?;
Ok(Some(EnterpriseOAuthGeneration(generation)))
}
_ => anyhow::bail!("invalid enterprise generation file"),
}
}
pub(crate) fn replace(&self) -> Result<EnterpriseOAuthGeneration> {
// Reuse OAuth's randomness without storing any credential. Random initialization
// also prevents an old attempt becoming valid if metadata is removed or truncated.
let random = CsrfToken::new_random_len(/*num_bytes*/ 32);
let generation =
EnterpriseOAuthGeneration(Sha256::digest(random.secret().as_bytes()).into());
let mut file = &self.file;
file.set_len(/*size*/ 0)?;
file.rewind()?;
file.write_all(&generation.0)?;
file.sync_all()?;
Ok(generation)
}
}
/// Invalidate cached grants before mutation, including when the following store write fails.
pub(crate) fn invalidate_enterprise_credential_version(
credential_name: &str,
issuer: &str,
lock: &RefreshCredentialLock,
) -> Result<()> {
if credential_name.starts_with("ema-idp:") {
EnterpriseOAuthGenerationFile::open(
credential_name,
issuer,
EnterpriseOAuthGenerationKind::Credential,
lock,
)?
.replace()?;
}
Ok(())
}

View File

@@ -0,0 +1,124 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use rmcp::transport::auth::AuthError;
use rmcp::transport::auth::AuthorizationMetadata;
use url::Url;
use super::StoredOAuthTokens;
/// Reject non-web authorization endpoints or endpoints that cannot be bound to their issuer.
pub(crate) fn validate_authorization_server_endpoints(
metadata: &AuthorizationMetadata,
) -> Result<()> {
let authorization_endpoint = Url::parse(&metadata.authorization_endpoint)
.context("OAuth authorization endpoint must be a valid URL")?;
if !matches!(authorization_endpoint.scheme(), "http" | "https") {
bail!("OAuth authorization endpoint must use HTTP or HTTPS");
}
let issuer = metadata
.issuer
.as_deref()
.filter(|issuer| !issuer.trim().is_empty())
.map(Url::parse)
.transpose()
.context("OAuth authorization server issuer must be a valid URL")?;
let issuer_bound_callbacks = metadata
.additional_fields
.get("authorization_response_iss_parameter_supported")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if issuer_bound_callbacks {
if issuer.is_none() {
bail!("OAuth issuer-bound callbacks require an authorization server issuer");
}
return Ok(());
}
let token_endpoint =
Url::parse(&metadata.token_endpoint).context("OAuth token endpoint must be a valid URL")?;
if let Some(issuer) = issuer {
if authorization_endpoint.origin() == issuer.origin()
|| authorization_endpoint.origin() == token_endpoint.origin()
// Remove these narrow compatibility exceptions once both providers support RFC 9207.
|| matches!(
(
issuer.as_str(),
authorization_endpoint.origin().ascii_serialization().as_str(),
token_endpoint.origin().ascii_serialization().as_str(),
),
(
"https://mcp.mercadopago.com/mcp",
"https://auth.mercadopago.com",
"https://mcp.mercadopago.com",
) | (
"https://agent.robinhood.com/mcp/trading",
"https://robinhood.com",
"https://api.robinhood.com",
)
)
{
return Ok(());
}
bail!(
"OAuth authorization endpoint origin does not match the authorization server origin without issuer-bound callbacks"
);
}
if token_endpoint.origin() != authorization_endpoint.origin() {
bail!(
"OAuth token endpoint origin does not match the authorization server origin without issuer-bound callbacks"
);
}
Ok(())
}
/// Verifies that a stored refresh token remains bound to its original issuer.
///
/// Call this with the same metadata snapshot that RMCP will use for the credentials. Missing or
/// changed issuers require a new login rather than risking sending a refresh token to a different
/// authorization server.
pub(crate) fn validate_refresh_token_issuer(
metadata: &AuthorizationMetadata,
tokens: &StoredOAuthTokens,
) -> Result<()> {
if !tokens.has_refresh_token() {
return Ok(());
}
let Some(stored_issuer) = tokens.bound_issuer() else {
return Err(AuthError::AuthorizationRequired).with_context(|| {
format!(
"OAuth refresh credentials for server {} are missing an authorization server issuer; authorization required",
tokens.server_name
)
});
};
let Some(current_issuer) = metadata
.issuer
.as_deref()
.filter(|issuer| !issuer.trim().is_empty())
else {
return Err(AuthError::AuthorizationRequired).with_context(|| {
format!(
"OAuth metadata for server {} did not include an authorization server issuer; authorization required",
tokens.server_name
)
});
};
if current_issuer != stored_issuer {
return Err(AuthError::AuthorizationRequired).with_context(|| {
format!(
"OAuth authorization server issuer changed for server {}; authorization required",
tokens.server_name
)
});
}
Ok(())
}

View File

@@ -0,0 +1,105 @@
//! Cross-process serialization for one MCP OAuth credential's refresh transaction.
//!
//! The guard is intentionally acquired before the authoritative credential reread and retained
//! through provider refresh and persistence. This prevents two processes from replaying the same
//! rotating refresh token or observing a partially persisted transaction.
//! EMA uses the same lock only for short credential reads and generation checks.
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_utils_home_dir::find_codex_home;
use sha2::Digest;
use sha2::Sha256;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::path::Path;
use std::time::Duration;
use tokio::time::sleep;
use tokio::time::timeout;
const REFRESH_LOCK_DIR: &str = "mcp-oauth-locks";
const REFRESH_LOCK_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60);
const REFRESH_LOCK_RETRY_SLEEP: Duration = Duration::from_millis(/*millis*/ 50);
// Keep this internal target stable so diagnostics and cross-process tests can distinguish actual
// WouldBlock contention from a contender that merely started late and observed persisted tokens.
const LOCK_CONTENTION_EVENT_TARGET: &str = "codex_rmcp_client::oauth::refresh_lock::contention";
pub(crate) struct RefreshCredentialLock {
_file: File,
}
impl RefreshCredentialLock {
pub(crate) async fn acquire_for_server(server_name: &str, url: &str) -> Result<Self> {
let store_key = super::compute_store_key(server_name, url)?;
let codex_home = find_codex_home()?;
Self::acquire_in(&codex_home, &store_key, REFRESH_LOCK_ACQUIRE_TIMEOUT)
.await
.with_context(|| format!("failed to acquire OAuth credential lock for {server_name}"))
}
async fn acquire_in(
codex_home: &Path,
store_key: &str,
acquire_timeout: Duration,
) -> Result<Self> {
// Scope coordination to CODEX_HOME alongside File and Secrets state. Direct keyring
// coordination across homes needs a separate cross-platform rendezvous.
// TODO(stevenlee): define that rendezvous before expanding this lock's scope.
let mut hasher = Sha256::new();
hasher.update(store_key.as_bytes());
let path = codex_home
.join(REFRESH_LOCK_DIR)
.join(format!("{:x}.lock", hasher.finalize()));
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.with_context(|| format!("failed to open OAuth refresh lock {}", path.display()))?;
// Bound every contender, but keep the acquired lock for the full provider request and
// persistence transaction. Releasing it while awaiting the provider would allow concurrent
// use of a rotating refresh token.
let mut reported_contention = false;
timeout(acquire_timeout, async {
loop {
match file.try_lock() {
Ok(()) => return Ok(()),
Err(std::fs::TryLockError::WouldBlock) => {
if !reported_contention {
tracing::debug!(
target: LOCK_CONTENTION_EVENT_TARGET,
lock_path = %path.display(),
"waiting for another process to finish refreshing MCP OAuth credentials"
);
reported_contention = true;
}
sleep(REFRESH_LOCK_RETRY_SLEEP).await;
}
Err(error) => return Err(std::io::Error::from(error)),
}
}
})
.await
.map_err(|_| {
anyhow!(
"timed out after {acquire_timeout:?} waiting for OAuth refresh lock {}",
path.display()
)
})?
.with_context(|| format!("failed to lock OAuth refresh lock {}", path.display()))?;
Ok(Self { _file: file })
}
}
#[cfg(test)]
#[path = "refresh_lock_tests.rs"]
mod tests;

View File

@@ -0,0 +1,40 @@
use super::RefreshCredentialLock;
use anyhow::Result;
use std::time::Duration;
use tempfile::tempdir;
#[tokio::test]
async fn acquisition_times_out_without_stealing() -> Result<()> {
let codex_home = tempdir()?;
let store_key = "test-store-key";
let held_lock = RefreshCredentialLock::acquire_in(
codex_home.path(),
store_key,
Duration::from_millis(/*millis*/ 100),
)
.await?;
let error = RefreshCredentialLock::acquire_in(
codex_home.path(),
store_key,
Duration::from_millis(/*millis*/ 50),
)
.await
.err()
.expect("contending lock acquisition should time out");
assert!(
error
.to_string()
.contains("timed out after 50ms waiting for OAuth refresh lock"),
"unexpected error: {error:#}"
);
drop(held_lock);
let _reacquired = RefreshCredentialLock::acquire_in(
codex_home.path(),
store_key,
Duration::from_millis(/*millis*/ 100),
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,400 @@
//! Serialized read-refresh-write transactions for MCP OAuth credentials.
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use codex_config::McpServerOAuthConfig;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use oauth2::TokenResponse;
use rmcp::transport::auth::AuthError;
use rmcp::transport::auth::AuthorizationManager;
use rmcp::transport::auth::CredentialStore as _;
use rmcp::transport::auth::InMemoryCredentialStore;
use rmcp::transport::auth::OAuthTokenResponse;
use rmcp::transport::auth::StoredCredentials;
use tokio::time::timeout;
use tracing::debug;
use tracing::warn;
use crate::oauth_client_credentials::OAuthClientCredentials;
use super::OAuthPersistor;
use super::OAuthPersistorInner;
use super::StoredOAuthTokens;
use super::WrappedOAuthTokenResponse;
use super::compute_expires_at_millis;
use super::expires_in_from_timestamp;
use super::refresh_lock::RefreshCredentialLock;
use super::token_needs_refresh;
use super::validate_refresh_token_issuer;
pub(super) const REFRESH_REQUEST_TIMEOUT: Duration = Duration::from_secs(45);
impl OAuthPersistor {
pub(crate) async fn refresh_if_needed(&self) -> Result<()> {
self.refresh_if_needed_in(&DefaultKeyringStore, REFRESH_REQUEST_TIMEOUT)
.await
}
/// Injects the credential backend and provider timeout for deterministic failure-path tests.
pub(super) async fn refresh_if_needed_in<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
refresh_request_timeout: Duration,
) -> Result<()> {
let expires_at = {
let guard = self.inner.last_credentials.lock().await;
guard.as_ref().and_then(|tokens| tokens.expires_at)
};
if !token_needs_refresh(expires_at) {
return Ok(());
}
let persistor = self.clone();
let keyring_store = keyring_store.clone();
// Once the provider can consume a rotating token, caller cancellation must not cancel
// persistence. The owned task continues with independently bounded lock and request waits.
// A provider timeout leaves the outcome unknown and permits a later serialized retry:
// provider grace may recover, otherwise reauthorization is unavoidable. This residual
// risk is preferred to holding the credential lock indefinitely.
let transaction_task = tokio::spawn(async move {
let result = persistor
.refresh_transaction(&keyring_store, refresh_request_timeout)
.await;
// Keep this summary inside the owned task so caller cancellation cannot suppress it.
if let Err(error) = &result {
warn!(
server_name = %persistor.inner.server_name,
refresh_reason = "expiry",
error = %error,
"MCP OAuth refresh transaction failed"
);
}
result
});
transaction_task.await.with_context(|| {
format!(
"OAuth refresh task failed for server {}",
self.inner.server_name
)
})?
}
#[expect(
clippy::await_holding_invalid_type,
reason = "AuthorizationManager async access must be serialized through its Tokio mutex"
)]
#[tracing::instrument(
level = "debug",
skip_all,
fields(
server_name = %self.inner.server_name,
refresh_reason = "expiry",
),
err
)]
async fn refresh_transaction<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
refresh_request_timeout: Duration,
) -> Result<()> {
debug!("waiting for the MCP OAuth credential transaction lock");
let _lock =
RefreshCredentialLock::acquire_for_server(&self.inner.server_name, &self.inner.url)
.await?;
debug!("acquired the MCP OAuth credential transaction lock");
// Stay on the lifecycle-pinned store. A failure is surfaced rather than falling back and
// possibly replaying an older rotating refresh token from the other store.
debug!("rereading authoritative MCP OAuth credentials");
let latest = self.inner.credential_store.load(
keyring_store,
&self.inner.server_name,
&self.inner.url,
)?;
// The pre-lock snapshot is only a hint. This locked reread is authoritative, so adopt a
// winner from another process rather than refreshing its predecessor.
let Some(latest) = latest else {
let manager = self.inner.authorization_manager.clone();
manager
.lock()
.await
.set_credential_store(InMemoryCredentialStore::new());
*self.inner.last_credentials.lock().await = None;
return Err(AuthError::AuthorizationRequired).with_context(|| {
format!(
"OAuth tokens for server {} were removed before refresh; authorization required",
self.inner.server_name
)
});
};
if !token_needs_refresh(latest.expires_at) {
debug!("adopting newer MCP OAuth credentials without contacting the provider");
let manager = self.inner.authorization_manager.clone();
let mut guard = manager.lock().await;
if latest.has_refresh_token() {
let previous = self.inner.last_credentials.lock().await;
let expected_issuer = previous.as_ref().and_then(StoredOAuthTokens::bound_issuer);
let latest_issuer = latest.bound_issuer();
if latest_issuer.is_none() || latest_issuer != expected_issuer {
return Err(AuthError::AuthorizationRequired).with_context(|| {
format!(
"OAuth refresh credentials for server {} could not be bound to the previously validated issuer; authorization required",
self.inner.server_name
)
});
}
}
install_tokens_in_manager(&mut guard, &latest, self.inner.oauth_config.as_ref())
.await?;
*self.inner.last_credentials.lock().await = Some(latest);
return Ok(());
}
// Without a refresh token, authorization is required before contacting the provider.
if !latest.has_refresh_token() {
return Err(AuthError::AuthorizationRequired).with_context(|| {
format!(
"OAuth tokens for server {} cannot be refreshed; authorization required",
self.inner.server_name
)
});
}
let manager = self.inner.authorization_manager.clone();
// The provider uses a separate HTTP client and cannot re-enter `AuthClient`. Retain this
// async guard so requests cannot observe credentials while they are staged and committed.
let mut guard = manager.lock().await;
let metadata = guard
.resolve_metadata()
.await
.context("failed to resolve OAuth metadata before using stored refresh credentials")?
.metadata;
validate_refresh_token_issuer(&metadata, &latest)?;
guard.set_metadata(metadata);
install_tokens_in_manager(&mut guard, &latest, self.inner.oauth_config.as_ref())
.await
.context("failed to stage OAuth credentials for refresh")?;
// The owned task prevents caller deadlines from canceling after possible token rotation;
// this timeout independently bounds the provider request.
debug!(
timeout_ms = refresh_request_timeout.as_millis(),
"requesting refreshed MCP OAuth credentials from the provider"
);
let refreshed = match timeout(refresh_request_timeout, guard.refresh_token()).await {
Ok(Ok(token_response)) => {
debug!("received refreshed MCP OAuth credentials from the provider");
refreshed_tokens(token_response, &latest, &self.inner)
}
Ok(Err(error @ AuthError::TokenRefreshRejected(_))) => {
// Definitive rejection requires authorization even if the access token has not
// expired yet. Other refresh failures below check actual access-token expiry.
warn!(
error = %error,
"MCP OAuth refresh token was rejected; reauthorization required"
);
return Err(AuthError::AuthorizationRequired).with_context(|| {
format!(
"failed to refresh OAuth tokens for server {}: {error}",
self.inner.server_name
)
});
}
Ok(Err(error)) => {
warn!(
error = %error,
"MCP OAuth provider refresh failed"
);
let error = Error::new(error).context(format!(
"failed to refresh OAuth tokens for server {}",
self.inner.server_name
));
return self
.recover_after_failed_refresh(keyring_store, &mut guard, &latest, error)
.await;
}
Err(_) => {
warn!(
timeout_ms = refresh_request_timeout.as_millis(),
"MCP OAuth provider refresh timed out; the outcome is unknown and a later serialized retry is permitted"
);
let error = anyhow::anyhow!(
"timed out after {refresh_request_timeout:?} refreshing OAuth tokens for server {}",
self.inner.server_name
);
return self
.recover_after_failed_refresh(keyring_store, &mut guard, &latest, error)
.await;
}
};
// Persist to the pinned source before exposing the refreshed token. On failure, restore
// the prior in-process credential and return the error; serving an unpersisted token would
// hide the root cause until a later process restart. If the provider already consumed the
// prior token, the next refresh may require reauthorization. That is the deliberate
// fail-closed policy.
// TODO: Add a bounded persistence retry only if telemetry shows this is common; never
// silently switch stores or continue with an unpersisted credential.
debug!("persisting refreshed MCP OAuth credentials to the resolved store");
let result = self.inner.credential_store.save_with_refresh_telemetry(
keyring_store,
&self.inner.server_name,
&refreshed,
);
if let Err(error) = result {
warn!(
"failed to persist refreshed MCP OAuth credentials; returning the error and restoring the previous in-process credentials"
);
install_tokens_in_manager(&mut guard, &latest, self.inner.oauth_config.as_ref())
.await
.context(
"failed to restore previous OAuth credentials after refresh persistence failed",
)?;
return Err(error);
}
// This layer retains RMCP's legacy persistence hook. Install the same merged response
// (including carried-forward refresh token/scopes) so that hook cannot overwrite durable
// credentials with the provider's partial response.
install_tokens_in_manager(&mut guard, &refreshed, self.inner.oauth_config.as_ref())
.await
.context(
"refreshed OAuth tokens were persisted but could not be installed in the authorization manager",
)?;
*self.inner.last_credentials.lock().await = Some(refreshed);
drop(guard);
debug!("persisted refreshed MCP OAuth credentials and completed the transaction");
Ok(())
}
async fn recover_after_failed_refresh<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
manager: &mut AuthorizationManager,
previous: &StoredOAuthTokens,
error: Error,
) -> Result<()> {
// A failed proactive refresh does not require a new login while the access token is
// still valid. Use actual expiry, not the 30-second refresh buffer.
if !token_has_expired(previous.expires_at) {
return Err(error);
}
// Browser login can finish while the provider request is pending. Reread the pinned
// authority before prompting, and never delete or overwrite a replacement credential.
let replacement = self.inner.credential_store.load(
keyring_store,
&self.inner.server_name,
&self.inner.url,
)?;
if let Some(replacement) = replacement
&& !token_has_expired(replacement.expires_at)
&& !replacement.client_id.trim().is_empty()
&& !replacement
.token_response
.0
.access_token()
.secret()
.trim()
.is_empty()
{
// Match the existing pre-refresh adoption rule: refresh credentials must remain
// bound to the issuer already validated for this authorization manager.
if replacement.has_refresh_token()
&& (replacement.bound_issuer().is_none()
|| replacement.bound_issuer() != previous.bound_issuer())
{
return Err(AuthError::AuthorizationRequired).context(
"replacement MCP OAuth refresh credentials do not match the validated issuer",
);
}
debug!("adopting new MCP OAuth credentials after a failed refresh");
install_tokens_in_manager(manager, &replacement, self.inner.oauth_config.as_ref())
.await?;
*self.inner.last_credentials.lock().await = Some(replacement);
return Ok(());
}
warn!("MCP OAuth access token is expired and refresh failed; reauthorization required");
// Keep AuthorizationRequired as the source so both startup classification and runtime
// tool-call recovery recognize it; retain the original failure as diagnostic context.
Err(Error::new(AuthError::AuthorizationRequired).context(error))
}
}
fn token_has_expired(expires_at: Option<u64>) -> bool {
expires_at.is_some_and(|expires_at| expires_in_from_timestamp(expires_at).is_none())
}
/// Installs tokens without resolving metadata again, so callers can pin the validated snapshot.
pub(crate) async fn install_tokens_in_manager(
authorization_manager: &mut AuthorizationManager,
tokens: &StoredOAuthTokens,
oauth_config: Option<&McpServerOAuthConfig>,
) -> Result<()> {
let credentials = OAuthClientCredentials::resolve(oauth_config)?;
credentials.validate_stored_client_id(&tokens.client_id)?;
let store = InMemoryCredentialStore::new();
let token_response = tokens.token_response.0.clone();
let granted_scopes = token_response
.scopes()
.map(|scopes| scopes.iter().map(|scope| scope.to_string()).collect())
.unwrap_or_default();
let token_received_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs());
store
.save(
StoredCredentials::new(
tokens.client_id.clone(),
Some(token_response),
granted_scopes,
token_received_at,
)
.with_issuer(tokens.issuer.clone()),
)
.await
.context("failed to stage OAuth tokens for authorization manager")?;
authorization_manager.set_credential_store(store);
// TODO(stevenlee): Add an RMCP adoption API that atomically updates credentials, client ID,
// and private `current_scopes`; this path cannot synchronize RMCP's scope-upgrade state.
authorization_manager
.initialize_from_store()
.await
.context("failed to adopt refreshed OAuth tokens")?;
credentials.configure_for_refresh(authorization_manager, &tokens.url, &tokens.client_id)?;
Ok(())
}
fn refreshed_tokens(
mut token_response: OAuthTokenResponse,
previous: &StoredOAuthTokens,
inner: &OAuthPersistorInner,
) -> StoredOAuthTokens {
if token_response.refresh_token().is_none() {
token_response.set_refresh_token(previous.token_response.0.refresh_token().cloned());
}
if token_response.scopes().is_none() {
token_response.set_scopes(previous.token_response.0.scopes().cloned());
}
StoredOAuthTokens {
server_name: inner.server_name.clone(),
url: inner.url.clone(),
issuer: previous.issuer.clone(),
client_id: previous.client_id.clone(),
expires_at: compute_expires_at_millis(&token_response),
token_response: WrappedOAuthTokenResponse(token_response),
}
}

View File

@@ -0,0 +1,465 @@
//! Resolves the configured MCP OAuth store and pins that concrete source for one client lifecycle.
//! Retains the originating client for later background storage observations.
use super::telemetry;
use anyhow::Context;
use anyhow::Result;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_keyring_store::KeyringStore;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_otel::auth_storage::Operation;
use codex_otel::auth_storage::Store;
use super::OAuthKeyringLoadError;
use super::OAuthStore;
use super::OAuthStoreLock;
use super::OAuthStoreLockFailure;
use super::StoredOAuthTokens;
use super::compute_store_key;
use super::delete_oauth_tokens_from_direct_keyring;
use super::delete_oauth_tokens_from_file;
use super::delete_oauth_tokens_from_secrets_keyring;
use super::load_oauth_tokens_from_file;
use super::load_oauth_tokens_from_file_with_lock_held;
use super::load_oauth_tokens_from_keyring;
use super::load_oauth_tokens_from_secrets_keyring_with_lock_held;
use super::normalized_oauth_credentials;
use super::read_fallback_file_unlocked;
use super::save_oauth_tokens_to_direct_keyring;
use super::save_oauth_tokens_to_file;
use super::save_oauth_tokens_to_secrets_keyring_with_lock_held;
use super::save_oauth_tokens_with_keyring;
use super::write_fallback_file;
/// Concrete credential store resolved for one MCP OAuth client lifecycle.
///
/// This is intentionally not durable. `Auto` may resolve differently in a later process, but a
/// client that loaded credentials from one store must reread, refresh, persist, and remove only
/// through that store. A mid-lifecycle backend failure is unexpected and must return an error
/// rather than falling back to another possibly stale refresh token.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ResolvedOAuthCredentialStore {
pub(super) backend: Backend,
pub(super) mode: OAuthCredentialsStoreMode,
pub(super) kind: AuthKeyringBackendKind,
pub(super) originator: AuthStorageOriginator,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Backend {
File,
Keyring(AuthKeyringBackendKind),
}
// Telemetry metadata must not change credential identity or trigger a reconnect.
impl PartialEq for ResolvedOAuthCredentialStore {
fn eq(&self, other: &Self) -> bool {
self.backend == other.backend
}
}
impl Eq for ResolvedOAuthCredentialStore {}
impl ResolvedOAuthCredentialStore {
pub(crate) fn file() -> Self {
Self {
backend: Backend::File,
mode: OAuthCredentialsStoreMode::File,
kind: AuthKeyringBackendKind::Direct,
originator: AuthStorageOriginator::current(),
}
}
pub(crate) fn keyring(kind: AuthKeyringBackendKind) -> Self {
Self {
backend: Backend::Keyring(kind),
mode: OAuthCredentialsStoreMode::Keyring,
kind,
originator: AuthStorageOriginator::current(),
}
}
fn with_policy(
mut self,
mode: OAuthCredentialsStoreMode,
kind: AuthKeyringBackendKind,
) -> Self {
self.mode = mode;
self.kind = kind;
self
}
/// Loads credentials only from this already-resolved authority.
///
/// Unlike `resolve_oauth_tokens_from_store_policy`, this never evaluates configured
/// `Auto` fallback policy.
pub(crate) fn load<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
server_name: &str,
url: &str,
) -> Result<Option<StoredOAuthTokens>> {
let mut observation = telemetry::resolved(self, Operation::Load);
let result = match self.backend {
Backend::File => load_oauth_tokens_from_file(server_name, url)
.context("failed to reread OAuth tokens from resolved file storage"),
Backend::Keyring(keyring_backend_kind) => load_oauth_tokens_from_keyring(
keyring_store,
keyring_backend_kind,
server_name,
url,
)
.map_err(anyhow::Error::from)
.context(
"failed to reread OAuth tokens from resolved keyring storage; refusing file fallback",
),
};
observation.record_load_attempt(telemetry::store(self), &result);
if matches!(self.backend, Backend::Keyring(_))
&& let Err(error) = &result
{
telemetry::record_secure_error(&mut observation, error.as_ref());
}
result
}
/// Reads the selected authority without waiting for its aggregate-store lock.
pub(crate) fn try_load<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
server_name: &str,
url: &str,
) -> Result<Option<StoredOAuthTokens>> {
match self.backend {
Backend::File => {
let _store_lock = OAuthStoreLock::try_acquire_for_read(OAuthStore::File)?;
load_oauth_tokens_from_file_with_lock_held(server_name, url)
.map(|entry| entry.map(|(_, tokens)| tokens))
.context("failed to probe OAuth tokens from resolved file storage")
}
Backend::Keyring(AuthKeyringBackendKind::Direct) => {
load_oauth_tokens_from_keyring(keyring_store, AuthKeyringBackendKind::Direct, server_name, url)
.map_err(anyhow::Error::from)
.context("failed to reread OAuth tokens from resolved keyring storage; refusing file fallback")
}
Backend::Keyring(AuthKeyringBackendKind::Secrets) => {
let _store_lock = OAuthStoreLock::try_acquire_for_read(OAuthStore::Secrets)?;
load_oauth_tokens_from_secrets_keyring_with_lock_held(
keyring_store,
server_name,
url,
)
.map_err(anyhow::Error::from)
}
}
}
/// Saves credentials only to this already-resolved authority.
pub(crate) fn save<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
server_name: &str,
tokens: &StoredOAuthTokens,
) -> Result<()> {
let mut observation = telemetry::resolved(self, Operation::Save);
let result = match self.backend {
Backend::File => save_oauth_tokens_to_file(tokens),
Backend::Keyring(keyring_backend_kind) => save_oauth_tokens_with_keyring(
keyring_store,
keyring_backend_kind,
server_name,
tokens,
),
};
observation.record_save_attempt(telemetry::store(self), &result);
if matches!(self.backend, Backend::Keyring(_))
&& let Err(error) = &result
{
telemetry::record_secure_error(&mut observation, error.as_ref());
}
result
}
/// Records the refresh-persistence milestone in addition to the underlying pinned save.
pub(crate) fn save_with_refresh_telemetry<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
server_name: &str,
tokens: &StoredOAuthTokens,
) -> Result<()> {
let mut observation = telemetry::resolved(self, Operation::RefreshPersist);
let result = self.save(keyring_store, server_name, tokens);
observation.record_save_attempt(telemetry::store(self), &result);
if matches!(self.backend, Backend::Keyring(_))
&& let Err(error) = &result
{
telemetry::record_secure_error(&mut observation, error.as_ref());
}
result
}
/// Retires a rejected refresh token only while its durable snapshot still matches.
///
/// File and Secrets keep one exclusive aggregate lock across the comparison and write,
/// including against legacy writers that do not take the caller's refresh guard. Direct
/// keyring callers must hold that guard and use a home-scoped enterprise credential.
pub(crate) fn retire_refresh_token_if_matches<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
server_name: &str,
url: &str,
expected: &StoredOAuthTokens,
) -> Result<()> {
let mut observation = telemetry::resolved(self, Operation::Load);
let mut _store_lock = None;
let mut file_key = None;
let current = (|| -> Result<_> {
_store_lock = match self.backend {
Backend::File => Some(OAuthStoreLock::acquire_for_write(OAuthStore::File)?),
Backend::Keyring(AuthKeyringBackendKind::Secrets) => {
Some(OAuthStoreLock::acquire_for_write(OAuthStore::Secrets)?)
}
Backend::Keyring(AuthKeyringBackendKind::Direct) => None,
};
match self.backend {
Backend::File => Ok(
load_oauth_tokens_from_file_with_lock_held(server_name, url)?.map(
|(key, tokens)| {
file_key = Some(key);
tokens
},
),
),
Backend::Keyring(AuthKeyringBackendKind::Secrets) => {
load_oauth_tokens_from_secrets_keyring_with_lock_held(
keyring_store,
server_name,
url,
)
.map_err(anyhow::Error::from)
}
Backend::Keyring(AuthKeyringBackendKind::Direct) => load_oauth_tokens_from_keyring(
keyring_store,
AuthKeyringBackendKind::Direct,
server_name,
url,
)
.map_err(anyhow::Error::from),
}
})();
observation.record_load_attempt(telemetry::store(self), &current);
if matches!(self.backend, Backend::Keyring(_))
&& let Err(error) = &current
{
telemetry::record_secure_error(&mut observation, error.as_ref());
}
drop(observation);
let current = current?;
if normalized_oauth_credentials(current.as_ref())
!= normalized_oauth_credentials(Some(expected))
{
return Ok(());
}
let mut retired = expected.clone();
retired.token_response.0.set_refresh_token(None);
let mut observation = telemetry::resolved(self, Operation::Save);
let result = match self.backend {
Backend::File => {
let mut store = read_fallback_file_unlocked()?.context("OAuth file disappeared")?;
// Reuse the key we compared: another binary may compute a different key.
let key = file_key.context("missing loaded OAuth file key")?;
store
.get_mut(&key)
.context("OAuth file entry disappeared")?
.refresh_token = None;
write_fallback_file(&store)
}
Backend::Keyring(AuthKeyringBackendKind::Secrets) => {
let serialized =
serde_json::to_string(&retired).context("failed to serialize OAuth tokens")?;
save_oauth_tokens_to_secrets_keyring_with_lock_held(
keyring_store,
server_name,
&retired,
&serialized,
)
}
Backend::Keyring(AuthKeyringBackendKind::Direct) => {
save_oauth_tokens_to_direct_keyring(keyring_store, server_name, &retired)
}
};
observation.record_save_attempt(telemetry::store(self), &result);
if matches!(self.backend, Backend::Keyring(_))
&& let Err(error) = &result
{
telemetry::record_secure_error(&mut observation, error.as_ref());
}
result
}
/// Deletes credentials only from this already-resolved authority.
pub(crate) fn delete<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
server_name: &str,
url: &str,
) -> Result<bool> {
let mut observation = telemetry::resolved(self, Operation::Delete);
let result = match self.backend {
Backend::File => compute_store_key(server_name, url)
.and_then(|key| delete_oauth_tokens_from_file(&key)),
Backend::Keyring(AuthKeyringBackendKind::Direct) => {
delete_oauth_tokens_from_direct_keyring(keyring_store, server_name, url)
}
Backend::Keyring(AuthKeyringBackendKind::Secrets) => {
delete_oauth_tokens_from_secrets_keyring(keyring_store, server_name, url)
}
};
observation.record_delete_attempt(telemetry::store(self), &result);
if matches!(self.backend, Backend::Keyring(_))
&& let Err(error) = &result
{
telemetry::record_secure_error(&mut observation, error.as_ref());
}
result
}
}
#[derive(Debug)]
pub(crate) struct ResolvedOAuthTokens {
pub(crate) tokens: StoredOAuthTokens,
pub(crate) store: ResolvedOAuthCredentialStore,
}
pub(crate) fn resolve_oauth_tokens_from_store_policy<K: KeyringStore + Clone + 'static>(
keyring_store: &K,
server_name: &str,
url: &str,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<Option<ResolvedOAuthTokens>> {
let mut observation = telemetry::policy(store_mode, keyring_backend_kind, Operation::Load);
match store_mode {
OAuthCredentialsStoreMode::Auto => {
// Auto remains keyring-first at lifecycle startup. The returned source is then pinned
// by the client transport recipe and OAuth persistor so retries, recovery, and
// refresh work cannot hot-switch stores.
// TODO(stevenlee): Different processes can still resolve Auto to different stores
// when keyring availability differs. Solving that safely requires durable backend
// selection or reconciliation of legacy entries and is intentionally outside this
// stack.
let result = load_oauth_tokens_from_keyring(
keyring_store,
keyring_backend_kind,
server_name,
url,
);
observation.record_load_attempt(telemetry::keyring(keyring_backend_kind), &result);
match result {
Ok(Some(tokens)) => Ok(Some(ResolvedOAuthTokens {
tokens,
store: ResolvedOAuthCredentialStore::keyring(keyring_backend_kind)
.with_policy(store_mode, keyring_backend_kind),
})),
Ok(None) => {
let result = load_oauth_tokens_from_file(server_name, url);
observation.record_load_attempt(Store::File, &result);
Ok(result?.map(|tokens| ResolvedOAuthTokens {
tokens,
store: ResolvedOAuthCredentialStore::file()
.with_policy(store_mode, keyring_backend_kind),
}))
}
// Auto may fall back when the keyring backend is unavailable, but a Secrets
// aggregate-lock failure means authority may be changing. Consulting File in
// that state could replay credentials hidden behind a newer Secrets entry.
Err(OAuthKeyringLoadError::StoreLock(error)) => {
telemetry::record_secure_error(&mut observation, &error);
Err(error.into())
}
Err(error) => {
telemetry::record_secure_error(&mut observation, &error);
let result = load_oauth_tokens_from_file(server_name, url);
observation.record_load_attempt(Store::File, &result);
Ok(result
.with_context(|| {
format!("failed to read OAuth tokens from keyring: {error}")
})?
.map(|tokens| ResolvedOAuthTokens {
tokens,
store: ResolvedOAuthCredentialStore::file()
.with_policy(store_mode, keyring_backend_kind),
}))
}
}
}
OAuthCredentialsStoreMode::File => {
let result = load_oauth_tokens_from_file(server_name, url);
observation.record_load_attempt(Store::File, &result);
Ok(result?.map(|tokens| ResolvedOAuthTokens {
tokens,
store: ResolvedOAuthCredentialStore::file()
.with_policy(store_mode, keyring_backend_kind),
}))
}
OAuthCredentialsStoreMode::Keyring => {
let result = load_oauth_tokens_from_keyring(
keyring_store,
keyring_backend_kind,
server_name,
url,
);
observation.record_load_attempt(telemetry::keyring(keyring_backend_kind), &result);
if let Err(error) = &result {
telemetry::record_secure_error(&mut observation, error);
}
Ok(result
.map_err(anyhow::Error::from)
.context("failed to read OAuth tokens from keyring")?
.map(|tokens| ResolvedOAuthTokens {
tokens,
store: ResolvedOAuthCredentialStore::keyring(keyring_backend_kind)
.with_policy(store_mode, keyring_backend_kind),
}))
}
}
}
pub(crate) fn try_resolve_oauth_tokens_from_store_policy<K: KeyringStore + Clone + 'static>(
keyring_store: &K,
server_name: &str,
url: &str,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<Option<ResolvedOAuthTokens>> {
let mut observation = telemetry::policy(store_mode, keyring_backend_kind, Operation::Load);
let mut load = |store: ResolvedOAuthCredentialStore| {
let result = store.try_load(keyring_store, server_name, url);
observation.record_load_attempt(telemetry::store(store), &result);
if matches!(store.backend, Backend::Keyring(_))
&& let Err(error) = &result
{
telemetry::record_secure_error(&mut observation, error.as_ref());
}
result.map(|tokens| tokens.map(|tokens| ResolvedOAuthTokens { tokens, store }))
};
let keyring = ResolvedOAuthCredentialStore::keyring(keyring_backend_kind)
.with_policy(store_mode, keyring_backend_kind);
match store_mode {
OAuthCredentialsStoreMode::File => {
load(ResolvedOAuthCredentialStore::file().with_policy(store_mode, keyring_backend_kind))
}
OAuthCredentialsStoreMode::Keyring => load(keyring),
OAuthCredentialsStoreMode::Auto => match load(keyring) {
Ok(Some(tokens)) => Ok(Some(tokens)),
Ok(None) => load(
ResolvedOAuthCredentialStore::file().with_policy(store_mode, keyring_backend_kind),
),
Err(error) if error.downcast_ref::<OAuthStoreLockFailure>().is_some() => Err(error),
Err(error) => load(
ResolvedOAuthCredentialStore::file().with_policy(store_mode, keyring_backend_kind),
)
.with_context(|| format!("failed to read OAuth tokens from keyring: {error}")),
},
}
}

View File

@@ -0,0 +1,64 @@
//! Keeps one OAuth refresh and persistence owner for the lifetime of a connection.
//!
//! Both modes use cached expiry to prepare credentials before the MCP request budget.
//! Coordinated preparation owns a task so caller cancellation cannot interrupt persistence.
//! It locks the manager before the credential store, matching RMCP's lock order.
//! RMCP commits through the pinned store while Legacy retains Codex's persistor.
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use rmcp::transport::auth::AuthorizationManager;
use tokio::sync::Mutex;
use tracing::warn;
use super::OAuthPersistor;
use super::credential_store::OAuthCredentialStore;
use super::token_needs_refresh;
#[derive(Clone)]
pub(crate) enum OAuthRuntime {
Legacy(OAuthPersistor),
Coordinated {
auth_manager: Arc<Mutex<AuthorizationManager>>,
store: OAuthCredentialStore,
},
}
impl OAuthRuntime {
#[expect(
clippy::await_holding_invalid_type,
reason = "AuthorizationManager access follows RMCP's manager-before-credential lock order"
)]
pub(crate) async fn refresh_if_needed(&self) -> Result<()> {
match self {
Self::Legacy(persistor) => persistor.refresh_if_needed().await,
Self::Coordinated {
auth_manager,
store,
} => {
let expires_at = store
.stored_credentials()
.await
.and_then(|tokens| tokens.expires_at);
if !token_needs_refresh(expires_at) {
return Ok(());
}
let auth_manager = Arc::clone(auth_manager);
let store = store.clone();
tokio::spawn(async move {
let mut manager = auth_manager.lock().await;
let result = store.refresh_if_needed(&mut manager).await;
if result.is_err() {
// Keep the summary in the owned task without logging credential/provider data.
warn!("MCP OAuth preparation failed");
}
result
})
.await
.context("OAuth refresh task failed")?
}
}
}
}

View File

@@ -0,0 +1,212 @@
//! Cross-process serialization for MCP OAuth stores shared by multiple credentials.
//!
//! File and Secrets each keep credentials for multiple MCP servers in one aggregate document.
//! Writers hold an exclusive lock across the complete read-modify-write operation. Readers share
//! the same lock so concurrent MCP startup and status checks do not serialize behind one another.
//! Direct keyring entries are already stored independently per credential and do not use this lock.
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use std::time::Instant;
use codex_utils_home_dir::find_codex_home;
const OAUTH_LOCK_DIR: &str = "mcp-oauth-locks";
const STORE_LOCK_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(60);
const STORE_LOCK_RETRY_SLEEP: Duration = Duration::from_millis(50);
// Tests listen for this event so they prove a contender reached the real WouldBlock branch.
const LOCK_CONTENTION_EVENT_TARGET: &str = "codex_rmcp_client::oauth::store_lock::contention";
#[derive(Clone, Copy, Debug)]
pub(super) enum OAuthStore {
File,
Secrets,
}
impl OAuthStore {
fn lock_filename(self) -> &'static str {
match self {
Self::File => "file-store.lock",
Self::Secrets => "secrets-store.lock",
}
}
}
impl std::fmt::Display for OAuthStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::File => f.write_str("fallback file"),
Self::Secrets => f.write_str("encrypted secrets"),
}
}
}
/// Serializes one complete operation on an aggregate OAuth credential store.
pub(super) struct OAuthStoreLock {
_file: File,
}
#[derive(Clone, Copy, Debug)]
enum OAuthStoreLockMode {
Shared,
Exclusive,
}
impl OAuthStoreLock {
pub(super) fn acquire_for_write(store: OAuthStore) -> Result<Self, OAuthStoreLockFailure> {
Self::acquire_with_timeout(
store,
STORE_LOCK_ACQUIRE_TIMEOUT,
OAuthStoreLockMode::Exclusive,
)
}
pub(super) fn acquire_for_read(store: OAuthStore) -> Result<Self, OAuthStoreLockFailure> {
Self::acquire_with_timeout(
store,
STORE_LOCK_ACQUIRE_TIMEOUT,
OAuthStoreLockMode::Shared,
)
}
pub(super) fn try_acquire_for_read(store: OAuthStore) -> Result<Self, OAuthStoreLockFailure> {
Self::acquire_with_timeout(store, Duration::ZERO, OAuthStoreLockMode::Shared)
}
fn acquire_with_timeout(
store: OAuthStore,
acquire_timeout: Duration,
mode: OAuthStoreLockMode,
) -> Result<Self, OAuthStoreLockFailure> {
// This lock intentionally follows the existing local File/Secrets credential-store
// authority. Those stores are CODEX_HOME-backed today: if CODEX_HOME is unset they use
// the default home (`~/.codex`), and if an embedder has no local home/filesystem authority
// those stores already cannot operate. A future provider-backed credential store should
// provide its own matching lock authority instead of using this local path.
let codex_home = find_codex_home()
.map_err(|source| OAuthStoreLockFailure::CodexHome { store, source })?;
Self::acquire_in_with_mode(&codex_home, store, acquire_timeout, mode)
}
fn acquire_in_with_mode(
codex_home: &Path,
store: OAuthStore,
acquire_timeout: Duration,
mode: OAuthStoreLockMode,
) -> Result<Self, OAuthStoreLockFailure> {
let path = oauth_store_lock_path(codex_home, store);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|source| OAuthStoreLockFailure::CreateDir {
store,
path: parent.to_path_buf(),
source,
})?;
}
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.map_err(|source| OAuthStoreLockFailure::Open {
store,
path: path.clone(),
source,
})?;
let started = Instant::now();
let mut reported_contention = false;
loop {
let result = match mode {
OAuthStoreLockMode::Shared => file.try_lock_shared(),
OAuthStoreLockMode::Exclusive => file.try_lock(),
};
match result {
Ok(()) => return Ok(Self { _file: file }),
Err(std::fs::TryLockError::WouldBlock) if started.elapsed() >= acquire_timeout => {
return Err(OAuthStoreLockFailure::Timeout {
store,
path,
acquire_timeout,
});
}
Err(std::fs::TryLockError::WouldBlock) => {
if !reported_contention {
tracing::debug!(
target: LOCK_CONTENTION_EVENT_TARGET,
store = %store,
lock_path = %path.display(),
"waiting for another process to finish updating MCP OAuth store state"
);
reported_contention = true;
}
std::thread::sleep(STORE_LOCK_RETRY_SLEEP.min(acquire_timeout));
}
Err(error) => {
return Err(OAuthStoreLockFailure::Lock {
store,
path,
source: io::Error::from(error),
});
}
}
}
}
}
/// Auto may fall back when the configured keyring backend is unavailable, but it must surface a
/// lock failure. Falling back while another process owns the aggregate-store lock could leave the
/// newer credential in File while a stale Secrets entry remains preferred.
#[derive(Debug, thiserror::Error)]
pub(super) enum OAuthStoreLockFailure {
#[error("failed to resolve CODEX_HOME for MCP OAuth {store} aggregate-store lock")]
CodexHome {
store: OAuthStore,
#[source]
source: io::Error,
},
#[error("failed to create MCP OAuth {store} aggregate-store lock directory {}", path.display())]
CreateDir {
store: OAuthStore,
path: PathBuf,
#[source]
source: io::Error,
},
#[error("failed to open MCP OAuth {store} aggregate-store lock {}", path.display())]
Open {
store: OAuthStore,
path: PathBuf,
#[source]
source: io::Error,
},
#[error(
"timed out after {acquire_timeout:?} waiting for MCP OAuth {store} aggregate-store lock {}",
path.display()
)]
Timeout {
store: OAuthStore,
path: PathBuf,
acquire_timeout: Duration,
},
#[error("failed to lock MCP OAuth {store} aggregate-store lock {}", path.display())]
Lock {
store: OAuthStore,
path: PathBuf,
#[source]
source: io::Error,
},
}
fn oauth_store_lock_path(codex_home: &Path, store: OAuthStore) -> PathBuf {
codex_home.join(OAUTH_LOCK_DIR).join(store.lock_filename())
}
#[cfg(test)]
#[path = "tests/store_lock_tests.rs"]
mod tests;

View File

@@ -0,0 +1,97 @@
//! Maps MCP storage policy, pinned stores, and typed failures to credential-free metric dimensions.
use super::OAuthKeyringLoadError;
use super::OAuthStoreLockFailure;
use super::ResolvedOAuthCredentialStore;
use super::resolved_store::Backend;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_otel::auth_storage::CredentialKind;
use codex_otel::auth_storage::Operation;
use codex_otel::auth_storage::StoragePhase;
use codex_otel::auth_storage::StorageTelemetry;
use codex_otel::auth_storage::Store;
use codex_otel::auth_storage::StoreMode;
use std::error::Error;
use std::io::ErrorKind;
/// Preserve aggregate-lock categories even when a transparent load error hides their source.
pub(super) fn record_secure_error(
observation: &mut StorageTelemetry,
error: &(dyn Error + 'static),
) {
let mut cause = Some(error);
while let Some(current) = cause {
let lock = match current.downcast_ref::<OAuthKeyringLoadError>() {
Some(OAuthKeyringLoadError::StoreLock(lock)) => Some(lock),
Some(OAuthKeyringLoadError::Backend(_)) | None => {
current.downcast_ref::<OAuthStoreLockFailure>()
}
};
if let Some(OAuthStoreLockFailure::Timeout {
acquire_timeout, ..
}) = lock
{
let kind = if acquire_timeout.is_zero() {
ErrorKind::WouldBlock
} else {
ErrorKind::TimedOut
};
observation.record_secure_error(&std::io::Error::from(kind));
return;
}
cause = current.source();
}
observation.record_secure_error(error);
}
pub(super) fn keyring(kind: AuthKeyringBackendKind) -> Store {
match kind {
AuthKeyringBackendKind::Direct => Store::DirectKeyring,
AuthKeyringBackendKind::Secrets => Store::Secrets,
}
}
pub(super) fn store(store: ResolvedOAuthCredentialStore) -> Store {
match store.backend {
Backend::File => Store::File,
Backend::Keyring(kind) => keyring(kind),
}
}
pub(super) fn policy(
mode: OAuthCredentialsStoreMode,
kind: AuthKeyringBackendKind,
operation: Operation,
) -> StorageTelemetry {
StorageTelemetry::new(
CredentialKind::Mcp,
store_mode(mode),
keyring(kind),
operation,
AuthStorageOriginator::current(),
)
}
pub(super) fn resolved(
source: ResolvedOAuthCredentialStore,
operation: Operation,
) -> StorageTelemetry {
StorageTelemetry::new(
CredentialKind::Mcp,
store_mode(source.mode),
keyring(source.kind),
operation,
source.originator,
)
.with_phase(StoragePhase::Pinned)
}
fn store_mode(mode: OAuthCredentialsStoreMode) -> StoreMode {
match mode {
OAuthCredentialsStoreMode::File => StoreMode::File,
OAuthCredentialsStoreMode::Auto => StoreMode::Auto,
OAuthCredentialsStoreMode::Keyring => StoreMode::Keyring,
}
}

View File

@@ -0,0 +1,69 @@
use std::path::Path;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::OnceLock;
use std::sync::PoisonError;
use tempfile::tempdir;
/// Build the actual client's Stop-policy route pool before measuring protocol deadlines.
/// Client construction loads platform/custom CA state and can be slow on developer hosts.
/// Use a separate local endpoint so warmup cannot affect the test server's request assertions;
/// the same production HTTP capability still applies all proxy and certificate policy.
pub(crate) async fn warm_http_client(
client: &dyn codex_exec_server::HttpClient,
) -> anyhow::Result<()> {
let server = wiremock::MockServer::start().await;
client
.http_request(codex_exec_server::HttpRequestParams {
method: "GET".to_string(),
url: server.uri(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: codex_exec_server::HttpRedirectPolicy::Stop,
request_id: "test-client-warmup".to_string(),
stream_response: false,
})
.await?;
Ok(())
}
/// Serializes tests that mutate process-wide CODEX_HOME.
///
/// Keep OAuth tests on this one guard instead of defining per-module helpers; otherwise
/// concurrently running test modules can point File/Secrets storage at different homes.
pub(crate) struct TempCodexHome {
_guard: MutexGuard<'static, ()>,
_dir: tempfile::TempDir,
}
impl TempCodexHome {
pub(crate) fn new() -> Self {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
let guard = LOCK
.get_or_init(Mutex::default)
.lock()
.unwrap_or_else(PoisonError::into_inner);
let dir = tempdir().expect("create CODEX_HOME temp dir");
unsafe {
std::env::set_var("CODEX_HOME", dir.path());
}
Self {
_guard: guard,
_dir: dir,
}
}
pub(super) fn path(&self) -> &Path {
self._dir.path()
}
}
impl Drop for TempCodexHome {
fn drop(&mut self) {
unsafe {
std::env::remove_var("CODEX_HOME");
}
}
}

View File

@@ -0,0 +1,387 @@
//! Verifies guarded mutations, pinned storage, token mapping, and saved runtime snapshots.
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Result;
use codex_config::types::AuthKeyringBackendKind;
use keyring::Error as KeyringError;
use oauth2::AccessToken;
use oauth2::RefreshToken;
use oauth2::TokenResponse;
use pretty_assertions::assert_eq;
use rmcp::transport::auth::AuthError;
use rmcp::transport::auth::CredentialStore;
use super::MockKeyringStore;
use super::TempCodexHome;
use super::assert_tokens_match_without_expiry;
use super::sample_tokens;
use crate::oauth::OAuthCredentialStore;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::ResolvedOAuthCredentialStore;
use crate::oauth::compute_store_key;
use crate::oauth::load_oauth_tokens_from_file;
use crate::oauth::normalized_oauth_credentials;
use crate::oauth::save_oauth_tokens_to_file;
use crate::oauth::save_oauth_tokens_to_file_with_lock_held;
use crate::oauth::store_lock::OAuthStore;
use crate::oauth::store_lock::OAuthStoreLock;
#[tokio::test(flavor = "current_thread")]
async fn mutations_require_and_retain_the_transaction_guard() -> Result<()> {
for clear in [false, true] {
let _env = TempCodexHome::new();
let initial = sample_tokens();
save_oauth_tokens_to_file(&initial)?;
let store = OAuthCredentialStore::new(
initial.clone(),
ResolvedOAuthCredentialStore::file(),
MockKeyringStore::default(),
/*oauth_config*/ None,
);
let guard = store.acquire_transaction_guard().await?;
let credentials = store.load().await?.unwrap();
if !clear {
store.clear().await?;
}
drop(guard);
let result = if clear {
store.clear().await
} else {
store.save(credentials.clone()).await
};
assert!(
matches!(result, Err(AuthError::CredentialStoreError(error)) if error.contains("active refresh guard"))
);
assert_eq!(
load_oauth_tokens_from_file(&initial.server_name, &initial.url)?.is_none(),
!clear,
);
// Guard acquisition now rereads storage. Restore the deleted credential first,
// then delete it again under the guard so the queued save must recreate it.
save_oauth_tokens_to_file(&initial)?;
let guard = CredentialStore::acquire_refresh_guard(&store)
.await?
.expect("coordinated refresh guard");
if !clear {
store.clear().await?;
}
let aggregate_lock = OAuthStoreLock::acquire_for_write(OAuthStore::File)?;
let mut mutation = if clear {
store.clear()
} else {
store.save(credentials)
};
assert!(futures::poll!(&mut mutation).is_pending());
drop(mutation);
drop(guard);
// The aggregate lock gates I/O, but only the retained refresh guard blocks this probe.
let mut contender = Box::pin(RefreshCredentialLock::acquire_for_server(
&initial.server_name,
&initial.url,
));
assert!(futures::poll!(&mut contender).is_pending());
drop(aggregate_lock);
let _guard = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), contender).await??;
let durable = load_oauth_tokens_from_file(&initial.server_name, &initial.url)?;
assert_eq!(durable.is_none(), clear);
}
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn save_publishes_only_persisted_credentials() -> Result<()> {
for fail_save in [false, true] {
let _env = TempCodexHome::new();
let initial = sample_tokens();
let keyring = MockKeyringStore::default();
let authority = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
authority.save(&keyring, &initial.server_name, &initial)?;
let mut fallback = initial.clone();
fallback
.token_response
.0
.set_access_token(AccessToken::new("fallback-token".into()));
save_oauth_tokens_to_file(&fallback)?;
let store = OAuthCredentialStore::new(
initial.clone(),
authority,
keyring.clone(),
/*oauth_config*/ None,
);
let _guard = store.acquire_transaction_guard().await?;
let mut credentials = store.load().await?.expect("stored credentials");
let token_response = credentials
.token_response
.as_mut()
.expect("stored token response");
token_response.set_access_token(AccessToken::new("rotated-access".into()));
token_response.set_refresh_token(Some(RefreshToken::new("rotated-refresh".into())));
// The adapter must encode the separate authoritative grant in the stored response.
token_response.set_scopes(/*scopes*/ None);
if fail_save {
let key = compute_store_key(&initial.server_name, &initial.url)?;
keyring.set_error(&key, KeyringError::Invalid("test".into(), "save".into()));
}
let result = store.save(credentials).await;
let durable = authority
.load(&keyring, &initial.server_name, &initial.url)?
.expect("durable keyring credentials");
let mut expected = initial.clone();
if fail_save {
assert!(matches!(result, Err(AuthError::CredentialStoreError(_))));
} else {
result?;
expected
.token_response
.0
.set_access_token(AccessToken::new("rotated-access".into()));
expected
.token_response
.0
.set_refresh_token(Some(RefreshToken::new("rotated-refresh".into())));
expected.expires_at = durable.expires_at;
}
assert_tokens_match_without_expiry(&durable, &expected);
assert_eq!(
store.stored_credentials().await,
normalized_oauth_credentials(Some(&expected))
);
assert_tokens_match_without_expiry(
&load_oauth_tokens_from_file(&initial.server_name, &initial.url)?.unwrap(),
&fallback,
);
}
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn pinned_read_failure_does_not_adopt_fallback_credentials() -> Result<()> {
let _env = TempCodexHome::new();
let initial = sample_tokens();
save_oauth_tokens_to_file(&initial)?;
let keyring = MockKeyringStore::default();
let key = compute_store_key(&initial.server_name, &initial.url)?;
keyring.set_error(&key, KeyringError::Invalid("test".into(), "load".into()));
let store = OAuthCredentialStore::new(
initial.clone(),
ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct),
keyring,
/*oauth_config*/ None,
);
let cached = store.load().await?.expect("cached credentials");
assert_eq!(
cached.token_response.unwrap().access_token().secret(),
initial.token_response.0.access_token().secret()
);
assert!(matches!(
store.acquire_transaction_guard().await,
Err(AuthError::CredentialStoreError(_))
));
assert_eq!(
store.stored_credentials().await,
normalized_oauth_credentials(Some(&initial))
);
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn replacement_or_removal_does_not_acknowledge_a_new_runtime_snapshot() -> Result<()> {
let _env = TempCodexHome::new();
let initial = sample_tokens();
save_oauth_tokens_to_file(&initial)?;
let store = OAuthCredentialStore::new(
initial.clone(),
ResolvedOAuthCredentialStore::file(),
MockKeyringStore::default(),
/*oauth_config*/ None,
);
let original_snapshot = store.stored_credentials().await;
for (client_id, issuer) in [
("replacement-client", initial.issuer.clone()),
(
initial.client_id.as_str(),
Some("https://replacement.example.test".into()),
),
(initial.client_id.as_str(), None),
] {
let mut replacement = initial.clone();
replacement.client_id = client_id.into();
replacement.issuer = issuer;
save_oauth_tokens_to_file(&replacement)?;
assert!(matches!(
store.acquire_transaction_guard().await,
Err(AuthError::AuthorizationRequired)
));
assert_eq!(store.stored_credentials().await, original_snapshot);
}
save_oauth_tokens_to_file(&initial)?;
let guard = store.acquire_transaction_guard().await?;
store.clear().await?;
assert!(load_oauth_tokens_from_file(&initial.server_name, &initial.url)?.is_none());
drop(guard);
assert!(matches!(
store.acquire_transaction_guard().await,
Err(AuthError::AuthorizationRequired)
));
assert!(store.load().await?.is_some());
assert_eq!(store.stored_credentials().await, original_snapshot);
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn storage_roundtrip_preserves_absolute_and_unknown_expiry() -> Result<()> {
let _env = TempCodexHome::new();
let initial = sample_tokens();
save_oauth_tokens_to_file(&initial)?;
let store = OAuthCredentialStore::new(
initial.clone(),
ResolvedOAuthCredentialStore::file(),
MockKeyringStore::default(),
/*oauth_config*/ None,
);
let future_received_at = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let future_deadline = (future_received_at + 120) * 1000;
for (received_at, expected_deadline) in [
(Some(future_received_at), Some(future_deadline)),
(None, None),
] {
let guard = store.acquire_transaction_guard().await?;
let mut credentials = store.load().await?.unwrap();
credentials.token_received_at = received_at;
credentials
.token_response
.as_mut()
.unwrap()
.set_expires_in(Some(&Duration::from_secs(/*secs*/ 120)));
store.save(credentials).await?;
let durable = load_oauth_tokens_from_file(&initial.server_name, &initial.url)?.unwrap();
let mut expected = initial.clone();
expected.expires_at = expected_deadline;
expected
.token_response
.0
.set_expires_in(expected_deadline.map(|_| Duration::ZERO).as_ref());
assert_tokens_match_without_expiry(&durable, &expected);
drop(guard);
let _guard = store.acquire_transaction_guard().await?;
let reloaded = store.load().await?.unwrap();
let expires_in = reloaded.token_response.unwrap().expires_in();
if let Some(expected_deadline) = expected_deadline {
let expires_in = expires_in.expect("future token expiry");
assert!(!expires_in.is_zero());
let reconstructed_deadline =
Duration::from_secs(reloaded.token_received_at.expect("token receipt time"))
+ expires_in;
let expected_deadline = Duration::from_millis(expected_deadline);
// Receipt times use whole seconds, so reconstruction may lose less than a second.
assert!(reconstructed_deadline <= expected_deadline);
assert!(expected_deadline - reconstructed_deadline < Duration::from_secs(/*secs*/ 1));
} else {
assert_eq!(expires_in, None);
}
assert_eq!(
store.stored_credentials().await,
normalized_oauth_credentials(Some(&expected))
);
}
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn cancelled_rejection_retains_guard_and_preserves_replacement() -> Result<()> {
let _env = TempCodexHome::new();
let initial = sample_tokens();
save_oauth_tokens_to_file(&initial)?;
let store = OAuthCredentialStore::new(
initial.clone(),
ResolvedOAuthCredentialStore::file(),
MockKeyringStore::default(),
/*oauth_config*/ None,
);
let credentials = store.load().await?.unwrap();
assert!(matches!(
store.on_refresh_token_rejected(&credentials).await,
Err(AuthError::CredentialStoreError(error)) if error.contains("active refresh guard")
));
let guard = store.acquire_transaction_guard().await?;
let aggregate_lock = OAuthStoreLock::acquire_for_write(OAuthStore::File)?;
let mut mutation = store.on_refresh_token_rejected(&credentials);
assert!(futures::poll!(&mut mutation).is_pending());
drop(mutation);
drop(guard);
let mut contender = Box::pin(RefreshCredentialLock::acquire_for_server(
&initial.server_name,
&initial.url,
));
assert!(futures::poll!(&mut contender).is_pending());
let mut replacement = initial.clone();
replacement
.token_response
.0
.set_refresh_token(Some(RefreshToken::new("replacement-refresh".into())));
// A legacy writer may finish while retirement is waiting for the aggregate lock.
save_oauth_tokens_to_file_with_lock_held(&replacement)?;
drop(aggregate_lock);
let _guard = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), contender).await??;
let mut expected = initial.clone();
expected.token_response.0.set_refresh_token(None);
let durable = load_oauth_tokens_from_file(&initial.server_name, &initial.url)?.unwrap();
assert_tokens_match_without_expiry(&durable, &replacement);
assert_eq!(
store.stored_credentials().await,
normalized_oauth_credentials(Some(&expected))
);
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn keyring_rejection_respects_credential_scope() -> Result<()> {
for kind in [
AuthKeyringBackendKind::Direct,
AuthKeyringBackendKind::Secrets,
] {
let _env = TempCodexHome::new();
let initial = sample_tokens();
let keyring = MockKeyringStore::default();
let authority = ResolvedOAuthCredentialStore::keyring(kind);
authority.save(&keyring, &initial.server_name, &initial)?;
let store = OAuthCredentialStore::new(
initial.clone(),
authority,
keyring.clone(),
/*oauth_config*/ None,
);
let guard = store.acquire_transaction_guard().await?;
store
.on_refresh_token_rejected(&store.load().await?.unwrap())
.await?;
let mut retired = initial.clone();
retired.token_response.0.set_refresh_token(None);
let expected_durable = match kind {
AuthKeyringBackendKind::Direct => &initial,
AuthKeyringBackendKind::Secrets => &retired,
};
assert_tokens_match_without_expiry(
&authority
.load(&keyring, &initial.server_name, &initial.url)?
.unwrap(),
expected_durable,
);
assert_eq!(
store.stored_credentials().await,
normalized_oauth_credentials(Some(&retired))
);
drop(guard);
if kind == AuthKeyringBackendKind::Direct {
assert!(matches!(
store.acquire_transaction_guard().await,
Err(AuthError::AuthorizationRequired)
));
}
}
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,707 @@
use std::process::Command;
use std::sync::mpsc;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use codex_config::types::AuthKeyringBackendKind;
use codex_keyring_store::KeyringStore;
use codex_keyring_store::tests::MockKeyringStore;
use oauth2::AccessToken;
use oauth2::RefreshToken;
use oauth2::Scope;
use oauth2::TokenResponse;
use oauth2::basic::BasicTokenType;
use pretty_assertions::assert_eq;
use rmcp::transport::auth::OAuthTokenResponse;
use rmcp::transport::auth::VendorExtraTokenFields;
use tracing::Event;
use tracing::Id;
use tracing::Metadata;
use tracing::Subscriber;
use tracing::span::Attributes;
use tracing::span::Record;
use tracing::subscriber::Interest;
use super::OAuthStore;
use super::OAuthStoreLock;
use super::OAuthStoreLockFailure;
use super::OAuthStoreLockMode;
use crate::oauth::StoredOAuthCredentialSnapshot;
use crate::oauth::StoredOAuthTokens;
use crate::oauth::WrappedOAuthTokenResponse;
use crate::oauth::fallback_file_path;
use crate::oauth::load_oauth_tokens_from_file;
use crate::oauth::load_oauth_tokens_from_keyring;
use crate::oauth::resolve_oauth_tokens_from_store_policy;
use crate::oauth::save_oauth_tokens_to_file;
use crate::oauth::save_oauth_tokens_to_file_with_lock_held;
use crate::oauth::save_oauth_tokens_to_secrets_keyring_with_lock_held;
use crate::oauth::save_oauth_tokens_with_keyring;
use crate::oauth::save_oauth_tokens_with_keyring_with_fallback_to_file;
use crate::oauth::stored_oauth_credential_snapshot;
use crate::oauth::test_support::TempCodexHome;
use codex_config::types::OAuthCredentialsStoreMode;
const STORE_LOCK_CONTENTION_EVENT_TARGET: &str = "codex_rmcp_client::oauth::store_lock::contention";
// Contention is proven by the tracing event emitted after a real WouldBlock. Keep the timeout
// generous because it only bounds a failed test; it must not turn worker scheduling latency into
// a false failure on loaded CI hosts.
const STORE_LOCK_CONTENTION_EVENT_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
fn assert_tokens_match_without_expiry(actual: &StoredOAuthTokens, expected: &StoredOAuthTokens) {
assert_eq!(actual.server_name, expected.server_name);
assert_eq!(actual.url, expected.url);
assert_eq!(actual.client_id, expected.client_id);
assert_eq!(actual.expires_at, expected.expires_at);
assert_token_response_match_without_expiry(&actual.token_response, &expected.token_response);
}
fn assert_token_response_match_without_expiry(
actual: &WrappedOAuthTokenResponse,
expected: &WrappedOAuthTokenResponse,
) {
let actual_response = &actual.0;
let expected_response = &expected.0;
assert_eq!(
actual_response.access_token().secret(),
expected_response.access_token().secret()
);
assert_eq!(actual_response.token_type(), expected_response.token_type());
assert_eq!(
actual_response.refresh_token().map(RefreshToken::secret),
expected_response.refresh_token().map(RefreshToken::secret),
);
assert_eq!(actual_response.scopes(), expected_response.scopes());
assert_eq!(
actual_response.extra_fields().0,
expected_response.extra_fields().0
);
assert_eq!(
actual_response.expires_in().is_some(),
expected_response.expires_in().is_some()
);
}
fn sample_tokens() -> StoredOAuthTokens {
let mut response = OAuthTokenResponse::new(
AccessToken::new("access-token".to_string()),
BasicTokenType::Bearer,
VendorExtraTokenFields::default(),
);
response.set_refresh_token(Some(RefreshToken::new("refresh-token".to_string())));
response.set_scopes(Some(vec![
Scope::new("scope-a".to_string()),
Scope::new("scope-b".to_string()),
]));
let expires_in = Duration::from_secs(3600);
response.set_expires_in(Some(&expires_in));
let expires_at = crate::oauth::compute_expires_at_millis(&response);
StoredOAuthTokens {
server_name: "test-server".to_string(),
url: "https://example.test".to_string(),
issuer: Some("https://issuer.example.test".to_string()),
client_id: "client-id".to_string(),
token_response: WrappedOAuthTokenResponse(response),
expires_at,
}
}
#[test]
fn file_credentials_keep_repeated_local_prefixes_isolated() -> Result<()> {
let _env = TempCodexHome::new();
let config: codex_config::McpServerConfig = serde_json::from_value(serde_json::json!({
"url": "https://example.test",
}))?;
let mut first = sample_tokens();
first.server_name = config.oauth_credential_name("local:foo").into_owned();
first.expires_at = None;
first.token_response.0.set_expires_in(None);
save_oauth_tokens_to_file(&first)?;
let second_name = config.oauth_credential_name("local:local:foo");
assert_eq!(load_oauth_tokens_from_file(&second_name, &first.url)?, None);
let mut second = first.clone();
second.server_name = second_name.into_owned();
second
.token_response
.0
.set_access_token(AccessToken::new("second-token".to_string()));
save_oauth_tokens_to_file(&second)?;
for expected in [first, second] {
assert_eq!(
load_oauth_tokens_from_file(&expected.server_name, &expected.url)?,
Some(expected)
);
}
Ok(())
}
#[test]
fn legacy_rmcp_oauth_keyring_credentials_remain_readable() -> Result<()> {
let _env = TempCodexHome::new();
let keyring_store = MockKeyringStore::default();
let mut expected = sample_tokens();
expected.expires_at = None;
expected.token_response.0.set_expires_in(None);
let serialized = serde_json::json!({
"server_name": "test-server",
"url": "https://example.test",
"client_id": "client-id",
"token_response": {
"access_token": "access-token",
"token_type": "Bearer",
"refresh_token": "refresh-token",
"scope": "scope-a scope-b",
},
})
.to_string();
let key = crate::oauth::compute_store_key(&expected.server_name, &expected.url)?;
keyring_store.save(crate::oauth::KEYRING_SERVICE, &key, &serialized)?;
let resolved = resolve_oauth_tokens_from_store_policy(
&keyring_store,
&expected.server_name,
&expected.url,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
)?
.expect("OAuth credentials written before the rmcp upgrade should remain readable");
assert_eq!(
resolved.store,
crate::oauth::ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct)
);
assert_tokens_match_without_expiry(&resolved.tokens, &expected);
assert!(crate::oauth::oauth_tokens_are_usable(&resolved.tokens));
Ok(())
}
const LOCK_HOLDER_CHILD_TEST: &str =
"oauth::store_lock::tests::store_lock_is_released_when_holder_process_exits_child";
const LOCK_HOLDER_READY_PATH_ENV: &str = "CODEX_OAUTH_STORE_LOCK_CHILD_READY_PATH";
#[test]
fn store_lock_is_released_when_holder_process_exits() -> Result<()> {
let env = TempCodexHome::new();
let ready_file = env.path().join("lock-holder-ready");
let mut child = Command::new(std::env::current_exe()?)
.arg("--exact")
.arg(LOCK_HOLDER_CHILD_TEST)
.arg("--ignored")
.env("CODEX_HOME", env.path())
.env(LOCK_HOLDER_READY_PATH_ENV, &ready_file)
.spawn()
.context("spawn OAuth store lock holder test process")?;
let test_result = (|| -> Result<()> {
let started = Instant::now();
while !ready_file.exists() {
if started.elapsed() > Duration::from_secs(/*secs*/ 5) {
anyhow::bail!("timed out waiting for child process to acquire OAuth store lock");
}
std::thread::sleep(Duration::from_millis(/*millis*/ 20));
}
let error = match OAuthStoreLock::acquire_in_with_mode(
env.path(),
OAuthStore::File,
Duration::from_millis(/*millis*/ 100),
OAuthStoreLockMode::Exclusive,
) {
Ok(_) => {
anyhow::bail!("live holder process should keep the OAuth store lock unavailable")
}
Err(error) => error,
};
assert!(matches!(error, OAuthStoreLockFailure::Timeout { .. }));
child
.kill()
.context("kill OAuth store lock holder process")?;
let status = child
.wait()
.context("wait for killed OAuth store lock holder process")?;
assert!(!status.success());
let _lock = OAuthStoreLock::acquire_in_with_mode(
env.path(),
OAuthStore::File,
Duration::from_secs(/*secs*/ 1),
OAuthStoreLockMode::Exclusive,
)?;
Ok(())
})();
if let Ok(None) = child.try_wait() {
let _ = child.kill();
let _ = child.wait();
}
test_result
}
#[test]
#[ignore = "child process for store_lock_is_released_when_holder_process_exits"]
fn store_lock_is_released_when_holder_process_exits_child() -> Result<()> {
let ready_file = match std::env::var_os(LOCK_HOLDER_READY_PATH_ENV) {
Some(path) => std::path::PathBuf::from(path),
None => return Ok(()),
};
let _lock = OAuthStoreLock::acquire_for_write(OAuthStore::File)?;
std::fs::write(ready_file, b"ready")?;
loop {
std::thread::sleep(Duration::from_secs(/*secs*/ 60));
}
}
#[test]
fn auto_save_secrets_lock_failure_does_not_fall_back_to_file() -> Result<()> {
let env = TempCodexHome::new();
let lock_dir = env.path().join("mcp-oauth-locks");
std::fs::create_dir_all(&lock_dir)?;
// Break only the Secrets lock path. The distinct File lock remains usable, so Auto would
// successfully write fallback credentials if it mistook coordination failure for backend
// unavailability.
std::fs::create_dir(lock_dir.join("secrets-store.lock"))?;
let keyring_store = MockKeyringStore::default();
let tokens = sample_tokens();
let error = save_oauth_tokens_with_keyring_with_fallback_to_file(
&keyring_store,
AuthKeyringBackendKind::Secrets,
&tokens.server_name,
&tokens,
)
.expect_err("aggregate-store lock failure must abort Auto persistence");
assert!(error.downcast_ref::<OAuthStoreLockFailure>().is_some());
assert!(!fallback_file_path()?.exists());
save_oauth_tokens_to_file(&tokens)?;
let loaded = load_oauth_tokens_from_file(&tokens.server_name, &tokens.url)?
.expect("fallback File should remain independently writable");
assert_tokens_match_without_expiry(&loaded, &tokens);
Ok(())
}
#[test]
fn auto_load_secrets_lock_failure_does_not_fall_back_to_file() -> Result<()> {
let env = TempCodexHome::new();
let keyring_store = MockKeyringStore::default();
let tokens = sample_tokens();
save_oauth_tokens_to_file(&tokens)?;
let lock_dir = env.path().join("mcp-oauth-locks");
std::fs::create_dir(lock_dir.join("secrets-store.lock"))?;
let error = resolve_oauth_tokens_from_store_policy(
&keyring_store,
&tokens.server_name,
&tokens.url,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Secrets,
)
.expect_err("aggregate-store lock failure must abort Auto resolution");
assert!(error.downcast_ref::<OAuthStoreLockFailure>().is_some());
let loaded = load_oauth_tokens_from_file(&tokens.server_name, &tokens.url)?
.expect("fallback File should remain independently readable");
assert_tokens_match_without_expiry(&loaded, &tokens);
Ok(())
}
#[test]
fn oauth_credential_probes_skip_contended_file_and_secrets_stores() -> Result<()> {
let _env = TempCodexHome::new();
let tokens = sample_tokens();
let file = OAuthCredentialsStoreMode::File;
let auto = OAuthCredentialsStoreMode::Auto;
let direct = AuthKeyringBackendKind::Direct;
let secrets = AuthKeyringBackendKind::Secrets;
save_oauth_tokens_to_file(&tokens)?;
let snapshot =
stored_oauth_credential_snapshot(&tokens.server_name, &tokens.url, file, direct)?
.expect("fallback credentials should exist before contention");
let reload = |store_mode, keyring_backend_kind| {
snapshot.reload(
&tokens.server_name,
&tokens.url,
store_mode,
keyring_backend_kind,
)
};
let probe = |store_mode, keyring_backend_kind| {
StoredOAuthCredentialSnapshot::for_runtime_refresh(
/*previous*/ None,
&tokens.server_name,
&tokens.url,
store_mode,
keyring_backend_kind,
)
};
let refresh = |url| {
StoredOAuthCredentialSnapshot::for_runtime_refresh(
Some(&snapshot),
&tokens.server_name,
url,
file,
direct,
)
};
{
let _lock = OAuthStoreLock::acquire_for_write(OAuthStore::File)?;
assert_eq!(reload(file, direct)?, None);
assert_eq!(reload(auto, secrets)?, None);
assert_eq!(probe(file, direct)?, None);
let contended = refresh(&tokens.url)?.expect("the previous snapshot should be retained");
assert!(contended.store_was_contended());
assert_eq!(contended, snapshot);
assert_eq!(
refresh("https://another.example.test")?,
None,
"store contention must not replay credentials for another endpoint",
);
}
assert_eq!(reload(file, direct)?, Some(snapshot.credentials().clone()));
let refreshed = refresh(&tokens.url)?.expect("the unlocked store should still contain tokens");
assert!(!refreshed.store_was_contended());
let _lock = OAuthStoreLock::acquire_for_write(OAuthStore::Secrets)?;
assert_eq!(
probe(auto, secrets)?,
None,
"a locked Secrets authority must not fall back to the stale File entry",
);
Ok(())
}
struct LockContentionSubscriber {
contended_tx: mpsc::Sender<()>,
}
impl Subscriber for LockContentionSubscriber {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.target() == STORE_LOCK_CONTENTION_EVENT_TARGET
}
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
if self.enabled(metadata) {
Interest::always()
} else {
Interest::never()
}
}
fn max_level_hint(&self) -> Option<tracing::level_filters::LevelFilter> {
Some(tracing::level_filters::LevelFilter::DEBUG)
}
fn new_span(&self, _span: &Attributes<'_>) -> Id {
Id::from_u64(/*u*/ 1)
}
fn record(&self, _span: &Id, _values: &Record<'_>) {}
fn record_follows_from(&self, _span: &Id, _follows_from: &Id) {}
fn event(&self, event: &Event<'_>) {
if self.enabled(event.metadata()) {
self.contended_tx
.send(())
.expect("signal actual OAuth store lock contention");
}
}
fn enter(&self, _span: &Id) {}
fn exit(&self, _span: &Id) {}
}
fn complete_after_store_lock_contention<T>(
codex_home: &std::path::Path,
store: OAuthStore,
while_locked: impl FnOnce() -> Result<()>,
operation: impl FnOnce() -> Result<T> + Send + 'static,
) -> Result<T>
where
T: Send + 'static,
{
std::thread::scope(|scope| {
let held_lock = OAuthStoreLock::acquire_in_with_mode(
codex_home,
store,
Duration::from_millis(/*millis*/ 100),
OAuthStoreLockMode::Exclusive,
)?;
let (contended_tx, contended_rx) = mpsc::channel();
let worker = scope.spawn(move || {
tracing::subscriber::with_default(LockContentionSubscriber { contended_tx }, operation)
});
// This event is emitted only after `try_lock()` returns WouldBlock, so the test fails if the
// operation stops acquiring the aggregate-store lock.
contended_rx
.recv_timeout(STORE_LOCK_CONTENTION_EVENT_TIMEOUT)
.context("timed out waiting for actual OAuth store lock contention")?;
while_locked()?;
drop(held_lock);
worker
.join()
.expect("contending OAuth store worker should finish")
})
}
#[test]
fn aggregate_store_readers_share_access_while_writers_remain_exclusive() -> Result<()> {
let env = TempCodexHome::new();
for store in [OAuthStore::File, OAuthStore::Secrets] {
let readers = (0..2)
.map(|_| {
OAuthStoreLock::acquire_in_with_mode(
env.path(),
store,
Duration::from_millis(/*millis*/ 100),
OAuthStoreLockMode::Shared,
)
})
.collect::<Result<Vec<_>, _>>()?;
let writer_error = match OAuthStoreLock::acquire_in_with_mode(
env.path(),
store,
Duration::from_millis(/*millis*/ 100),
OAuthStoreLockMode::Exclusive,
) {
Ok(_) => anyhow::bail!("an active OAuth store reader must exclude writers"),
Err(error) => error,
};
assert!(matches!(
writer_error,
OAuthStoreLockFailure::Timeout { .. }
));
drop(readers);
let _writer = OAuthStoreLock::acquire_in_with_mode(
env.path(),
store,
Duration::from_millis(/*millis*/ 100),
OAuthStoreLockMode::Exclusive,
)?;
}
Ok(())
}
#[test]
fn aggregate_store_credential_loads_can_share_an_existing_reader() -> Result<()> {
let env = TempCodexHome::new();
let keyring_store = MockKeyringStore::default();
let tokens = sample_tokens();
save_oauth_tokens_to_file(&tokens)?;
save_oauth_tokens_with_keyring(
&keyring_store,
AuthKeyringBackendKind::Secrets,
&tokens.server_name,
&tokens,
)?;
let file_reader = OAuthStoreLock::acquire_in_with_mode(
env.path(),
OAuthStore::File,
Duration::from_millis(/*millis*/ 100),
OAuthStoreLockMode::Shared,
)?;
let file_tokens = load_oauth_tokens_from_file(&tokens.server_name, &tokens.url)?
.expect("a File credential read should coexist with another reader");
assert_tokens_match_without_expiry(&file_tokens, &tokens);
drop(file_reader);
let secrets_reader = OAuthStoreLock::acquire_in_with_mode(
env.path(),
OAuthStore::Secrets,
Duration::from_millis(/*millis*/ 100),
OAuthStoreLockMode::Shared,
)?;
let secrets_tokens = load_oauth_tokens_from_keyring(
&keyring_store,
AuthKeyringBackendKind::Secrets,
&tokens.server_name,
&tokens.url,
)?
.expect("a Secrets credential read should coexist with another reader");
assert_tokens_match_without_expiry(&secrets_tokens, &tokens);
drop(secrets_reader);
Ok(())
}
#[test]
fn file_store_lock_preserves_updates_for_different_servers() -> Result<()> {
let env = TempCodexHome::new();
let first = sample_tokens();
let mut second = sample_tokens();
second.server_name = "second-server".to_string();
second.url = "https://second.example.test".to_string();
let second_for_writer = second.clone();
complete_after_store_lock_contention(
env.path(),
OAuthStore::File,
|| save_oauth_tokens_to_file_with_lock_held(&first),
move || save_oauth_tokens_to_file(&second_for_writer),
)?;
let loaded_first = load_oauth_tokens_from_file(&first.server_name, &first.url)?
.expect("first server tokens should remain stored");
let loaded_second = load_oauth_tokens_from_file(&second.server_name, &second.url)?
.expect("second server tokens should be stored");
assert_tokens_match_without_expiry(&loaded_first, &first);
assert_tokens_match_without_expiry(&loaded_second, &second);
Ok(())
}
#[test]
fn file_store_load_and_delete_observe_aggregate_lock() -> Result<()> {
let env = TempCodexHome::new();
let tokens = sample_tokens();
save_oauth_tokens_to_file(&tokens)?;
let server_name = tokens.server_name.clone();
let url = tokens.url.clone();
let loaded = complete_after_store_lock_contention(
env.path(),
OAuthStore::File,
|| Ok(()),
move || load_oauth_tokens_from_file(&server_name, &url),
)?
.expect("file credentials should remain readable after contention");
assert_tokens_match_without_expiry(&loaded, &tokens);
let key = crate::oauth::compute_store_key(&tokens.server_name, &tokens.url)?;
let removed = complete_after_store_lock_contention(
env.path(),
OAuthStore::File,
|| Ok(()),
move || crate::oauth::delete_oauth_tokens_from_file(&key),
)?;
assert!(removed);
assert!(load_oauth_tokens_from_file(&tokens.server_name, &tokens.url)?.is_none());
Ok(())
}
#[test]
fn secrets_store_lock_preserves_updates_for_different_servers() -> Result<()> {
let env = TempCodexHome::new();
let keyring_store = MockKeyringStore::default();
let first = sample_tokens();
let mut second = sample_tokens();
second.server_name = "second-server".to_string();
second.url = "https://second.example.test".to_string();
let store_for_writer = keyring_store.clone();
let second_for_writer = second.clone();
complete_after_store_lock_contention(
env.path(),
OAuthStore::Secrets,
|| {
let first_serialized = serde_json::to_string(&first)?;
save_oauth_tokens_to_secrets_keyring_with_lock_held(
&keyring_store,
&first.server_name,
&first,
&first_serialized,
)
},
move || {
save_oauth_tokens_with_keyring(
&store_for_writer,
AuthKeyringBackendKind::Secrets,
&second_for_writer.server_name,
&second_for_writer,
)
},
)?;
let loaded_first = load_oauth_tokens_from_keyring(
&keyring_store,
AuthKeyringBackendKind::Secrets,
&first.server_name,
&first.url,
)?
.expect("first server tokens should remain stored");
let loaded_second = load_oauth_tokens_from_keyring(
&keyring_store,
AuthKeyringBackendKind::Secrets,
&second.server_name,
&second.url,
)?
.expect("second server tokens should be stored");
assert_tokens_match_without_expiry(&loaded_first, &first);
assert_tokens_match_without_expiry(&loaded_second, &second);
Ok(())
}
#[test]
fn secrets_store_load_and_delete_observe_aggregate_lock() -> Result<()> {
let env = TempCodexHome::new();
let keyring_store = MockKeyringStore::default();
let tokens = sample_tokens();
save_oauth_tokens_with_keyring(
&keyring_store,
AuthKeyringBackendKind::Secrets,
&tokens.server_name,
&tokens,
)?;
let store_for_load = keyring_store.clone();
let server_name = tokens.server_name.clone();
let url = tokens.url.clone();
let loaded = complete_after_store_lock_contention(
env.path(),
OAuthStore::Secrets,
|| Ok(()),
move || {
Ok(load_oauth_tokens_from_keyring(
&store_for_load,
AuthKeyringBackendKind::Secrets,
&server_name,
&url,
)?)
},
)?
.expect("encrypted credentials should remain readable after contention");
assert_tokens_match_without_expiry(&loaded, &tokens);
let store_for_delete = keyring_store.clone();
let server_name = tokens.server_name.clone();
let url = tokens.url.clone();
let removed = complete_after_store_lock_contention(
env.path(),
OAuthStore::Secrets,
|| Ok(()),
move || {
crate::oauth::delete_oauth_tokens_from_secrets_keyring(
&store_for_delete,
&server_name,
&url,
)
},
)?;
assert!(removed);
assert!(
load_oauth_tokens_from_keyring(
&keyring_store,
AuthKeyringBackendKind::Secrets,
&tokens.server_name,
&tokens.url,
)?
.is_none()
);
Ok(())
}

View File

@@ -0,0 +1,460 @@
//! Exercises emitted metrics through MCP storage policy and pinned-store operations.
use super::persistor_tests::authorization_manager_for;
use super::persistor_tests::test_context;
use super::*;
use codex_otel::auth_storage::AuthStorageOriginator;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
type MetricRecord = (String, u64, BTreeMap<String, String>);
#[test]
fn policy_and_pinned_operations_keep_distinct_outcomes_and_originator() -> Result<()> {
if isolated_process()? {
return Ok(());
}
let _env = TempCodexHome::new();
keyring::set_default_credential_builder(keyring::mock::default_credential_builder());
let metrics = test_metrics()?;
let store = MockKeyringStore::default();
let tokens = sample_tokens();
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
store.set_error(
&key,
KeyringError::PlatformFailure(std::io::Error::from(std::io::ErrorKind::Unsupported).into()),
);
save_oauth_tokens_with_keyring_with_fallback_to_file(
&store,
AuthKeyringBackendKind::Direct,
&tokens.server_name,
&tokens,
)?;
store.save(KEYRING_SERVICE, &key, &serde_json::to_string(&tokens)?)?;
let resolved = AuthStorageOriginator::from_client_name("codex_vscode")
.sync_scope(|| {
resolve_oauth_tokens_from_store_policy(
&store,
&tokens.server_name,
&tokens.url,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
)
})?
.unwrap();
let snapshot = StoredOAuthCredentialSnapshot::new(resolved.tokens, resolved.store);
store.set_error(
&key,
KeyringError::PlatformFailure(std::io::Error::from(std::io::ErrorKind::TimedOut).into()),
);
// Pinned operations retain the original Auto policy and client on another thread.
std::thread::scope(|scope| {
scope
.spawn(|| {
// The SDK mock is empty; this probe must emit exactly one pinned observation.
assert_eq!(
snapshot.reload(
&tokens.server_name,
&tokens.url,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
)?,
None
);
assert!(
resolved
.store
.save(&store, &tokens.server_name, &tokens)
.is_err()
);
Ok::<_, anyhow::Error>(())
})
.join()
.unwrap()
})?;
let mut expected = vec![
expected_metric(
/*count*/ 1,
&[
("operation", "save"),
("actual_store", "file"),
("secure_outcome", "error"),
("fallback_reason", "secure_error"),
("secure_error", "unsupported"),
("originator", "none"),
],
),
expected_metric(/*count*/ 1, &[]),
expected_metric(
/*count*/ 1,
&[
("storage_phase", "pinned"),
("secure_outcome", "not_found"),
("outcome", "not_found"),
],
),
expected_metric(
/*count*/ 1,
&[
("storage_phase", "pinned"),
("operation", "save"),
("secure_outcome", "error"),
("outcome", "error"),
("secure_error", "timeout"),
],
),
];
expected.sort();
assert_eq!(operation_metrics(&metrics)?, expected);
metrics.shutdown()?;
Ok(())
}
fn isolated_process() -> Result<bool> {
if std::env::var_os("CODEX_AUTH_STORAGE_TEST_CHILD").is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
std::thread::current().name().unwrap(),
"--nocapture",
])
.env("CODEX_AUTH_STORAGE_TEST_CHILD", "1")
.output()?;
assert!(
output.status.success(),
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return Ok(true);
}
Ok(false)
}
fn operation_metrics(metrics: &codex_otel::MetricsClient) -> Result<Vec<MetricRecord>> {
let snapshot = metrics.snapshot()?;
let mut actual = Vec::new();
for metric in snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
{
if matches!(
metric.name(),
"codex.auth_storage.operation" | "codex.auth_storage.refresh_persist"
) && let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data()
{
for point in sum.data_points() {
actual.push((
metric.name().to_string(),
point.value(),
point
.attributes()
.map(|a| (a.key.to_string(), a.value.to_string()))
.collect::<BTreeMap<_, _>>(),
));
}
}
}
actual.sort();
Ok(actual)
}
fn expected_metric(count: u64, tags: &[(&str, &str)]) -> MetricRecord {
let mut attributes = BTreeMap::from([
("credential_kind", "mcp"),
("store_mode", "auto"),
("selected_store", "direct_keyring"),
("actual_store", "direct_keyring"),
("operation", "load"),
("secure_outcome", "success"),
("outcome", "success"),
("fallback_reason", "none"),
("secure_error", "none"),
("storage_phase", "policy"),
("originator", "codex_vscode"),
]);
attributes.extend(tags.iter().copied());
(
if attributes["operation"] == "refresh_persist" {
"codex.auth_storage.refresh_persist"
} else {
"codex.auth_storage.operation"
}
.into(),
count,
attributes
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
)
}
fn test_metrics() -> Result<codex_otel::MetricsClient> {
Ok(codex_otel::install_global_metrics(
codex_otel::MetricsClient::new(
codex_otel::MetricsConfig::in_memory("test", "test", "1", Default::default())
.with_runtime_reader(),
)?,
))
}
#[test]
fn cleanup_failure_retains_policy_and_remains_best_effort() -> Result<()> {
if isolated_process()? {
return Ok(());
}
let _env = TempCodexHome::new();
let metrics = test_metrics()?;
let tokens = sample_tokens();
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
std::fs::write(fallback_file_path()?, "{")?;
let mut expected = Vec::new();
AuthStorageOriginator::from_client_name("codex_vscode").sync_scope(|| -> Result<()> {
for (mode, mode_tag) in [
(OAuthCredentialsStoreMode::Auto, "auto"),
(OAuthCredentialsStoreMode::Keyring, "keyring"),
] {
let store = MockKeyringStore::default();
save_oauth_tokens_with_keyring_and_cleanup_file(
&store,
mode,
AuthKeyringBackendKind::Direct,
&tokens.server_name,
&tokens,
)?;
assert_eq!(
store.saved_value(&key),
Some(serde_json::to_string(&tokens)?)
);
expected.push(expected_metric(
/*count*/ 1,
&[
("store_mode", mode_tag),
("operation", "cleanup"),
("actual_store", "file"),
("secure_outcome", "not_attempted"),
("outcome", "error"),
],
));
}
Ok(())
})?;
expected.sort();
assert_eq!(operation_metrics(&metrics)?, expected);
metrics.shutdown()?;
Ok(())
}
#[test]
fn lock_errors_retain_typed_categories_through_wrappers() -> Result<()> {
if isolated_process()? {
return Ok(());
}
let metrics = test_metrics()?;
let mut expected = Vec::new();
AuthStorageOriginator::from_client_name("codex_vscode").sync_scope(|| {
for (duration, category) in [
(Duration::ZERO, "locked"),
(Duration::from_secs(/*secs*/ 1), "timeout"),
] {
for wrapped in [false, true] {
let error = OAuthStoreLockFailure::Timeout {
store: OAuthStore::Secrets,
path: "private-lock-path".into(),
acquire_timeout: duration,
};
let error = if wrapped {
Error::from(OAuthKeyringLoadError::StoreLock(error)).context("private context")
} else {
Error::from(error)
};
let result: Result<Option<()>> = Err(error);
let mut observation = telemetry::policy(
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Secrets,
Operation::Load,
);
observation.record_load_attempt(Store::Secrets, &result);
telemetry::record_secure_error(
&mut observation,
result.as_ref().unwrap_err().as_ref(),
);
}
expected.push(expected_metric(
/*count*/ 2,
&[
("selected_store", "secrets"),
("actual_store", "secrets"),
("secure_outcome", "error"),
("outcome", "error"),
("secure_error", category),
],
));
}
});
expected.sort();
assert_eq!(operation_metrics(&metrics)?, expected);
metrics.shutdown()?;
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn coordinated_refresh_persistence_records_success_and_failure() -> Result<()> {
use rmcp::transport::auth::CredentialStore;
if isolated_process()? {
return Ok(());
}
let _env = TempCodexHome::new();
let metrics = test_metrics()?;
for fail_save in [false, true] {
let keyring = MockKeyringStore::default();
let tokens = sample_tokens();
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
keyring.save(KEYRING_SERVICE, &key, &serde_json::to_string(&tokens)?)?;
let resolved = AuthStorageOriginator::from_client_name("codex_vscode")
.sync_scope(|| {
resolve_oauth_tokens_from_store_policy(
&keyring,
&tokens.server_name,
&tokens.url,
OAuthCredentialsStoreMode::Auto,
AuthKeyringBackendKind::Direct,
)
})?
.unwrap();
let store = OAuthCredentialStore::new(
tokens,
resolved.store,
keyring.clone(),
/*oauth_config*/ None,
);
let _guard = store.acquire_transaction_guard().await?;
let mut credentials = store.load().await?.unwrap();
credentials
.token_response
.as_mut()
.unwrap()
.set_access_token(AccessToken::new("refreshed-access".into()));
if fail_save {
keyring.set_error(
&key,
KeyringError::PlatformFailure(
std::io::Error::from(std::io::ErrorKind::TimedOut).into(),
),
);
}
let _ = operation_metrics(&metrics)?;
assert_eq!(store.save(credentials).await.is_err(), fail_save);
let outcome = if fail_save { "error" } else { "success" };
let expected = ["save", "refresh_persist"].map(|operation| {
expected_metric(
/*count*/ 1,
&[
("operation", operation),
("storage_phase", "pinned"),
("secure_outcome", outcome),
("outcome", outcome),
("secure_error", if fail_save { "timeout" } else { "none" }),
],
)
});
assert_eq!(operation_metrics(&metrics)?, expected);
}
metrics.shutdown()?;
Ok(())
}
#[expect(
clippy::await_holding_invalid_type,
reason = "The legacy authorization manager serializes refresh through its Tokio mutex"
)]
#[tokio::test(flavor = "current_thread")]
async fn legacy_refresh_persistence_records_each_write_once() -> Result<()> {
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
if isolated_process()? {
return Ok(());
}
let metrics = test_metrics()?;
for proactive in [false, true] {
for fail_save in [false, true] {
let (_env, server, initial) = test_context().await?;
save_oauth_tokens_to_file(&initial)?;
let file = fallback_file_path()?;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(move |_: &wiremock::Request| {
if fail_save {
std::fs::write(&file, "{").unwrap();
}
ResponseTemplate::new(/*s*/ 200).set_body_json(serde_json::json!({
"access_token": "refreshed-access", "token_type": "Bearer",
"refresh_token": "rotated-refresh", "expires_in": 3600,
}))
})
.expect(1)
.mount(&server)
.await;
let manager = Arc::new(Mutex::new(authorization_manager_for(&initial).await?));
let authority = AuthStorageOriginator::from_client_name("codex_vscode")
.sync_scope(ResolvedOAuthCredentialStore::file);
let persistor = OAuthPersistor::new(
initial.server_name.clone(),
initial.url.clone(),
Arc::clone(&manager),
authority,
Some(initial),
/*oauth_config*/ None,
);
let result = if proactive {
persistor.refresh_if_needed().await
} else {
manager.lock().await.refresh_token().await?;
persistor.persist_if_needed().await
};
assert_eq!(result.is_err(), fail_save);
let mut expected = Vec::new();
for operation in if proactive {
vec!["load", "save", "refresh_persist"]
} else {
vec!["save", "refresh_persist"]
} {
expected.push(expected_metric(
/*count*/ 1,
&[
("operation", operation),
("store_mode", "file"),
("actual_store", "file"),
("storage_phase", "pinned"),
("secure_outcome", "not_attempted"),
(
"outcome",
if fail_save && operation != "load" {
"error"
} else {
"success"
},
),
],
));
}
expected.sort();
assert_eq!(operation_metrics(&metrics)?, expected);
if !fail_save {
// The proactive path installs the persisted response; the reactive path updates
// its snapshot. Neither should emit another milestone without another write.
persistor.persist_if_needed().await?;
assert_eq!(operation_metrics(&metrics)?, Vec::new());
}
server.verify().await;
}
}
metrics.shutdown()?;
Ok(())
}

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;

View File

@@ -0,0 +1,179 @@
//! Accepts a pasted OAuth redirect without navigating to it. The prepared callback address
//! is checked before the existing OAuth flow validates state/issuer and exchanges the code.
use super::CallbackResult;
use super::OAuthHttpContext;
use super::OAuthLoginPurpose;
use super::OAuthProviderError;
use super::OauthCallbackResult;
use super::OauthLoginFlow;
use crate::McpOAuthClientRegistration;
use crate::StreamableHttpRedirectMode;
use crate::save_oauth_tokens;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpServerOAuthConfig;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use tokio::time::timeout;
use url::Url;
/// Runs MCP OAuth without opening a browser, accepting either the HTTP callback or a
/// full redirect URL returned by `read_callback`. The reader receives the authorization
/// URL and must release terminal state when its future is dropped (callback or timeout).
#[allow(clippy::too_many_arguments)]
pub async fn perform_oauth_login_with_callback_input<F>(
server_name: &str,
server_url: &str,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
scopes: &[String],
oauth_config: Option<&McpServerOAuthConfig>,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
callback_port: Option<u16>,
callback_url: Option<&str>,
global_callback_url: Option<&str>,
http_client: Arc<dyn HttpClient>,
read_callback: impl FnOnce(String) -> F,
) -> Result<()>
where
F: Future<Output = Result<String>>,
{
let mut flow = OauthLoginFlow::new(
server_name,
server_url,
store_mode,
keyring_backend_kind,
OAuthHttpContext {
http_headers,
env_http_headers,
http_client,
redirect_mode: StreamableHttpRedirectMode::Legacy,
},
scopes,
oauth_config,
OAuthLoginPurpose::Mcp,
client_registration,
oauth_resource,
/*launch_browser*/ false,
callback_port,
callback_url,
global_callback_url,
/*timeout_secs*/ None,
)
.await?;
let authorization_url = flow.authorization_url();
let callback = timeout(flow.timeout, async {
tokio::select! {
callback = &mut flow.rx => callback.context("OAuth callback was cancelled"),
input = read_callback(authorization_url.clone()) => {
parse_callback_url(&input?, &flow.redirect_uri, &authorization_url)
}
}
})
.await
.context("timed out waiting for OAuth callback")??;
// RMCP's issuer-mismatch error includes the received value. Reject it here
// without echoing any part of a pasted callback into terminal diagnostics.
if let CallbackResult::Success(callback) = &callback
&& callback
.issuer
.as_deref()
.is_some_and(|issuer| Some(issuer) != flow.authorization_server_issuer.as_deref())
{
bail!("OAuth callback issuer does not match this login");
}
let stored = flow.complete_callback(callback).await?;
save_oauth_tokens(server_name, &stored, store_mode, keyring_backend_kind).await
}
fn parse_callback_url(
input: &str,
redirect_uri: &str,
authorization_url: &str,
) -> Result<CallbackResult> {
if input.len() > 64 * 1024 {
bail!("OAuth callback URL exceeds 64 KiB");
}
let mut callback = Url::parse(input.trim()).context("Invalid OAuth callback URL")?;
let mut expected = Url::parse(redirect_uri).context("Invalid OAuth redirect URI")?;
if callback.fragment().is_some()
|| !callback.username().is_empty()
|| callback.password().is_some()
{
bail!("OAuth callback URL must not contain credentials or a fragment");
}
let mut response_params: Vec<_> = callback.query_pairs().into_owned().collect();
// Configured redirect query parameters must survive unchanged. OAuth response
// parameters are appended by the authorization server, not part of that address.
let expected_params: Vec<_> = expected.query_pairs().into_owned().collect();
for expected_param in &expected_params {
let position = response_params
.iter()
.position(|param| param == expected_param)
.ok_or_else(|| {
anyhow!("OAuth callback URL does not match this login's redirect URI")
})?;
response_params.remove(position);
}
if response_params
.iter()
.any(|(name, _)| expected_params.iter().any(|(key, _)| key == name))
{
bail!("OAuth callback URL changes this login's redirect query parameters");
}
callback.set_query(/*query*/ None);
expected.set_query(/*query*/ None);
if callback != expected {
bail!("OAuth callback URL does not match this login's redirect URI");
}
let mut params = HashMap::new();
for (name, value) in response_params {
if params.insert(name, value).is_some() {
bail!("OAuth callback URL contains duplicate parameters");
}
}
let state = params
.remove("state")
.filter(|state| !state.is_empty())
.ok_or_else(|| anyhow!("OAuth callback URL is missing state"))?;
if params.contains_key("error") {
if params.contains_key("code") {
bail!("OAuth callback URL contains both a code and an error");
}
let authorization = Url::parse(authorization_url)?;
if !authorization
.query_pairs()
.any(|(key, value)| key == "state" && value == state)
{
bail!("OAuth callback state does not match this login");
}
// Do not print arbitrary pasted error descriptions or other callback values.
return Ok(CallbackResult::Error(OAuthProviderError::new(
/*error*/ None, /*error_description*/ None,
)));
}
let code = params
.remove("code")
.filter(|code| !code.is_empty())
.ok_or_else(|| anyhow!("OAuth callback URL is missing an authorization code"))?;
Ok(CallbackResult::Success(OauthCallbackResult {
code,
state,
issuer: params.remove("iss"),
}))
}
#[cfg(test)]
#[path = "oauth_callback_input_tests.rs"]
mod tests;

View File

@@ -0,0 +1,70 @@
//! Validates pasted callback addresses, parameter ambiguity, and redacted errors.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn pasted_callback_preserves_configured_query_and_decodes_response() {
let CallbackResult::Success(callback) = parse_callback_url(
" https://callback.example:9443/registered?tenant=a&code=a%2Bb&state=csrf&iss=https%3A%2F%2Fissuer.example ",
"https://callback.example:9443/registered?tenant=a",
"https://issuer.example/authorize?state=csrf",
)
.unwrap() else {
panic!("expected successful callback");
};
assert_eq!(
callback,
OauthCallbackResult {
code: "a+b".to_string(),
state: "csrf".to_string(),
issuer: Some("https://issuer.example".to_string()),
}
);
}
#[test]
fn pasted_callback_rejects_ambiguous_or_unbound_urls_without_echoing_values() {
let redirect = "http://127.0.0.1:1234/callback/server?tenant=a";
for input in [
"http://127.0.0.1:1234/other?tenant=a&code=secret&state=csrf",
"http://127.0.0.1:1235/callback/server?tenant=a&code=secret&state=csrf",
"http://127.0.0.1:1234/callback/server?tenant=b&code=secret&state=csrf",
"http://127.0.0.1:1234/callback/server?tenant=a&tenant=b&code=secret&state=csrf",
"http://127.0.0.1:1234/callback/server?tenant=a&code=secret&%63ode=second&state=csrf",
"http://127.0.0.1:1234/callback/server?tenant=a&code=secret&state=csrf&state=second",
"http://127.0.0.1:1234/callback/server?tenant=a&code=secret&state=csrf&iss=a&iss=b",
"http://secret@127.0.0.1:1234/callback/server?tenant=a&code=secret&state=csrf",
"http://127.0.0.1:1234/callback/server?tenant=a&code=secret&state=csrf#fragment",
"http://127.0.0.1:1234/callback/server?tenant=a&code=secret&state=",
"http://127.0.0.1:1234/callback/server?tenant=a&code=secret&state=csrf&error=denied",
] {
let error =
parse_callback_url(input, redirect, "https://issuer.example?state=csrf").unwrap_err();
assert!(!format!("{error:#}").contains("secret"));
}
assert!(parse_callback_url(&"x".repeat(/*n*/ 65_537), redirect, "").is_err());
}
#[test]
fn pasted_provider_error_requires_matching_state_and_redacts_description() {
let redirect = "http://127.0.0.1:1234/callback/server";
let input = format!("{redirect}?error=access_denied&error_description=secret&state=csrf");
let CallbackResult::Error(error) = parse_callback_url(
&input,
redirect,
"https://issuer.example/authorize?state=csrf",
)
.unwrap() else {
panic!("expected provider error");
};
assert_eq!(error.to_string(), "OAuth provider returned an error");
assert!(
parse_callback_url(
&input,
redirect,
"https://issuer.example/authorize?state=other",
)
.is_err()
);
}

View File

@@ -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
);
}
}

View File

@@ -0,0 +1,68 @@
//! Applies configured OAuth client secrets to login and refresh without persisting them.
//! A confidential client must never reuse tokens issued to a different client ID.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_config::McpServerOAuthConfig;
use oauth2::ClientSecret;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::auth::AuthError;
use rmcp::transport::auth::OAuthClientConfig;
#[derive(Debug, Default)]
pub(crate) struct OAuthClientCredentials {
pub(crate) client_id: Option<String>,
pub(crate) client_secret: Option<ClientSecret>,
}
impl OAuthClientCredentials {
pub(crate) fn resolve(config: Option<&McpServerOAuthConfig>) -> Result<Self> {
let client_id = config
.and_then(|config| config.client_id.clone())
.filter(|id| !id.trim().is_empty());
let client_secret = config
.and_then(|config| config.client_secret.as_ref())
.map(|secret| ClientSecret::new(secret.to_string()));
if client_secret.is_some() && client_id.is_none() {
bail!("MCP OAuth client_secret requires a nonempty client_id");
}
if client_secret
.as_ref()
.is_some_and(|secret| secret.secret().trim().is_empty())
{
bail!("MCP OAuth client_secret must not be empty");
}
Ok(Self {
client_id,
client_secret,
})
}
pub(crate) fn validate_stored_client_id(&self, stored_client_id: &str) -> Result<()> {
if self.client_secret.is_some() && self.client_id.as_deref() != Some(stored_client_id) {
return Err(AuthError::AuthorizationRequired).context(
"Configured MCP OAuth client ID differs from stored credentials; log in again",
);
}
Ok(())
}
pub(crate) fn configure_for_refresh(
&self,
manager: &mut AuthorizationManager,
server_url: &str,
stored_client_id: &str,
) -> Result<()> {
self.validate_stored_client_id(stored_client_id)?;
if let Some(secret) = &self.client_secret {
// Preserve the manager's application type, as configure_client_id does.
// Refresh does not send the redirect URI.
let mut config = OAuthClientConfig::new(stored_client_id, server_url)
.with_client_secret(secret.secret());
config.application_type = None;
manager.configure_client(config)?;
}
Ok(())
}
}

View File

@@ -0,0 +1,139 @@
use std::sync::Arc;
use anyhow::Result;
use anyhow::bail;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::AuthorizationRequest;
use rmcp::transport::AuthorizationSession;
use rmcp::transport::auth::OAuthHttpClient;
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)]
pub enum McpOAuthClientRegistration {
/// Prefer a supported native CIMD and otherwise use advertised DCR.
#[default]
Auto,
/// Require a ChatGPT-hosted Codex public native Client ID Metadata Document.
Cimd,
/// Require the authorization server's Dynamic Client Registration endpoint.
Dcr,
}
/// OAuth state prepared from one authorization-server metadata resolution.
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(
server_url: &str,
http_client: Arc<dyn OAuthHttpClient>,
scopes: &[&str],
redirect_uri: &str,
callback_id: &str,
client_registration: McpOAuthClientRegistration,
) -> Result<PreparedOAuthLogin> {
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)?;
let authorization_server_issuer = metadata.issuer.clone();
let callback_mode = callback_mode(&metadata)?;
let cimd_advertised = metadata
.additional_fields
.get("client_id_metadata_document_supported")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
let public_client_auth_supported = metadata
.additional_fields
.get("token_endpoint_auth_methods_supported")
.and_then(serde_json::Value::as_array)
.is_some_and(|methods| methods.iter().any(|method| method.as_str() == Some("none")));
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() == 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
let offer_cimd = match client_registration {
McpOAuthClientRegistration::Auto => {
cimd_advertised && native_redirect_supported && public_client_auth_supported
}
McpOAuthClientRegistration::Cimd => {
if !cimd_advertised || !public_client_auth_supported {
bail!(
"MCP authorization server does not advertise CIMD with token endpoint auth method `none`"
);
}
if !native_redirect_supported {
bail!(
"MCP OAuth CIMD requires an ephemeral loopback callback at `{expected_callback_path}`"
);
}
true
}
McpOAuthClientRegistration::Dcr => false,
};
auth_manager.set_metadata(metadata);
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/
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
.map_err(|(_auth_manager, error)| error)?;
Ok(PreparedOAuthLogin {
oauth_state: OAuthState::Session(session),
authorization_server_issuer,
redirect_uri,
})
}
#[cfg(test)]
#[path = "oauth_client_registration_tests.rs"]
mod tests;

View File

@@ -0,0 +1,571 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use http::HeaderMap;
use pretty_assertions::assert_eq;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthState;
use serde_json::Value;
use serde_json::json;
use url::Url;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::McpOAuthClientRegistration;
use super::start_authorization;
use crate::oauth::validate_authorization_server_endpoints;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::utils::MCP_USER_AGENT;
use crate::utils::build_default_headers;
const CALLBACK_ID: &str = "abc123ABC_-x";
async fn oauth_server(overrides: Value) -> MockServer {
let server = MockServer::start().await;
let base_url = server.uri();
let mut metadata = json!({
"authorization_endpoint": format!("{base_url}/authorize"),
"token_endpoint": format!("{base_url}/token"),
"registration_endpoint": format!("{base_url}/register"),
"client_id_metadata_document_supported": true,
"token_endpoint_auth_methods_supported": ["none"],
"code_challenge_methods_supported": ["S256"],
"scopes_supported": ["read", "offline_access"],
});
metadata
.as_object_mut()
.expect("metadata should be an object")
.extend(
overrides
.as_object()
.expect("overrides should be an object")
.clone(),
);
if metadata["authorization_response_iss_parameter_supported"] == json!(true)
&& metadata.get("issuer").is_none()
{
metadata["issuer"] = json!(format!("{base_url}/mcp"));
}
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(metadata))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(|request: &Request| {
let registration: Value = serde_json::from_slice(&request.body)
.expect("dynamic registration should contain JSON");
ResponseTemplate::new(200).set_body_json(json!({
"client_id": "dcr-client",
"redirect_uris": registration["redirect_uris"],
}))
})
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "test-access-token",
"token_type": "Bearer",
"refresh_token": "test-refresh-token",
})))
.mount(&server)
.await;
server
}
async fn requests_to(server: &MockServer, request_path: &str) -> Vec<Request> {
server
.received_requests()
.await
.expect("mock server should record requests")
.into_iter()
.filter(|request| request.url.path() == request_path)
.collect()
}
async fn authorization(
server: &MockServer,
redirect_uri: &str,
registration: McpOAuthClientRegistration,
) -> Result<(OAuthState, HashMap<String, String>)> {
let prepared = start_authorization(
&format!("{}/mcp", server.uri()),
Arc::new(OAuthHttpClientAdapter::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
HeaderMap::new(),
&format!("{}/mcp", server.uri()),
)),
&["read"],
redirect_uri,
CALLBACK_ID,
registration,
)
.await?;
let state = prepared.oauth_state;
let query = Url::parse(&state.get_authorization_url().await?)?
.query_pairs()
.into_owned()
.collect();
Ok((state, query))
}
#[tokio::test]
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?;
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"],
supports_issuer
.then(|| format!("{}/mcp", server.uri()))
.as_deref(),
)
.await?;
let token_requests = requests_to(&server, "/token").await;
assert_eq!(token_requests.len(), 1);
let request = &token_requests[0];
let body: HashMap<_, _> = url::form_urlencoded::parse(&request.body)
.into_owned()
.collect();
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"));
assert!(!request.headers.contains_key("authorization"));
assert!(requests_to(&server, "/register").await.is_empty());
assert_eq!(
requests_to(&server, "/.well-known/oauth-authorization-server/mcp")
.await
.len(),
1
);
}
Ok(())
}
#[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 [
(
json!({"client_id_metadata_document_supported": false}),
native,
McpOAuthClientRegistration::Auto,
native,
),
(
json!({"token_endpoint_auth_methods_supported": null}),
native,
McpOAuthClientRegistration::Auto,
native,
),
(
json!({"token_endpoint_auth_methods_supported": ["private_key_jwt"]}),
native,
McpOAuthClientRegistration::Auto,
native,
),
(json!({}), custom, McpOAuthClientRegistration::Auto, custom),
(
json!({"authorization_response_iss_parameter_supported": true}),
shared_native,
McpOAuthClientRegistration::Dcr,
shared_native,
),
] {
let server = oauth_server(metadata).await;
let (_, query) = authorization(&server, redirect, registration).await?;
assert_eq!(query["client_id"], "dcr-client");
assert_eq!(query["redirect_uri"], expected_redirect);
let registrations = requests_to(&server, "/register").await;
assert_eq!(registrations.len(), 1);
let registration: Value = serde_json::from_slice(&registrations[0].body)?;
assert_eq!(registration["redirect_uris"], json!([expected_redirect]));
}
Ok(())
}
#[test]
fn legacy_provider_exceptions_require_exact_issuer_and_endpoint_origins() -> Result<()> {
for (issuer, authorization_endpoint, token_endpoint, accepted) in [
(
"https://mcp.mercadopago.com/mcp",
"https://auth.mercadopago.com/mcp/authorization",
"https://mcp.mercadopago.com/oauth/token",
true,
),
(
"https://agent.robinhood.com/mcp/trading",
"https://robinhood.com/oauth",
"https://api.robinhood.com/oauth2/token/",
true,
),
(
"https://mcp.mercadopago.com.attacker.example/mcp",
"https://auth.mercadopago.com/mcp/authorization",
"https://mcp.mercadopago.com.attacker.example/oauth/token",
false,
),
(
"https://mcp.mercadopago.com/mcp",
"https://auth.mercadopago.com/mcp/authorization",
"https://attacker.example/token",
false,
),
(
"http://mcp.mercadopago.com/mcp",
"https://auth.mercadopago.com/mcp/authorization",
"http://mcp.mercadopago.com/oauth/token",
false,
),
(
"https://agent.robinhood.com/mcp/attacker",
"https://robinhood.com/oauth",
"https://api.robinhood.com/oauth2/token/",
false,
),
(
"https://agent.robinhood.com/mcp/trading",
"https://robinhood.com.attacker.example/oauth",
"https://api.robinhood.com/oauth2/token/",
false,
),
] {
let metadata: AuthorizationMetadata = serde_json::from_value(json!({
"issuer": issuer,
"authorization_endpoint": authorization_endpoint,
"token_endpoint": token_endpoint,
}))?;
assert_eq!(
validate_authorization_server_endpoints(&metadata).is_ok(),
accepted,
"unexpected validation result for issuer {issuer}",
);
}
Ok(())
}
#[tokio::test]
async fn verified_issuer_can_delegate_authorization_and_token_to_one_origin() -> Result<()> {
let issuer_server = MockServer::start().await;
let endpoint_server = MockServer::start().await;
let issuer = format!("{}/mcp", issuer_server.uri());
let redirect_uri = format!("http://127.0.0.1:43123/callback/{CALLBACK_ID}");
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": issuer,
"authorization_endpoint": format!("{}/authorize", endpoint_server.uri()),
"token_endpoint": format!("{}/token", endpoint_server.uri()),
"registration_endpoint": format!("{}/register", endpoint_server.uri()),
"token_endpoint_auth_methods_supported": ["none"],
"code_challenge_methods_supported": ["S256"],
})))
.expect(1)
.mount(&issuer_server)
.await;
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(|request: &Request| {
let registration: Value = serde_json::from_slice(&request.body)
.expect("dynamic registration should contain JSON");
ResponseTemplate::new(200).set_body_json(json!({
"client_id": "delegated-provider-client",
"redirect_uris": registration["redirect_uris"],
}))
})
.expect(1)
.mount(&endpoint_server)
.await;
Mock::given(method("POST"))
.and(path("/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "delegated-provider-token",
"token_type": "Bearer",
})))
.expect(1)
.mount(&endpoint_server)
.await;
let (mut state, query) = authorization(
&issuer_server,
&redirect_uri,
McpOAuthClientRegistration::Dcr,
)
.await?;
assert_eq!(query["client_id"], "delegated-provider-client");
assert_eq!(
Url::parse(&state.get_authorization_url().await?)?.origin(),
Url::parse(&endpoint_server.uri())?.origin(),
);
state
.handle_callback_with_issuer("valid-authorization-code", &query["state"], None)
.await?;
let token_requests = requests_to(&endpoint_server, "/token").await;
assert_eq!(token_requests.len(), 1);
assert!(
url::form_urlencoded::parse(&token_requests[0].body)
.any(|(name, _)| name == "code_verifier")
);
issuer_server.verify().await;
endpoint_server.verify().await;
Ok(())
}
#[tokio::test]
async fn resource_headers_follow_same_origin_registration_redirect_and_sdk_auth_wins() -> Result<()>
{
const RESOURCE_AUTHORIZATION: &str = "Bearer resource-only-secret";
const RESOURCE_API_KEY: &str = "resource-api-key-secret";
// These dummy OAuth credentials exist only in this test's local mock server.
const DUMMY_CLIENT_ID: &str = "dummy-test-client-id";
const DUMMY_CLIENT_SECRET: &str = "dummy-test-client-secret";
let sdk_authorization = format!(
"Basic {}",
STANDARD.encode(format!("{DUMMY_CLIENT_ID}:{DUMMY_CLIENT_SECRET}"))
);
let server = MockServer::start().await;
let authorization_server = MockServer::start().await;
let resource_url = format!("{}/mcp", server.uri());
let resource_metadata_url = format!("{}/resource-metadata", server.uri());
let redirect_uri = format!("http://127.0.0.1:43123/callback/{CALLBACK_ID}");
Mock::given(method("GET"))
.and(path("/mcp"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.respond_with(ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{resource_metadata_url}\""),
))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": resource_url,
"authorization_servers": [authorization_server.uri()],
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.and(header("user-agent", MCP_USER_AGENT))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": authorization_server.uri(),
"authorization_endpoint": format!("{}/authorize", authorization_server.uri()),
"token_endpoint": format!("{}/token", server.uri()),
"registration_endpoint": format!("{}/register", server.uri()),
"token_endpoint_auth_methods_supported": ["client_secret_basic"],
"code_challenge_methods_supported": ["S256"],
})))
.expect(1)
.mount(&authorization_server)
.await;
Mock::given(method("POST"))
.and(path("/register"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.and(header("content-type", "application/json"))
.respond_with(ResponseTemplate::new(307).insert_header("location", "/register/"))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/register/"))
.and(header("authorization", RESOURCE_AUTHORIZATION))
.and(header("x-api-key", RESOURCE_API_KEY))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
"client_id": DUMMY_CLIENT_ID,
"client_secret": DUMMY_CLIENT_SECRET,
"redirect_uris": [redirect_uri],
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/token"))
.and(header("authorization", sdk_authorization))
.and(header("x-api-key", RESOURCE_API_KEY))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "test-access-token",
"token_type": "Bearer",
})))
.expect(1)
.mount(&server)
.await;
let default_headers = build_default_headers(
Some(HashMap::from([
(
"Authorization".to_string(),
RESOURCE_AUTHORIZATION.to_string(),
),
("X-Api-Key".to_string(), RESOURCE_API_KEY.to_string()),
])),
/*env_http_headers*/ None,
)?;
let prepared = start_authorization(
&resource_url,
Arc::new(OAuthHttpClientAdapter::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
default_headers,
&resource_url,
)),
&[],
&redirect_uri,
CALLBACK_ID,
McpOAuthClientRegistration::Dcr,
)
.await?;
assert_eq!(
prepared.authorization_server_issuer.as_deref(),
Some(authorization_server.uri().as_str())
);
let mut state = prepared.oauth_state;
let csrf_state = Url::parse(&state.get_authorization_url().await?)?
.query_pairs()
.find(|(name, _)| name == "state")
.expect("authorization request should contain a CSRF state")
.1
.into_owned();
state
.handle_callback_with_issuer("valid-authorization-code", &csrf_state, None)
.await?;
let authorization_requests = authorization_server
.received_requests()
.await
.expect("authorization server should record requests");
assert_eq!(authorization_requests.len(), 1);
assert_eq!(authorization_requests[0].headers.get("authorization"), None);
assert_eq!(authorization_requests[0].headers.get("x-api-key"), None);
server.verify().await;
authorization_server.verify().await;
Ok(())
}
#[tokio::test]
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,
"token endpoint auth method `none`",
),
(
json!({}),
"http://127.0.0.1.evil.example:43123/callback/abc123ABC_-x",
"ephemeral loopback callback",
),
(
json!({}),
"http://127.0.0.1/callback/abc123ABC_-x",
"ephemeral loopback callback",
),
(
json!({}),
"http://127.0.0.1:43123/callback/wrong-id",
"ephemeral loopback callback",
),
(
json!({}),
"http://127.0.0.1:43123/callback/abc123ABC_-x?unexpected=true",
"ephemeral loopback callback",
),
(
json!({}),
"http://[::1]:43123/callback/abc123ABC_-x",
"ephemeral loopback callback",
),
] {
let server = oauth_server(metadata).await;
let error = authorization(&server, redirect, McpOAuthClientRegistration::Cimd)
.await
.err()
.expect("invalid CIMD metadata or callback should fail");
assert!(error.to_string().contains(expected_error));
assert!(requests_to(&server, "/register").await.is_empty());
assert!(requests_to(&server, "/token").await.is_empty());
}
let server = oauth_server(json!({"registration_endpoint": null})).await;
let error = authorization(&server, valid, McpOAuthClientRegistration::Dcr)
.await
.err()
.expect("explicit DCR should require an advertised registration endpoint");
assert!(error.to_string().contains("registration not supported"));
}

View File

@@ -0,0 +1,496 @@
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use http::StatusCode;
use http::header::AUTHORIZATION;
use http::header::CONTENT_ENCODING;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use http::header::LOCATION;
use http::header::TRANSFER_ENCODING;
use http::header::USER_AGENT;
use oauth2::HttpRequest;
use oauth2::HttpResponse;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthHttpClient;
use rmcp::transport::auth::OAuthHttpClientError;
use rmcp::transport::auth::OAuthHttpClientFuture;
use rmcp::transport::auth::OAuthHttpRedirectPolicy;
use rmcp::transport::auth::OAuthHttpRequest;
use url::Origin;
use url::Url;
use crate::auth_status::OAuthDiscoveryTimeout;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::utils::MCP_USER_AGENT;
const MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES: usize = 1024 * 1024;
const MAX_OAUTH_HTTP_REDIRECTS: usize = 10;
static NEXT_OAUTH_REQUEST_ID: AtomicU64 = AtomicU64::new(0);
tokio::task_local! {
/// Bounds provider HTTP work during preparation, excluding credential lock waits and saves.
pub(crate) static PROACTIVE_REFRESH_TIMEOUT: Duration;
}
#[derive(Debug, thiserror::Error)]
enum OAuthHttpClientAdapterError {
#[error("unsupported OAuth HTTP redirect policy")]
UnsupportedRedirectPolicy,
#[error("OAuth HTTP request timed out")]
TimedOut,
#[error("OAuth HTTP request exceeded {MAX_OAUTH_HTTP_REDIRECTS} redirects")]
TooManyRedirects,
#[error("OAuth HTTP response body exceeds {maximum_bytes} bytes")]
ResponseBodyTooLarge { maximum_bytes: usize },
#[error("OAuth authorization server issuer does not match authorization metadata origin")]
AuthorizationMetadataIssuerOriginMismatch,
}
fn oauth_http_client_error(
error: impl std::error::Error + Send + Sync + 'static,
) -> OAuthHttpClientError {
Box::new(error)
}
#[derive(Clone)]
pub(crate) struct OAuthHttpClientAdapter {
http_client: Arc<dyn HttpClient>,
default_headers: HeaderMap,
resource_origin: Origin,
timeout: OAuthDiscoveryTimeout,
has_configured_headers: bool,
redirect_mode: StreamableHttpRedirectMode,
}
impl OAuthHttpClientAdapter {
/// Recover only a candidate-local 503 without turning failed discovery into
/// missing metadata (which would enable RMCP's legacy endpoint fallback).
async fn execute_with_metadata_fallback(
&self,
request: HttpRequest,
redirect_policy: OAuthHttpRedirectPolicy,
timeout: Option<Duration>,
) -> Result<HttpResponse, OAuthHttpClientError> {
let issuer_path = request
.uri()
.path()
.strip_prefix("/.well-known/oauth-authorization-server")
.filter(|suffix| suffix.is_empty() || suffix.starts_with('/'));
let Some(issuer_path) = issuer_path.filter(|_| {
request.method() == Method::GET
&& matches!(redirect_policy, OAuthHttpRedirectPolicy::Stop)
}) else {
return self
.execute_request(request, redirect_policy, timeout)
.await;
};
let mut candidates = vec![format!("/.well-known/openid-configuration{issuer_path}")];
if !issuer_path.is_empty() {
candidates.push(format!("{issuer_path}/.well-known/openid-configuration"));
}
let mut candidate_url =
Url::parse(&request.uri().to_string()).map_err(oauth_http_client_error)?;
candidate_url.set_query(None);
candidate_url.set_fragment(None);
let operation = async {
let original = self
.execute_request(request.clone(), redirect_policy, timeout)
.await?;
if original.status() != StatusCode::SERVICE_UNAVAILABLE {
return Ok(original);
}
// These are the same issuer's OIDC candidates, in RMCP's discovery
// order. Reuse the adapter's header, origin and body-size checks.
// Do not follow redirects here: RMCP owns discovery redirect policy.
for path in candidates {
candidate_url.set_path(&path);
let mut candidate = request.clone();
*candidate.uri_mut() = candidate_url
.as_str()
.parse()
.map_err(oauth_http_client_error)?;
let response = self
.execute_request(candidate, OAuthHttpRedirectPolicy::Stop, timeout)
.await?;
match response.status() {
StatusCode::OK => {
if serde_json::from_slice::<AuthorizationMetadata>(response.body()).is_ok()
{
// RMCP still validates the exact expected issuer
// before using these endpoints or saved credentials.
return Ok(response);
}
}
StatusCode::NOT_FOUND
| StatusCode::METHOD_NOT_ALLOWED
| StatusCode::SERVICE_UNAVAILABLE => {}
StatusCode::REQUEST_TIMEOUT
| StatusCode::TOO_EARLY
| StatusCode::TOO_MANY_REQUESTS => return Ok(response),
status if status.is_server_error() => return Ok(response),
_ => return Ok(original),
}
}
Ok(original)
};
// Additional candidates share the original request's time budget.
let timeout = match self.timeout {
OAuthDiscoveryTimeout::Requested => timeout,
OAuthDiscoveryTimeout::Capped(cap) => {
Some(timeout.map_or(cap, |timeout| timeout.min(cap)))
}
};
match timeout {
Some(timeout) => tokio::time::timeout(timeout, operation)
.await
.map_err(|_| oauth_http_client_error(OAuthHttpClientAdapterError::TimedOut))?,
None => operation.await,
}
}
#[cfg(test)]
pub(crate) fn new(
http_client: Arc<dyn HttpClient>,
default_headers: HeaderMap,
resource_url: &str,
) -> Self {
Self::new_with_redirect_mode(
http_client,
default_headers,
resource_url,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)
.expect("OAuth resource URL should be valid")
}
pub(crate) fn new_with_redirect_mode(
http_client: Arc<dyn HttpClient>,
default_headers: HeaderMap,
resource_url: &str,
has_configured_headers: bool,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<Self, url::ParseError> {
Ok(Self {
http_client,
default_headers,
resource_origin: Url::parse(resource_url)?.origin(),
timeout: OAuthDiscoveryTimeout::Requested,
has_configured_headers,
redirect_mode,
})
}
pub(crate) fn new_with_max_timeout_and_redirect_mode(
http_client: Arc<dyn HttpClient>,
default_headers: HeaderMap,
resource_url: &str,
max_timeout: Duration,
has_configured_headers: bool,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<Self, url::ParseError> {
Ok(Self {
http_client,
default_headers,
resource_origin: Url::parse(resource_url)?.origin(),
timeout: OAuthDiscoveryTimeout::Capped(max_timeout),
has_configured_headers,
redirect_mode,
})
}
pub(crate) async fn execute_request(
&self,
request: HttpRequest,
redirect_policy: OAuthHttpRedirectPolicy,
timeout: Option<Duration>,
) -> Result<HttpResponse, OAuthHttpClientError> {
let redirect_policy = match redirect_policy {
OAuthHttpRedirectPolicy::Follow => HttpRedirectPolicy::Follow,
OAuthHttpRedirectPolicy::Stop => HttpRedirectPolicy::Stop,
_ => {
return Err(oauth_http_client_error(
OAuthHttpClientAdapterError::UnsupportedRedirectPolicy,
));
}
};
let (parts, body) = request.into_parts();
let mut request_url =
Url::parse(&parts.uri.to_string()).map_err(oauth_http_client_error)?;
let is_resource_origin = request_url.origin() == self.resource_origin;
let mut headers = if is_resource_origin {
self.default_headers.clone()
} else {
HeaderMap::new()
};
for name in parts.headers.keys() {
headers.remove(name);
}
let has_resource_only_headers = is_resource_origin
&& headers.iter().any(|(name, value)| {
name != USER_AGENT || value != HeaderValue::from_static(MCP_USER_AGENT)
});
headers.extend(parts.headers);
if !is_resource_origin {
headers.insert(USER_AGENT, HeaderValue::from_static(MCP_USER_AGENT));
}
let redirect_policy = oauth_redirect_policy(
self.redirect_mode,
&headers,
self.has_configured_headers,
redirect_policy,
);
// The executor can only follow every redirect or none, so replay credentialed
// requests ourselves after checking that each destination stays on the resource origin.
let follow_same_origin_redirects =
has_resource_only_headers && redirect_policy == HttpRedirectPolicy::Follow;
let headers = headers
.iter()
.map(|(name, value)| {
Ok(HttpHeader {
name: name.as_str().to_string(),
value: value.to_str().map_err(oauth_http_client_error)?.to_string(),
value_env_var: None,
})
})
.collect::<Result<Vec<_>, OAuthHttpClientError>>()?;
let timeout = match self.timeout {
OAuthDiscoveryTimeout::Requested => timeout,
OAuthDiscoveryTimeout::Capped(max_timeout) => {
Some(timeout.map_or(max_timeout, |timeout| timeout.min(max_timeout)))
}
};
let timeout_ms = timeout.map(|timeout| {
u64::try_from(timeout.as_millis())
.unwrap_or(u64::MAX)
.max(1)
});
let deadline = timeout.map(|timeout| Instant::now() + timeout);
let mut params = HttpRequestParams {
method: parts.method.to_string(),
url: parts.uri.to_string(),
headers,
body: (!body.is_empty()).then_some(body.into()),
timeout_ms,
redirect_policy: if follow_same_origin_redirects {
HttpRedirectPolicy::Stop
} else {
redirect_policy
},
request_id: String::new(),
stream_response: true,
};
let mut redirects = 0;
let (response, body) = loop {
let request_id = NEXT_OAUTH_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
params.request_id = format!("oauth-request-{request_id}");
let (response, mut body_stream) = self
.http_client
.http_request_stream(params.clone())
.await
.map_err(oauth_http_client_error)?;
let mut body = Vec::new();
while let Some(chunk) = body_stream.recv().await.map_err(oauth_http_client_error)? {
if chunk.len() > MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES - body.len() {
return Err(oauth_http_client_error(
OAuthHttpClientAdapterError::ResponseBodyTooLarge {
maximum_bytes: MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES,
},
));
}
body.extend_from_slice(&chunk);
}
let Ok(status) = StatusCode::from_u16(response.status) else {
break (response, body);
};
if !follow_same_origin_redirects
|| !matches!(
status,
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::SEE_OTHER
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT
)
{
break (response, body);
}
let Some(next_url) = response
.headers
.iter()
.find(|header| header.name.eq_ignore_ascii_case(LOCATION.as_str()))
.and_then(|header| request_url.join(&header.value).ok())
.filter(|url| url.origin() == self.resource_origin)
else {
break (response, body);
};
if redirects >= MAX_OAUTH_HTTP_REDIRECTS {
return Err(oauth_http_client_error(
OAuthHttpClientAdapterError::TooManyRedirects,
));
}
if status == StatusCode::SEE_OTHER
|| matches!(status, StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND)
&& params.method == Method::POST.as_str()
{
if params.method != Method::HEAD.as_str() {
params.method = Method::GET.to_string();
}
params.body = None;
params.headers.retain(|header| {
![
CONTENT_TYPE,
CONTENT_LENGTH,
CONTENT_ENCODING,
TRANSFER_ENCODING,
]
.iter()
.any(|name| header.name.eq_ignore_ascii_case(name.as_str()))
});
}
params.url = next_url.to_string();
if let Some(deadline) = deadline {
let remaining =
deadline
.checked_duration_since(Instant::now())
.ok_or_else(|| {
oauth_http_client_error(OAuthHttpClientAdapterError::TimedOut)
})?;
params.timeout_ms = Some(
u64::try_from(remaining.as_millis())
.unwrap_or(u64::MAX)
.max(1),
);
}
request_url = next_url;
redirects += 1;
};
if response.status == StatusCode::OK.as_u16()
&& let Ok(metadata) = serde_json::from_slice::<AuthorizationMetadata>(&body)
&& let Some(issuer) = metadata.issuer.as_deref()
&& Url::parse(issuer)
.map_err(oauth_http_client_error)?
.origin()
!= request_url.origin()
{
return Err(oauth_http_client_error(
OAuthHttpClientAdapterError::AuthorizationMetadataIssuerOriginMismatch,
));
}
let mut builder = oauth2::http::Response::builder().status(response.status);
for header in response.headers {
builder = builder.header(header.name, header.value);
}
builder.body(body).map_err(oauth_http_client_error)
}
}
fn oauth_redirect_policy(
mode: StreamableHttpRedirectMode,
headers: &HeaderMap,
has_configured_headers: bool,
requested_policy: HttpRedirectPolicy,
) -> HttpRedirectPolicy {
if mode == StreamableHttpRedirectMode::AgentPluginV1
&& (has_configured_headers || headers.contains_key(AUTHORIZATION))
{
HttpRedirectPolicy::Stop
} else {
requested_policy
}
}
impl OAuthHttpClient for OAuthHttpClientAdapter {
fn execute(&self, request: OAuthHttpRequest) -> OAuthHttpClientFuture<'_> {
Box::pin(async move {
let operation = self.execute_with_metadata_fallback(
request.request,
request.redirect_policy,
request.timeout,
);
match PROACTIVE_REFRESH_TIMEOUT.try_with(|duration| *duration) {
Ok(duration) => tokio::time::timeout(duration, operation)
.await
.map_err(|_| oauth_http_client_error(OAuthHttpClientAdapterError::TimedOut))?,
Err(_) => operation.await,
}
})
}
}
#[cfg(test)]
#[path = "oauth_http_client_security_tests.rs"]
mod security_tests;
#[cfg(test)]
mod tests {
use http::HeaderValue;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn agent_plugin_oauth_stops_only_for_sensitive_headers() {
assert_eq!(
policy(
StreamableHttpRedirectMode::AgentPluginV1,
/*has_configured_headers*/ true,
/*has_authorization*/ false,
),
HttpRedirectPolicy::Stop
);
assert_eq!(
policy(
StreamableHttpRedirectMode::AgentPluginV1,
/*has_configured_headers*/ false,
/*has_authorization*/ true,
),
HttpRedirectPolicy::Stop
);
assert_eq!(
policy(
StreamableHttpRedirectMode::AgentPluginV1,
/*has_configured_headers*/ false,
/*has_authorization*/ false,
),
HttpRedirectPolicy::Follow
);
assert_eq!(
policy(
StreamableHttpRedirectMode::Legacy,
/*has_configured_headers*/ true,
/*has_authorization*/ true,
),
HttpRedirectPolicy::Follow
);
}
fn policy(
mode: StreamableHttpRedirectMode,
has_configured_headers: bool,
has_authorization: bool,
) -> HttpRedirectPolicy {
let mut headers = HeaderMap::new();
if has_authorization {
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret"));
}
oauth_redirect_policy(
mode,
&headers,
has_configured_headers,
HttpRedirectPolicy::Follow,
)
}
}

View File

@@ -0,0 +1,463 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::transport::auth::AuthorizationManager;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthHttpRedirectPolicy;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES;
use super::OAuthHttpClientAdapter;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::utils::MCP_USER_AGENT;
use crate::utils::build_default_headers;
async fn metadata_manager(
resource: &MockServer,
authorization: &MockServer,
issuer_path: &str,
) -> Result<AuthorizationManager> {
let resource_url = format!("{}/mcp", resource.uri());
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!(
"Bearer resource_metadata=\"{}/resource-metadata\"",
resource.uri()
),
))
.mount(resource)
.await;
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": resource_url,
"authorization_servers": [format!("{}{issuer_path}", authorization.uri())]
})))
.mount(resource)
.await;
let adapter = OAuthHttpClientAdapter::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
build_default_headers(
Some(HashMap::from([(
"X-Api-Key".to_string(),
"resource-secret".to_string(),
)])),
/*env_http_headers*/ None,
)?,
&resource_url,
);
Ok(AuthorizationManager::new_with_oauth_http_client(resource_url, Arc::new(adapter)).await?)
}
#[tokio::test]
async fn oauth_metadata_503_falls_back_to_oidc() -> Result<()> {
for (issuer_path, first_oidc_response) in [
("", None),
("/adfs", Some(ResponseTemplate::new(404))),
("/adfs", Some(ResponseTemplate::new(405))),
("/adfs", Some(ResponseTemplate::new(503))),
(
"/adfs",
Some(ResponseTemplate::new(200).set_body_string("not metadata")),
),
] {
let resource = MockServer::start().await;
let authorization = MockServer::start().await;
let manager = metadata_manager(&resource, &authorization, issuer_path).await?;
let oauth_path = format!("/.well-known/oauth-authorization-server{issuer_path}");
let oidc_path = format!("{issuer_path}/.well-known/openid-configuration");
let metadata = json!({
"issuer": format!("{}{issuer_path}", authorization.uri()),
"authorization_endpoint": format!("{}/authorize", authorization.uri()),
"token_endpoint": format!("{}/token", authorization.uri())
});
Mock::given(method("GET"))
.and(path(oauth_path.clone()))
.respond_with(ResponseTemplate::new(503))
.expect(1)
.mount(&authorization)
.await;
if let Some(response) = first_oidc_response {
Mock::given(method("GET"))
.and(path(format!(
"/.well-known/openid-configuration{issuer_path}"
)))
.respond_with(response)
.expect(1)
.mount(&authorization)
.await;
}
Mock::given(method("GET"))
.and(path(oidc_path.clone()))
.respond_with(ResponseTemplate::new(200).set_body_json(&metadata))
.expect(1)
.mount(&authorization)
.await;
let resolved = manager.resolve_metadata().await?;
let expected: AuthorizationMetadata = serde_json::from_value(metadata)?;
assert_eq!(
serde_json::to_value(resolved.metadata)?,
serde_json::to_value(expected)?
);
let requests = authorization.received_requests().await.unwrap();
let mut expected_paths = vec![oauth_path];
if !issuer_path.is_empty() {
expected_paths.push(format!("/.well-known/openid-configuration{issuer_path}"));
}
expected_paths.push(oidc_path);
assert_eq!(
requests
.iter()
.map(|request| request.url.path().to_string())
.collect::<Vec<_>>(),
expected_paths
);
assert!(
requests
.iter()
.all(|request| !request.headers.contains_key("x-api-key"))
);
authorization.verify().await;
}
Ok(())
}
#[tokio::test]
async fn oauth_metadata_fallback_preserves_terminal_failures() -> Result<()> {
let resource = MockServer::start().await;
let authorization = MockServer::start().await;
let manager = metadata_manager(&resource, &authorization, "/adfs").await?;
let redirect_target = MockServer::start().await;
let wrong_issuer = json!({
"issuer": format!("{}/other-tenant", authorization.uri()),
"authorization_endpoint": format!("{}/authorize", authorization.uri()),
"token_endpoint": format!("{}/token", authorization.uri())
});
for (fallback, expected_error, request_count) in [
(ResponseTemplate::new(404), "503", 3),
(
ResponseTemplate::new(200).set_body_json(wrong_issuer),
"issuer mismatch",
2,
),
(
ResponseTemplate::new(307).insert_header("location", redirect_target.uri()),
"503",
2,
),
(ResponseTemplate::new(408), "408", 2),
(ResponseTemplate::new(425), "425", 2),
(ResponseTemplate::new(429), "429", 2),
(ResponseTemplate::new(500), "500", 2),
] {
authorization.reset().await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/adfs"))
.respond_with(ResponseTemplate::new(503))
.expect(1)
.mount(&authorization)
.await;
Mock::given(method("GET"))
.and(path("/.well-known/openid-configuration/adfs"))
.respond_with(fallback)
.expect(1)
.mount(&authorization)
.await;
let error = manager
.resolve_metadata()
.await
.expect_err("discovery must fail closed");
assert!(error.to_string().contains(expected_error), "{error}");
assert_eq!(
authorization.received_requests().await.unwrap().len(),
request_count
);
authorization.verify().await;
}
assert_eq!(redirect_target.received_requests().await.unwrap().len(), 0);
Ok(())
}
#[tokio::test]
async fn oauth_metadata_fallback_does_not_retry_other_requests_or_statuses() -> Result<()> {
for (verb, request_path, status) in [
("POST", "/.well-known/oauth-authorization-server/adfs", 503),
("GET", "/.well-known/oauth-protected-resource/mcp", 503),
("GET", "/.well-known/oauth-authorization-server-other", 503),
("GET", "/.well-known/oauth-authorization-server/adfs", 500),
] {
let server = MockServer::start().await;
Mock::given(method(verb))
.and(path(request_path))
.respond_with(ResponseTemplate::new(status))
.mount(&server)
.await;
let adapter = OAuthHttpClientAdapter::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
Default::default(),
&format!("{}/mcp", server.uri()),
);
let response = adapter
.execute_with_metadata_fallback(
oauth2::http::Request::builder()
.method(verb)
.uri(format!("{}{request_path}", server.uri()))
.body(Vec::new())?,
OAuthHttpRedirectPolicy::Stop,
Some(Duration::from_secs(/*secs*/ 5)),
)
.await
.map_err(|error| anyhow::anyhow!(error))?;
assert_eq!(response.status().as_u16(), status);
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}
Ok(())
}
struct DelayedMetadataHttpClient;
impl HttpClient for DelayedMetadataHttpClient {
fn http_request(
&self,
_params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
Box::pin(async { panic!("OAuth requests must stream responses") })
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
Box::pin(async move {
// Each response fits the per-request timeout. Only the shared
// deadline can prevent the fallback from finishing.
tokio::time::sleep(Duration::from_millis(/*millis*/ 100)).await;
Ok((
HttpRequestResponse {
status: if params.url.contains("oauth-authorization-server") {
503
} else {
404
},
headers: Vec::new(),
body: Vec::new().into(),
},
HttpResponseBodyStream::from_chunks(Vec::new()),
))
})
}
}
#[tokio::test]
async fn oauth_metadata_fallback_shares_the_original_timeout() -> Result<()> {
let adapter = OAuthHttpClientAdapter::new(
Arc::new(DelayedMetadataHttpClient),
Default::default(),
"https://resource.example/mcp",
);
let error = adapter
.execute_with_metadata_fallback(
oauth2::http::Request::builder()
.method("GET")
.uri("https://issuer.example/.well-known/oauth-authorization-server/adfs")
.body(Vec::new())?,
OAuthHttpRedirectPolicy::Stop,
Some(Duration::from_millis(/*millis*/ 150)),
)
.await
.expect_err("fallback requests must share the original deadline");
assert!(error.to_string().contains("timed out"), "{error}");
Ok(())
}
#[tokio::test]
async fn oauth_registration_redirects_never_forward_resource_only_headers() -> Result<()> {
const RESOURCE_API_KEY: &str = "resource-api-key-secret";
const RESOURCE_USER_AGENT: &str = "resource-only-user-agent";
for (redirect_mode, has_resource_only_headers) in [
(StreamableHttpRedirectMode::Legacy, true),
(StreamableHttpRedirectMode::AgentPluginV1, true),
(StreamableHttpRedirectMode::Legacy, false),
] {
let resource_server = MockServer::start().await;
let redirect_target = MockServer::start().await;
let resource_url = format!("{}/mcp", resource_server.uri());
Mock::given(method("POST"))
.and(path("/register"))
.and(header("content-type", "application/json"))
.and(header(
"user-agent",
if has_resource_only_headers {
RESOURCE_USER_AGENT
} else {
MCP_USER_AGENT
},
))
.respond_with(ResponseTemplate::new(307).insert_header(
"location",
format!("{}/redirected-register", redirect_target.uri()),
))
.expect(1)
.mount(&resource_server)
.await;
Mock::given(method("POST"))
.and(path("/redirected-register"))
.and(header("content-type", "application/json"))
.and(header("user-agent", MCP_USER_AGENT))
.respond_with(ResponseTemplate::new(201))
.expect(u64::from(!has_resource_only_headers))
.mount(&redirect_target)
.await;
let configured_headers = if has_resource_only_headers {
HashMap::from([
("X-Api-Key".to_string(), RESOURCE_API_KEY.to_string()),
("User-Agent".to_string(), RESOURCE_USER_AGENT.to_string()),
])
} else {
HashMap::from([(
"Content-Type".to_string(),
"resource-only-content-type".to_string(),
)])
};
let adapter = OAuthHttpClientAdapter::new_with_redirect_mode(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
build_default_headers(Some(configured_headers), /*env_http_headers*/ None)?,
&resource_url,
/*has_configured_headers*/ true,
redirect_mode,
)?;
let response = adapter
.execute_request(
oauth2::http::Request::builder()
.method("POST")
.uri(format!("{}/register", resource_server.uri()))
.header("content-type", "application/json")
.body(br#"{"client_name":"Codex"}"#.to_vec())?,
OAuthHttpRedirectPolicy::Follow,
/*timeout*/ None,
)
.await
.map_err(|error| anyhow::anyhow!(error))?;
assert_eq!(
response.status(),
if has_resource_only_headers {
oauth2::http::StatusCode::TEMPORARY_REDIRECT
} else {
oauth2::http::StatusCode::CREATED
}
);
resource_server.verify().await;
redirect_target.verify().await;
}
Ok(())
}
#[tokio::test]
async fn same_origin_redirects_preserve_timeout_and_response_body_limits() -> Result<()> {
let http_client: Arc<dyn codex_exec_server::HttpClient> = Arc::new(RouteAwareHttpClient::new(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
));
crate::oauth::test_support::warm_http_client(http_client.as_ref()).await?;
for oversized_redirect_body in [false, true] {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/warmup"))
.respond_with(ResponseTemplate::new(204))
.expect(1)
.mount(&server)
.await;
let resource_url = format!("{}/mcp", server.uri());
let redirect = ResponseTemplate::new(307).insert_header("location", "/register/");
let redirect = if oversized_redirect_body {
redirect.set_body_bytes(vec![0; MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES + 1])
} else {
redirect.set_delay(Duration::from_millis(/*millis*/ 400))
};
Mock::given(method("POST"))
.and(path("/register"))
.respond_with(redirect)
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/register/"))
.respond_with(
ResponseTemplate::new(201).set_delay(Duration::from_millis(/*millis*/ 400)),
)
.expect(u64::from(!oversized_redirect_body))
.mount(&server)
.await;
let adapter = OAuthHttpClientAdapter::new(
Arc::clone(&http_client),
build_default_headers(
Some(HashMap::from([(
"X-Api-Key".to_string(),
"resource-api-key-secret".to_string(),
)])),
/*env_http_headers*/ None,
)?,
&resource_url,
);
// Measure redirect handling after lazy native HTTP client initialization.
adapter
.execute_request(
oauth2::http::Request::builder()
.uri(format!("{}/warmup", server.uri()))
.body(Vec::new())?,
OAuthHttpRedirectPolicy::Stop,
/*timeout*/ None,
)
.await
.expect("HTTP client warmup should succeed");
let error = adapter
.execute_request(
oauth2::http::Request::builder()
.method("POST")
.uri(format!("{}/register", server.uri()))
.body(Vec::new())?,
OAuthHttpRedirectPolicy::Follow,
(!oversized_redirect_body).then_some(Duration::from_millis(/*millis*/ 700)),
)
.await
.expect_err("redirects must preserve request timeout and response body limits");
if oversized_redirect_body {
assert!(error.to_string().contains("exceeds"));
}
server.verify().await;
}
Ok(())
}

View File

@@ -0,0 +1,11 @@
//! Selects the owner of MCP OAuth refresh and credential persistence.
/// MCP OAuth policy pinned for the lifetime of a connection.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum McpOAuthRefreshMode {
/// Keep Codex's existing refresh and persistence path.
#[default]
Legacy,
/// Let RMCP coordinate refresh through Codex's credential store.
Coordinated,
}

View File

@@ -0,0 +1,65 @@
//! Preserve byte-stream message order even when rmcp polls send futures out of order.
//! Only wrap transports whose send completes after writing, without awaiting a response.
use std::future::Future;
use std::io;
use std::sync::Arc;
use futures::FutureExt;
use rmcp::RoleClient;
use rmcp::service::RxJsonRpcMessage;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::Transport;
use tokio::sync::Semaphore;
pub(crate) struct OrderedByteTransport<T> {
inner: T,
writes: Arc<Semaphore>,
}
impl<T> OrderedByteTransport<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner,
writes: Arc::new(Semaphore::new(1)),
}
}
}
impl<T: Transport<RoleClient, Error = io::Error>> Transport<RoleClient>
for OrderedByteTransport<T>
{
type Error = io::Error;
fn send(
&mut self,
item: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
// Reserve FIFO order now, before rmcp independently schedules each send.
// Ignore cooperative budgeting for this one poll so it always queues.
let mut acquire = Box::pin(Arc::clone(&self.writes).acquire_owned());
let acquired = tokio::task::unconstrained(acquire.as_mut()).now_or_never();
let send = self.inner.send(item);
async move {
let _permit = match acquired {
Some(result) => result,
None => acquire.await,
}
.map_err(io::Error::other)?;
// Serialize only writes, never the corresponding tool responses.
send.await
}
}
async fn receive(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
self.inner.receive().await
}
async fn close(&mut self) -> Result<(), Self::Error> {
self.inner.close().await
}
}
#[cfg(test)]
#[path = "ordered_byte_transport_tests.rs"]
mod tests;

View File

@@ -0,0 +1,58 @@
//! Exercise write ordering independently of rmcp's send-task scheduling.
use super::OrderedByteTransport;
use rmcp::RoleClient;
use rmcp::RoleServer;
use rmcp::model::CallToolRequest;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CancelledNotification;
use rmcp::model::CancelledNotificationParam;
use rmcp::model::ClientJsonRpcMessage;
use rmcp::model::ClientNotification;
use rmcp::model::ClientRequest;
use rmcp::model::RequestId;
use rmcp::transport::IntoTransport;
use rmcp::transport::Transport;
use std::time::Duration;
use tokio::time::timeout;
#[tokio::test]
async fn cancellation_cannot_overtake_request() -> anyhow::Result<()> {
let (client_io, server_io) = tokio::io::duplex(/*max_buf_size*/ 4096);
let mut client =
OrderedByteTransport::new(IntoTransport::<RoleClient, _, _>::into_transport(client_io));
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_io);
let request = ClientJsonRpcMessage::request(
ClientRequest::CallToolRequest(CallToolRequest::new(CallToolRequestParams::new("wait"))),
RequestId::Number(1),
);
let cancellation = ClientJsonRpcMessage::notification(
ClientNotification::CancelledNotification(CancelledNotification::new(
CancelledNotificationParam::new(Some(RequestId::Number(1)), None),
)),
);
// Exhaust the task budget: reserving write order must still happen synchronously.
while tokio::task::coop::has_budget_remaining() {
tokio::task::consume_budget().await;
}
let first = client.send(request.clone());
let discarded = client.send(request.clone());
let mut second = Box::pin(client.send(cancellation.clone()));
tokio::task::yield_now().await;
assert!(futures::poll!(second.as_mut()).is_pending());
drop(discarded);
assert!(futures::poll!(second.as_mut()).is_pending());
timeout(Duration::from_secs(5), first).await??;
timeout(Duration::from_secs(5), second).await??;
let received = [
timeout(Duration::from_secs(5), server.receive()).await?,
timeout(Duration::from_secs(5), server.receive()).await?,
];
pretty_assertions::assert_eq!(
serde_json::to_value(received)?,
serde_json::to_value([Some(request), Some(cancellation)])?
);
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,238 @@
//! Platform-specific program resolution for MCP server execution.
//!
//! This module provides a unified interface for resolving executable paths
//! across different operating systems. The key challenge it addresses is that
//! Windows cannot execute script files (e.g., `.cmd`, `.bat`) directly through
//! `Command::new()` without their file extensions, while Unix systems handle
//! scripts natively through shebangs.
//!
//! The `resolve` function abstracts these platform differences:
//! - On Unix: Returns the program unchanged (OS handles script execution)
//! - On Windows: Uses the `which` crate to resolve full paths including extensions
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::Path;
/// Resolves a program to its executable path on Unix systems.
///
/// Unix systems handle PATH resolution and script execution natively through
/// the kernel's shebang (`#!`) mechanism, so this function simply returns
/// the program name unchanged.
#[cfg(unix)]
pub fn resolve(
program: OsString,
_env: &HashMap<OsString, OsString>,
_cwd: &Path,
) -> std::io::Result<OsString> {
Ok(program)
}
/// Resolves a program to its executable path on Windows systems.
///
/// Windows requires explicit file extensions for script execution. This function
/// uses the `which` crate to search the `PATH` environment variable and find
/// the full path to the executable, including necessary script extensions
/// (`.cmd`, `.bat`, etc.) defined in `PATHEXT`.
///
/// This enables tools like `npx`, `pnpm`, and `yarn` to work correctly on Windows
/// without requiring users to specify full paths or extensions in their configuration.
#[cfg(windows)]
pub fn resolve(
program: OsString,
env: &HashMap<OsString, OsString>,
cwd: &Path,
) -> std::io::Result<OsString> {
// Extract PATH from environment for search locations
let search_path = env.iter().find_map(|(name, value)| {
name.to_string_lossy()
.eq_ignore_ascii_case("PATH")
.then_some(value)
});
// Attempt resolution via which crate
match which::which_in(&program, search_path, cwd) {
Ok(resolved) => {
tracing::debug!("Resolved {program:?} to {resolved:?}");
Ok(resolved.into_os_string())
}
Err(e) => {
tracing::debug!("Failed to resolve {program:?}: {e}. Using original path");
// Fallback to original program - let Command::new() handle the error
Ok(program)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::create_env_for_mcp_server;
use anyhow::Result;
#[cfg(windows)]
use std::fs;
use std::path::Path;
use tempfile::TempDir;
use tokio::process::Command;
/// Unix: Verifies the OS handles script execution without file extensions.
#[cfg(unix)]
#[tokio::test]
async fn test_unix_executes_script_without_extension() -> Result<()> {
let env = TestExecutableEnv::new()?;
let output = Command::new(&env.program_name)
.envs(&env.mcp_env)
.output()
.await;
assert!(
output.is_ok(),
"Unix should execute PATH-resolved scripts directly: {output:?}"
);
Ok(())
}
/// Windows: Verifies scripts fail to execute without the proper extension.
#[cfg(windows)]
#[tokio::test]
async fn test_windows_fails_without_extension() -> Result<()> {
let env = TestExecutableEnv::new()?;
let mut cmd = Command::new(&env.program_name);
cmd.envs(&env.mcp_env);
let output = cmd.output().await;
assert!(
output.is_err(),
"Windows requires .cmd/.bat extension for direct execution"
);
Ok(())
}
/// Windows: Verifies scripts with an explicit extension execute correctly.
#[cfg(windows)]
#[tokio::test]
async fn test_windows_succeeds_with_extension() -> Result<()> {
let env = TestExecutableEnv::new()?;
// Append the `.cmd` extension to the program name
let program_with_ext = format!("{}.cmd", env.program_name);
let mut cmd = Command::new(&program_with_ext);
cmd.envs(&env.mcp_env);
let output = cmd.output().await;
assert!(
output.is_ok(),
"Windows should execute scripts when the extension is provided"
);
Ok(())
}
/// Verifies program resolution enables successful execution on all platforms.
#[tokio::test]
async fn test_resolved_program_executes_successfully() -> Result<()> {
let env = TestExecutableEnv::new()?;
#[cfg(windows)]
let env = {
let mut env = env;
let path = env
.mcp_env
.remove(std::ffi::OsStr::new("PATH"))
.expect("test environment should include PATH");
env.mcp_env.insert(OsString::from("Path"), path);
env
};
let program = OsString::from(&env.program_name);
// Apply platform-specific resolution
let resolved = resolve(program, &env.mcp_env, std::env::current_dir()?.as_path())?;
// Verify resolved path executes successfully
let mut cmd = Command::new(resolved);
cmd.envs(&env.mcp_env);
let output = cmd.output().await;
assert!(
output.is_ok(),
"Resolved program should execute successfully"
);
Ok(())
}
// Test fixture for creating temporary executables in a controlled environment.
struct TestExecutableEnv {
// Held to prevent the temporary directory from being deleted.
_temp_dir: TempDir,
program_name: String,
mcp_env: HashMap<OsString, OsString>,
}
impl TestExecutableEnv {
const TEST_PROGRAM: &'static str = "test_mcp_server";
fn new() -> Result<Self> {
let temp_dir = TempDir::new()?;
let dir_path = temp_dir.path();
Self::create_executable(dir_path)?;
// Build a clean environment with the temp dir in the PATH.
let mut extra_env = HashMap::new();
extra_env.insert(OsString::from("PATH"), Self::build_path_env_var(dir_path));
#[cfg(windows)]
extra_env.insert(OsString::from("PATHEXT"), Self::ensure_cmd_extension());
let mcp_env = create_env_for_mcp_server(Some(extra_env), &[])?;
Ok(Self {
_temp_dir: temp_dir,
program_name: Self::TEST_PROGRAM.to_string(),
mcp_env,
})
}
/// Creates a simple, platform-specific executable script.
fn create_executable(dir: &Path) -> Result<()> {
#[cfg(windows)]
{
let file = dir.join(format!("{}.cmd", Self::TEST_PROGRAM));
fs::write(&file, "@echo off\nexit 0")?;
}
#[cfg(unix)]
{
let file = dir.join(Self::TEST_PROGRAM);
codex_utils_cargo_bin::write_executable(&file, "#!/bin/sh\nexit 0")?;
}
Ok(())
}
/// Prepends the given directory to the system's PATH variable.
fn build_path_env_var(dir: &Path) -> OsString {
let mut path = OsString::from(dir.as_os_str());
if let Some(current) = std::env::var_os("PATH") {
let sep = if cfg!(windows) { ";" } else { ":" };
path.push(sep);
path.push(current);
}
path
}
/// Ensures `.CMD` is in the `PATHEXT` variable on Windows for script discovery.
#[cfg(windows)]
fn ensure_cmd_extension() -> OsString {
let current = std::env::var_os("PATHEXT").unwrap_or_default();
if current
.to_string_lossy()
.to_ascii_uppercase()
.contains(".CMD")
{
current
} else {
let mut path_ext = OsString::from(".CMD;");
path_ext.push(current);
path_ext
}
}
}
}

View File

@@ -0,0 +1,130 @@
use std::ffi::OsStr;
use std::io;
use rmcp::model::ProtocolVersion;
use rmcp::service::ClientLifecycleMode;
/// MCP compatibility policy selected once when a Codex session is created.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum McpProtocolMode {
/// Preserve the existing MCP initialization and OAuth behavior.
#[default]
Legacy,
/// Allow the MCP 2026-07-28 discovery and request lifecycle.
V20260728,
/// Probe an eligible local stdio server even when its launch config omits a version.
DiscoverLocalStdio,
}
impl McpProtocolMode {
/// Returns the newest protocol version this compatibility policy can use.
pub fn preferred_protocol_version(self) -> ProtocolVersion {
match self {
Self::Legacy => ProtocolVersion::V_2025_06_18,
Self::V20260728 | Self::DiscoverLocalStdio => ProtocolVersion::V_2026_07_28,
}
}
pub(crate) fn client_lifecycle(self) -> ClientLifecycleMode {
match self {
Self::Legacy => ClientLifecycleMode::Initialize,
Self::V20260728 | Self::DiscoverLocalStdio => ClientLifecycleMode::Auto {
preferred_versions: vec![ProtocolVersion::V_2026_07_28],
legacy_version: Some(ProtocolVersion::V_2025_06_18),
},
}
}
/// Selects the stdio handshake from the client policy and the server's declared version.
pub fn stdio_mode(self, requested_version: Option<&OsStr>) -> io::Result<Self> {
match (self, requested_version) {
(Self::Legacy, _) => Ok(Self::Legacy),
(Self::DiscoverLocalStdio, None) => Ok(Self::DiscoverLocalStdio),
(Self::V20260728, None) => Ok(Self::Legacy),
(_, Some(version)) if version == OsStr::new("2026-07-28") => Ok(Self::V20260728),
(_, Some(version)) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"unsupported CODEX_MCP_PROTOCOL_VERSION `{}` for stdio MCP server; expected `2026-07-28`",
version.to_string_lossy()
),
)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn protocol_modes_select_compatible_sdk_lifecycles() {
assert_eq!(
McpProtocolMode::Legacy.preferred_protocol_version(),
ProtocolVersion::V_2025_06_18
);
assert_eq!(
McpProtocolMode::Legacy.client_lifecycle(),
ClientLifecycleMode::Initialize
);
assert_eq!(
McpProtocolMode::V20260728.preferred_protocol_version(),
ProtocolVersion::V_2026_07_28
);
assert_eq!(
McpProtocolMode::V20260728.client_lifecycle(),
ClientLifecycleMode::Auto {
preferred_versions: vec![ProtocolVersion::V_2026_07_28],
legacy_version: Some(ProtocolVersion::V_2025_06_18),
}
);
}
#[test]
fn stdio_requires_both_the_modern_feature_and_a_server_opt_in() {
let modern_version = Some(OsStr::new("2026-07-28"));
assert_eq!(
McpProtocolMode::Legacy
.stdio_mode(/*requested_version*/ None)
.unwrap(),
McpProtocolMode::Legacy
);
assert_eq!(
McpProtocolMode::Legacy.stdio_mode(modern_version).unwrap(),
McpProtocolMode::Legacy
);
assert_eq!(
McpProtocolMode::V20260728
.stdio_mode(/*requested_version*/ None)
.unwrap(),
McpProtocolMode::Legacy
);
assert_eq!(
McpProtocolMode::V20260728
.stdio_mode(modern_version)
.unwrap(),
McpProtocolMode::V20260728
);
}
#[test]
fn stdio_rejects_unknown_protocol_markers() {
let error = McpProtocolMode::V20260728
.stdio_mode(Some(OsStr::new("1999-01-01")))
.expect_err("an unknown protocol marker must fail");
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
assert!(error.to_string().contains("1999-01-01"));
}
#[test]
fn legacy_stdio_does_not_interpret_existing_protocol_markers() {
assert_eq!(
McpProtocolMode::Legacy
.stdio_mode(Some(OsStr::new("1999-01-01")))
.unwrap(),
McpProtocolMode::Legacy
);
}
}

View File

@@ -0,0 +1,131 @@
//! Cancel remote MCP work when its local response future is dropped.
use std::future::Future;
use rmcp::Peer;
use rmcp::RoleClient;
use rmcp::model::CancelledNotificationParam;
use rmcp::model::ClientRequest;
use rmcp::model::RequestId;
use rmcp::model::ServerResult;
use rmcp::service::PeerRequestOptions;
use rmcp::service::ServiceError;
use tokio::runtime::Handle;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
tokio::task_local! {
static REQUEST_SCOPE: RequestScope;
}
/// Tracks cancellation writes for one chat's requests on a shared stdio transport.
#[derive(Clone)]
pub struct RequestScope {
runtime: Handle,
cancellation: CancellationToken,
pending: TaskTracker,
}
impl RequestScope {
pub fn new(runtime: Handle, cancellation: CancellationToken) -> Self {
Self {
runtime,
cancellation,
pending: TaskTracker::new(),
}
}
async fn send(
&self,
peer: Peer<RoleClient>,
request: ClientRequest,
options: PeerRequestOptions,
) -> Result<ServerResult, ServiceError> {
let cancellation = self.cancellation.child_token();
let _cancel_on_drop = cancellation.clone().drop_guard();
// The transport must make progress even if the caller stops polling its future.
// Register before the task checks cancellation so a racing release observes it.
let send = async move {
let handle = tokio::select! {
biased;
() = cancellation.cancelled() => return Err(ServiceError::Cancelled { reason: None }),
result = peer.send_request_with_option(request, options) => result?,
};
let id = handle.id.clone();
tokio::select! {
biased;
result = handle.await_response() => result,
() = cancellation.cancelled() => {
notify_cancelled(peer, id).await;
Err(ServiceError::Cancelled { reason: None })
}
}
};
self.pending
.spawn_on(send, &self.runtime)
.await
.map_err(|_| ServiceError::TransportClosed)?
}
/// Include every wire request made by this operation, including MCP continuations.
pub async fn scope<F: Future>(&self, operation: F) -> F::Output {
REQUEST_SCOPE.scope(self.clone(), operation).await
}
/// Stop admitting requests and wait for the transport to finish writing their cancellations.
pub async fn cancel_and_wait(&self) {
self.cancellation.cancel();
self.pending.close();
self.pending.wait().await;
}
}
/// Whether dropping a caller's future should cancel its request on the peer.
#[derive(Clone, Copy)]
pub(crate) enum RequestCancellation {
Disabled,
OnDrop,
}
impl RequestCancellation {
/// Send a request and tie its remote lifetime to the caller when requested.
pub(crate) async fn send(
self,
peer: &Peer<RoleClient>,
request: ClientRequest,
options: PeerRequestOptions,
) -> Result<ServerResult, ServiceError> {
if let Ok(scope) = REQUEST_SCOPE.try_with(Clone::clone) {
return scope.send(peer.clone(), request, options).await;
}
let handle = peer.send_request_with_option(request, options).await?;
let mut cancellation = CancelOnDrop(match self {
Self::Disabled => None,
Self::OnDrop => Some((peer.clone(), handle.id.clone())),
});
let result = handle.await_response().await;
cancellation.0 = None;
result
}
}
struct CancelOnDrop(Option<(Peer<RoleClient>, RequestId)>);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
if let Some((peer, id)) = self.0.take()
&& let Ok(runtime) = tokio::runtime::Handle::try_current()
{
runtime.spawn(notify_cancelled(peer, id));
}
}
}
async fn notify_cancelled(peer: Peer<RoleClient>, id: RequestId) {
let _ = peer
.notify_cancelled(CancelledNotificationParam::new(
Some(id),
Some("MCP request cancelled by caller".into()),
))
.await;
}

View File

@@ -0,0 +1,258 @@
//! Drives modern request continuations, including the native verification extension.
//! Inputs use the caller's client service; proofs never bypass its validation.
//! Session recovery cannot replay a submitted proof; connection closure drops pending inputs.
use std::collections::BTreeMap;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use rmcp::RoleClient;
use rmcp::model::CallToolRequest;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CallToolResult;
use rmcp::model::ClientRequest;
use rmcp::model::DEFAULT_MRTR_MAX_ROUNDS;
use rmcp::model::GetExtensions;
use rmcp::model::GetMeta;
use rmcp::model::InputRequest;
use rmcp::model::ReadResourceRequest;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::ReadResourceResult;
use rmcp::model::RequestId;
use rmcp::model::ServerRequest;
use rmcp::model::ServerResult;
use rmcp::service::PeerRequestOptions;
use rmcp::service::RequestContext;
use rmcp::service::RunningService;
use rmcp::service::Service;
use rmcp::service::ServiceError;
use rmcp::transport::streamable_http_client::StreamableHttpError;
use serde::Deserialize;
use serde_json::Value;
use crate::elicitation_client_service::ElicitationClientService;
use crate::http_client_adapter::StreamableHttpClientAdapterError;
use crate::request_cancellation::RequestCancellation;
static NEXT_INPUT_ID: AtomicU64 = AtomicU64::new(0);
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RequiredInput {
input_requests: Option<BTreeMap<String, Value>>,
request_state: Option<String>,
}
pub(crate) async fn call_tool(
service: &RunningService<RoleClient, ElicitationClientService>,
input_service: &ElicitationClientService,
params: CallToolRequestParams,
) -> Result<CallToolResult, ServiceError> {
match request(
service,
input_service,
ClientRequest::CallToolRequest(CallToolRequest::new(params)),
RequestCancellation::OnDrop,
)
.await?
{
ServerResult::CallToolResult(result) => Ok(result),
_ => Err(ServiceError::UnexpectedResponse),
}
}
pub(crate) async fn read_resource(
service: &RunningService<RoleClient, ElicitationClientService>,
input_service: &ElicitationClientService,
params: ReadResourceRequestParams,
cancellation: RequestCancellation,
) -> Result<ReadResourceResult, ServiceError> {
match request(
service,
input_service,
ClientRequest::ReadResourceRequest(ReadResourceRequest::new(params)),
cancellation,
)
.await?
{
ServerResult::ReadResourceResult(result) => Ok(result),
_ => Err(ServiceError::UnexpectedResponse),
}
}
async fn request(
service: &RunningService<RoleClient, ElicitationClientService>,
input_service: &ElicitationClientService,
mut request: ClientRequest,
cancellation: RequestCancellation,
) -> Result<ServerResult, ServiceError> {
let mut state_only_rounds = 0;
let mut submitted_verification_proof = false;
for round in 0..DEFAULT_MRTR_MAX_ROUNDS {
let response = cancellation
.send(
service.peer(),
request.clone(),
PeerRequestOptions::no_options(),
)
.await;
let result = response.map_err(|error| {
if submitted_verification_proof
&& let ServiceError::TransportSend(transport) = &error
&& !matches!(
transport
.error
.downcast_ref::<StreamableHttpError<StreamableHttpClientAdapterError>>(),
Some(StreamableHttpError::AuthRequired(_))
)
{
// Session recovery must not replay the original operation after a
// continuation (which may already have consumed a signed proof).
// Auth challenges already return without replaying the operation.
invalid("MCP continuation failed; the operation was not restarted")
} else {
error
}
})?;
let input = match result {
result @ (ServerResult::CallToolResult(_) | ServerResult::ReadResourceResult(_)) => {
return Ok(result);
}
ServerResult::InputRequiredResult(result) => {
serde_json::to_value(result).map_err(|_| invalid("invalid MCP input request"))?
}
// RMCP's InputRequest union intentionally excludes custom methods.
ServerResult::CustomResult(result)
if result.0.get("resultType").and_then(Value::as_str) == Some("input_required") =>
{
result.0
}
_ => return Err(ServiceError::UnexpectedResponse),
};
if round + 1 == DEFAULT_MRTR_MAX_ROUNDS {
break;
}
let input: RequiredInput =
serde_json::from_value(input).map_err(|_| invalid("invalid MCP input request"))?;
let requests = input.input_requests.unwrap_or_default();
if requests.is_empty() && input.request_state.is_none() {
return Err(ServiceError::UnexpectedResponse);
}
// Parse the whole round before presenting any prompts. Only standard MCP
// inputs and supported OpenAI elicitation modes are accepted.
let requests = requests
.into_iter()
.map(|(key, value)| parse_input(value).map(|request| (key, request)))
.collect::<Result<Vec<_>, _>>()?;
if requests.is_empty() {
let millis = (50_u64 << state_only_rounds.min(/*other*/ 3)).min(/*other*/ 250);
tokio::time::sleep(Duration::from_millis(millis)).await;
state_only_rounds += 1;
} else {
state_only_rounds = 0;
}
let responses =
futures::future::try_join_all(requests.into_iter().map(|(key, mut request)| {
// Prompts outlive individual transport requests, including across
// session recovery, so their IDs must not reuse a peer's counter.
let native_verification = matches!(&request, ServerRequest::CustomRequest(request)
if request.params.as_ref().and_then(|params| params.get("mode"))
.and_then(Value::as_str) == Some(crate::user_verification::MODE));
let id = NEXT_INPUT_ID.fetch_add(1, Ordering::Relaxed);
let request_id = RequestId::String(format!("mcp-input/{id}").into());
let mut context = RequestContext::new(request_id, service.peer().clone());
context.meta = std::mem::take(request.get_meta_mut());
context.extensions = std::mem::take(request.extensions_mut());
async move {
let result = input_service
.handle_request(request, context)
.await
.map_err(ServiceError::McpError)?;
let result = serde_json::to_value(result)
.map_err(|_| invalid("invalid MCP input response"))?;
let contains_proof = native_verification
&& result.get("action").and_then(Value::as_str) == Some("accept");
Ok::<_, ServiceError>((key, result, contains_proof))
}
}));
let responses = tokio::select! {
biased;
_ = async {
// RMCP exposes closure status but no awaitable closure notification.
// Include explicit cancellation and transport EOF; dropping the joined
// handlers releases both their UI callbacks and timeout pause guards.
while !service.is_closed() && !service.peer().is_transport_closed() {
tokio::time::sleep(Duration::from_millis(/*millis*/ 50)).await;
}
} => return Err(ServiceError::TransportClosed),
responses = responses => responses?,
};
let input_responses = (!responses.is_empty()).then(|| {
responses
.into_iter()
.map(|(key, result, contains_proof)| {
submitted_verification_proof |= contains_proof;
(key, result)
})
.collect()
});
match &mut request {
ClientRequest::CallToolRequest(request) => {
request.params.input_responses = input_responses;
request.params.request_state = input.request_state;
}
ClientRequest::ReadResourceRequest(request) => {
request.params.input_responses = input_responses;
request.params.request_state = input.request_state;
}
_ => return Err(ServiceError::UnexpectedResponse),
}
}
Err(ServiceError::InputRequiredRoundsExceeded {
max_rounds: DEFAULT_MRTR_MAX_ROUNDS,
})
}
fn parse_input(value: Value) -> Result<ServerRequest, ServiceError> {
if let Ok(request) = serde_json::from_value::<InputRequest>(value.clone()) {
return match request {
InputRequest::CreateMessage(request) => {
Ok(ServerRequest::CreateMessageRequest(request))
}
InputRequest::Elicitation(request) => Ok(ServerRequest::ElicitRequest(request)),
InputRequest::ListRoots(request) => Ok(ServerRequest::ListRootsRequest(request)),
_ => Err(ServiceError::UnexpectedResponse),
};
}
let request: ServerRequest =
serde_json::from_value(value).map_err(|_| invalid("invalid MCP input request"))?;
if let ServerRequest::CustomRequest(request) = &request
&& request.method == "openai/elicitation/create"
{
match request
.params
.as_ref()
.and_then(|params| params.get("mode"))
.and_then(Value::as_str)
{
Some("form") => {
crate::elicitation_client_service::openai_elicitation_form(request.clone())
.map_err(ServiceError::McpError)?;
}
Some(crate::user_verification::MODE) => {
crate::user_verification::parse_request(request.clone())
.map_err(ServiceError::McpError)?;
}
_ => return Err(invalid("unsupported OpenAI elicitation mode")),
}
return Ok(ServerRequest::CustomRequest(request.clone()));
}
Err(invalid("unsupported MCP input request"))
}
fn invalid(message: &'static str) -> ServiceError {
ServiceError::McpError(rmcp::ErrorData::invalid_request(
message, /*data*/ None,
))
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,56 @@
//! Access structured MCP errors without dropping their original protocol data.
use anyhow::Error;
use rmcp::ErrorData;
use rmcp::service::ServiceError;
use std::time::Duration;
use crate::rmcp_client::ClientOperationError;
use crate::rmcp_client::RmcpClient;
/// Whether tools/list would retry this transport error before returning it to the caller.
pub fn is_retryable_transport_error(error: &Error) -> bool {
error
.downcast_ref()
.is_some_and(RmcpClient::is_retryable_transport_error)
}
/// Returns the server's structured protocol error, including its original data.
pub fn mcp_error(error: &Error) -> Option<&ErrorData> {
let ClientOperationError::Service(ServiceError::McpError(error)) = error.downcast_ref()? else {
return None;
};
Some(error)
}
/// Preserves a request deadline as a typed error for caller-side telemetry.
pub fn request_timeout_error(label: &str, duration: Duration) -> Error {
ClientOperationError::Timeout {
label: label.to_string(),
duration,
}
.into()
}
/// Returns a bounded caller-side failure category without parsing error text.
pub fn request_error_code(error: &Error) -> Option<&'static str> {
let error = error.downcast_ref::<ClientOperationError>()?;
Some(match error {
ClientOperationError::Timeout { .. } => "request_timeout",
ClientOperationError::Service(error) => match error {
ServiceError::Timeout { .. } => "request_timeout",
ServiceError::TransportClosed => "transport_closed",
ServiceError::TransportSend(_) => "transport_error",
ServiceError::McpError(_) => "protocol_error",
ServiceError::UnexpectedResponse => "unexpected_response",
ServiceError::Cancelled { .. } => "cancelled",
ServiceError::SubscriptionLagged { .. } => "subscription_lagged",
ServiceError::InputRequiredRoundsExceeded { .. } => "input_required_rounds_exceeded",
_ => return None,
},
})
}
#[cfg(test)]
#[path = "service_error_tests.rs"]
mod tests;

View File

@@ -0,0 +1,24 @@
//! Verify caller error classification preserves typed causes through context.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn request_error_codes_preserve_typed_causes_through_context() {
for (error, expected) in [
(
request_timeout_error("tools/call", Duration::from_secs(1)),
Some("request_timeout"),
),
(
anyhow::Error::from(ClientOperationError::Service(ServiceError::TransportClosed)),
Some("transport_closed"),
),
(anyhow::anyhow!("timed out awaiting tools/call"), None),
] {
assert_eq!(
request_error_code(&error.context("tool call failed")),
expected
);
}
}

View File

@@ -0,0 +1,96 @@
use anyhow::Error;
use codex_exec_server::ExecServerError;
use rmcp::service::ClientInitializeError;
use rmcp::service::ServiceError;
use rmcp::transport::DynamicTransportError;
use rmcp::transport::auth::AuthError;
use rmcp::transport::streamable_http_client::StreamableHttpError;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaInvalidGrantSource;
use crate::http_client_adapter::StreamableHttpClientAdapterError;
use crate::rmcp_client::ClientOperationError;
/// Returns whether an RMCP client error indicates that authentication is required.
///
/// This does not distinguish first-time login from reauthentication.
/// Streamable HTTP initialization errors are stored inside RMCP's dynamic
/// transport error, which is not part of the standard error source chain.
pub fn is_authentication_required_error(error: &Error) -> bool {
error.chain().any(|source| {
if let Some(error) = source.downcast_ref::<crate::EmaTokenSourceError>() {
return error.is_authentication_required();
}
source
.downcast_ref::<AuthError>()
.is_some_and(auth_error_requires_authentication)
|| source
.downcast_ref::<EmaAuthFailure>()
.is_some_and(|error| match error {
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::IdentityClientRejected
| EmaAuthFailure::ReauthenticationRequired => true,
// Rejecting an ID-JAG does not invalidate the enterprise login itself.
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
} => false,
})
|| source
.downcast_ref::<ExecServerError>()
.is_some_and(exec_server_error_requires_authentication)
|| source
.downcast_ref::<ClientInitializeError>()
.is_some_and(|mut error| {
while let ClientInitializeError::LegacyFallbackFailed { fallback, .. } = error {
error = fallback;
}
matches!(
error,
ClientInitializeError::TransportError { error, .. }
if transport_error_requires_authentication(error)
)
})
|| source
.downcast_ref::<ClientOperationError>()
.is_some_and(|error| {
matches!(
error,
ClientOperationError::Service(ServiceError::TransportSend(error))
if transport_error_requires_authentication(error)
)
})
})
}
fn transport_error_requires_authentication(error: &DynamicTransportError) -> bool {
error
.error
.downcast_ref::<StreamableHttpError<StreamableHttpClientAdapterError>>()
.is_some_and(|error| match error {
StreamableHttpError::AuthRequired(_) => true,
StreamableHttpError::Auth(auth_error) => auth_error_requires_authentication(auth_error),
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(error)) => {
exec_server_error_requires_authentication(error)
}
_ => false,
})
}
fn exec_server_error_requires_authentication(error: &ExecServerError) -> bool {
matches!(error, ExecServerError::AuthenticationRequired(_))
}
fn auth_error_requires_authentication(error: &AuthError) -> bool {
matches!(
error,
AuthError::AuthorizationRequired | AuthError::TokenExpired
)
}

View File

@@ -0,0 +1,115 @@
//! Selects the handshake for a fresh local helper when automatic discovery cannot finish in place.
//! A late discovery response can still negotiate the modern protocol after rmcp sent initialize.
use std::io;
use rmcp::model::ErrorCode;
use rmcp::model::ErrorData;
use rmcp::model::JsonRpcMessage;
use rmcp::model::ProtocolVersion;
use rmcp::model::ServerResult;
use rmcp::service::ClientInitializeError;
use super::HandshakeError;
use crate::McpProtocolMode;
use crate::http_client_adapter::is_known_legacy_protocol_version;
use crate::local_stdio_transport::DiscoveryOutcome;
pub(super) fn restart_mode(
error: &ClientInitializeError,
discovery: Option<DiscoveryOutcome>,
) -> anyhow::Result<Option<McpProtocolMode>> {
let Some(DiscoveryOutcome::Late {
reply,
after_reoffer,
}) = discovery
else {
return Ok(should_restart_legacy(error, discovery).then_some(McpProtocolMode::Legacy));
};
match *reply {
JsonRpcMessage::Response(response) => match response.result {
ServerResult::DiscoverResult(result) => {
let supported = result.supported_versions;
restart_for_versions(&supported).map(Some).ok_or_else(|| {
ClientInitializeError::NoCompatibleProtocolVersion {
client_supported: vec![ProtocolVersion::V_2026_07_28],
server_supported: supported,
}
})
}
ServerResult::InitializeResult(result)
if is_known_legacy_protocol_version(&result.protocol_version) =>
{
Ok(Some(McpProtocolMode::Legacy))
}
result => Err(ClientInitializeError::ExpectedInitResult(Some(result))),
},
JsonRpcMessage::Error(response) => {
let mode = offered_restart_mode(&response.error);
match mode {
// rmcp permits one re-offer. A fresh discover verifies it even without an ID.
Some(McpProtocolMode::DiscoverLocalStdio) if !after_reoffer => Ok(mode),
// Without an ID the error may have rejected initialize itself.
Some(McpProtocolMode::Legacy) if response.id.is_some() => Ok(mode),
_ => Err(ClientInitializeError::JsonRpcError(response.error)),
}
}
_ => unreachable!("a late discovery reply is a response or error"),
}
.map_err(|source| HandshakeError { source }.into())
}
fn offered_restart_mode(error: &ErrorData) -> Option<McpProtocolMode> {
if error.code != ErrorCode::UNSUPPORTED_PROTOCOL_VERSION {
return None;
}
let supported = error.data.as_ref()?.get("supported")?;
let versions = serde_json::from_value::<Vec<ProtocolVersion>>(supported.clone()).ok()?;
restart_for_versions(&versions)
}
fn restart_for_versions(supported: &[ProtocolVersion]) -> Option<McpProtocolMode> {
if supported.contains(&ProtocolVersion::V_2026_07_28) {
Some(McpProtocolMode::DiscoverLocalStdio)
} else if supported.iter().any(is_known_legacy_protocol_version) {
Some(McpProtocolMode::Legacy)
} else {
None
}
}
fn should_restart_legacy(
error: &ClientInitializeError,
discovery: Option<DiscoveryOutcome>,
) -> bool {
match error {
// A helper that assumes its first request is initialize can answer discover with this.
ClientInitializeError::ExpectedInitResult(Some(ServerResult::InitializeResult(result))) => {
!matches!(discovery, Some(DiscoveryOutcome::Reply))
&& is_known_legacy_protocol_version(&result.protocol_version)
}
ClientInitializeError::NoCompatibleProtocolVersion {
server_supported, ..
} => restart_for_versions(server_supported) == Some(McpProtocolMode::Legacy),
ClientInitializeError::LegacyFallbackFailed { discover, fallback } => {
match fallback.as_ref() {
ClientInitializeError::ConnectionClosed(_) => true,
// A legacy helper can reject initialize if discover already took its first request.
ClientInitializeError::JsonRpcError(_) => matches!(
discover.as_ref(),
ClientInitializeError::JsonRpcError(error) if error.code == ErrorCode::METHOD_NOT_FOUND
),
ClientInitializeError::TransportError { error, .. } => {
error.error.downcast_ref::<io::Error>().is_some_and(|e| {
matches!(
e.kind(),
io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
)
})
}
_ => false,
}
}
_ => matches!(discovery, Some(DiscoveryOutcome::RetryLegacy)),
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,259 @@
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use anyhow::Result;
use anyhow::anyhow;
use codex_exec_server::ExecServerError;
use http::StatusCode;
use rmcp::service::RoleClient;
use rmcp::service::RunningService;
use rmcp::transport::streamable_http_client::StreamableHttpError;
use tokio::time;
use tracing::warn;
use crate::elicitation_client_service::ElicitationClientService;
use crate::http_client_adapter::StreamableHttpClientAdapterError;
use crate::oauth::OAuthRuntime;
use super::InitializeContext;
use super::PendingTransport;
use super::RmcpClient;
const JSON_RPC_INTERNAL_ERROR_CODE: i64 = -32603;
pub(super) const STREAMABLE_HTTP_RETRY_DELAYS_MS: [u64; 2] = [250, 1_000];
impl RmcpClient {
pub(super) async fn connect_pending_transport_with_initialize_retries(
&self,
initial_transport: PendingTransport,
initialize_context: &InitializeContext,
) -> Result<(
Arc<RunningService<RoleClient, ElicitationClientService>>,
Option<OAuthRuntime>,
)> {
let timeout = initialize_context.timeout;
let should_retry = match &initial_transport {
PendingTransport::InProcess { .. } | PendingTransport::Stdio { .. } => false,
PendingTransport::StreamableHttp { .. }
| PendingTransport::StreamableHttpWithOAuth { .. }
| PendingTransport::StreamableHttpWithAccessTokenOnly { .. } => true,
};
let mut retry_deadline = timeout.map(|duration| Instant::now() + duration);
let mut pending_transport = Some(initial_transport);
for (attempt, retry_delay_ms) in STREAMABLE_HTTP_RETRY_DELAYS_MS
.iter()
.copied()
.map(Some)
.chain(std::iter::once(None))
.enumerate()
{
let transport = match pending_transport.take() {
Some(transport) => transport,
None => {
let remaining = remaining_initialize_timeout(timeout, retry_deadline)?;
match remaining {
Some(remaining) => time::timeout(
remaining,
Self::create_pending_transport(&self.transport_recipe),
)
.await
.map_err(|_| initialize_timeout_error(timeout, remaining))??,
None => Self::create_pending_transport(&self.transport_recipe).await?,
}
}
};
if let PendingTransport::StreamableHttpWithOAuth { oauth_runtime, .. } = &transport {
// OAuth refresh has its own lock and provider request bounds. Exclude it from the
// MCP handshake budget, and finish persistence before attempting initialize.
let refresh_started_at = Instant::now();
oauth_runtime.refresh_if_needed().await?;
if let Some(deadline) = retry_deadline.as_mut() {
*deadline += refresh_started_at.elapsed();
}
}
let attempt_timeout = remaining_initialize_timeout(timeout, retry_deadline)?;
match self
.connect_pending_transport(transport, initialize_context, attempt_timeout)
.await
{
Ok(result) => return Ok(result),
Err(error) if should_retry && Self::is_retryable_initialize_error(&error) => {
let Some(retry_delay_ms) = retry_delay_ms else {
return Err(error);
};
let delay = Duration::from_millis(retry_delay_ms);
warn!(
attempt = attempt + 1,
max_attempts = STREAMABLE_HTTP_RETRY_DELAYS_MS.len() + 1,
delay_ms = delay.as_millis(),
error = %error,
"streamable HTTP MCP initialize failed with a retryable error; retrying"
);
if !sleep_with_retry_deadline(delay, retry_deadline).await {
let duration = timeout.unwrap_or(delay);
return Err(anyhow!(
"timed out handshaking with MCP server after {duration:?}"
));
}
}
Err(error) => return Err(error),
}
}
unreachable!("initialize retry loop should return on success or final error")
}
fn is_retryable_initialize_error(error: &anyhow::Error) -> bool {
error.chain().any(|source| {
source
.downcast_ref::<HandshakeError>()
.is_some_and(|error| Self::is_retryable_client_initialize_error(&error.source))
|| source
.downcast_ref::<rmcp::service::ClientInitializeError>()
.is_some_and(Self::is_retryable_client_initialize_error)
})
}
fn is_retryable_client_initialize_error(error: &rmcp::service::ClientInitializeError) -> bool {
match error {
rmcp::service::ClientInitializeError::LegacyFallbackFailed { fallback, .. } => {
Self::is_retryable_client_initialize_error(fallback)
}
rmcp::service::ClientInitializeError::TransportError { error, context }
if matches!(
context.as_ref(),
"send initialize request" | "send discover request"
) =>
{
error
.error
.downcast_ref::<StreamableHttpError<StreamableHttpClientAdapterError>>()
.is_some_and(Self::is_retryable_streamable_http_error)
}
rmcp::service::ClientInitializeError::TransportError { error, context }
if context.as_ref() == "send initialized notification" =>
{
error
.error
.downcast_ref::<StreamableHttpError<StreamableHttpClientAdapterError>>()
.is_some_and(|error| {
matches!(error, StreamableHttpError::TransportChannelClosed)
|| Self::is_retryable_streamable_http_error(error)
})
}
_ => false,
}
}
pub(super) fn is_retryable_streamable_http_error(
error: &StreamableHttpError<StreamableHttpClientAdapterError>,
) -> bool {
match error {
StreamableHttpError::Client(StreamableHttpClientAdapterError::Auth(
codex_api::AuthError::Transient(_),
)) => true,
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::HttpRequest(_),
)) => true,
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::Server { code, message },
)) => {
*code == JSON_RPC_INTERNAL_ERROR_CODE && message.starts_with("http/request failed:")
}
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::Protocol(message),
)) => message.starts_with("http response stream `") && message.contains("` failed:"),
StreamableHttpError::UnexpectedServerResponse(message) => {
is_retryable_unexpected_server_response(message.as_ref())
}
StreamableHttpError::AuthRequired(_)
| StreamableHttpError::InsufficientScope(_)
| StreamableHttpError::SessionExpired
| StreamableHttpError::UnexpectedContentType(_)
| StreamableHttpError::ServerDoesNotSupportSse
| StreamableHttpError::Deserialize(_)
| StreamableHttpError::Client(StreamableHttpClientAdapterError::Auth(
codex_api::AuthError::Build(_),
))
| StreamableHttpError::Client(StreamableHttpClientAdapterError::SessionExpired404)
| StreamableHttpError::Client(StreamableHttpClientAdapterError::Header(_)) => false,
_ => false,
}
}
}
fn is_retryable_unexpected_server_response(message: &str) -> bool {
let Some(message) = message.strip_prefix("HTTP ") else {
return false;
};
let status_code = message
.chars()
.take_while(char::is_ascii_digit)
.collect::<String>();
let Ok(status) = status_code.parse::<u16>() else {
return false;
};
let Ok(status) = StatusCode::from_u16(status) else {
return false;
};
is_retryable_http_status(status)
}
fn is_retryable_http_status(status: StatusCode) -> bool {
matches!(
status,
StatusCode::REQUEST_TIMEOUT
| StatusCode::TOO_MANY_REQUESTS
| StatusCode::INTERNAL_SERVER_ERROR
| StatusCode::BAD_GATEWAY
| StatusCode::SERVICE_UNAVAILABLE
| StatusCode::GATEWAY_TIMEOUT
)
}
fn remaining_initialize_timeout(
timeout: Option<Duration>,
deadline: Option<Instant>,
) -> Result<Option<Duration>> {
let Some(deadline) = deadline else {
return Ok(None);
};
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
Err(initialize_timeout_error(timeout, remaining))
} else {
Ok(Some(remaining))
}
}
fn initialize_timeout_error(timeout: Option<Duration>, fallback: Duration) -> anyhow::Error {
let duration = timeout.unwrap_or(fallback);
anyhow!("timed out handshaking with MCP server after {duration:?}")
}
pub(super) async fn sleep_with_retry_deadline(delay: Duration, deadline: Option<Instant>) -> bool {
if let Some(deadline) = deadline {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return false;
}
time::timeout(remaining, time::sleep(delay)).await.is_ok()
} else {
time::sleep(delay).await;
true
}
}
#[derive(Debug, thiserror::Error)]
#[error("handshaking with MCP server failed: {source}")]
pub(super) struct HandshakeError {
#[source]
pub(super) source: rmcp::service::ClientInitializeError,
}
#[cfg(test)]
#[path = "streamable_http_retry_tests.rs"]
mod tests;

View File

@@ -0,0 +1,132 @@
use std::any::TypeId;
use codex_exec_server::ExecServerError;
use pretty_assertions::assert_eq;
use rmcp::transport::DynamicTransportError;
use rmcp::transport::streamable_http_client::AuthRequiredError;
use rmcp::transport::streamable_http_client::StreamableHttpError;
use crate::http_client_adapter::StreamableHttpClientAdapterError;
use crate::rmcp_client::ClientOperationError;
use super::*;
#[test]
fn retryable_initialize_error_includes_discovery_and_initialized_notification_context() {
let contexts = [
"send discover request",
"send initialize request",
"send initialized notification",
"receive initialize response",
];
assert_eq!(
contexts.map(|context| {
RmcpClient::is_retryable_client_initialize_error(&retryable_initialize_error(context))
}),
[true, true, true, false],
);
}
#[test]
fn streamable_http_retry_classifies_transport_and_auth_errors() {
let errors = [
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::RequestNotSent("enterprise policy is updating".to_string()),
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::HttpRequest("error sending request for url".to_string()),
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::Server {
code: JSON_RPC_INTERNAL_ERROR_CODE,
message: "http/request failed: error sending request for url".to_string(),
},
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::Protocol(
"http response stream `http-1` failed: exec-server transport disconnected"
.to_string(),
),
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::HttpRequest(
ExecServerError::Protocol(
"http response stream `http-1` received seq 2, expected 1".to_string(),
),
)),
StreamableHttpError::UnexpectedServerResponse("HTTP 502: upstream failure".into()),
StreamableHttpError::UnexpectedServerResponse("HTTP 503: service unavailable".into()),
StreamableHttpError::UnexpectedServerResponse("HTTP 403: forbidden".into()),
StreamableHttpError::UnexpectedServerResponse("HTTP 400: bad request".into()),
StreamableHttpError::Client(StreamableHttpClientAdapterError::Auth(
codex_api::AuthError::Transient("credential refresh unavailable".to_string()),
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::Auth(
codex_api::AuthError::Build("invalid authentication".to_string()),
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::Auth(
codex_api::AuthError::Policy(codex_http_client::NetworkPolicyDenied::Revoked),
)),
];
assert_eq!(
errors.map(|error| {
let transport = DynamicTransportError::from_parts(
"streamable_http",
TypeId::of::<()>(),
Box::new(error),
);
let error =
ClientOperationError::from(rmcp::service::ServiceError::TransportSend(transport));
crate::is_retryable_transport_error(&anyhow::Error::new(error).context("listing tools"))
}),
[
false, true, true, true, false, true, true, false, false, true, false, false
],
);
}
#[test]
fn startup_http_authentication_challenges_require_reauthorization() {
let transport_error = || {
DynamicTransportError::from_parts(
"streamable_http",
TypeId::of::<()>(),
Box::new(
StreamableHttpError::<StreamableHttpClientAdapterError>::AuthRequired(
AuthRequiredError::new("Bearer error=\"invalid_token\"".to_string()),
),
),
)
};
let errors = [
anyhow::Error::new(rmcp::service::ClientInitializeError::TransportError {
error: transport_error(),
context: "send initialize request".into(),
}),
anyhow::Error::new(ClientOperationError::from(
rmcp::service::ServiceError::TransportSend(transport_error()),
)),
];
for error in errors {
assert!(crate::startup_error::is_authentication_required_error(
&error
));
}
}
fn retryable_initialize_error(context: &'static str) -> rmcp::service::ClientInitializeError {
rmcp::service::ClientInitializeError::TransportError {
error: DynamicTransportError::from_parts(
"streamable_http",
TypeId::of::<()>(),
Box::new(StreamableHttpError::Client(
StreamableHttpClientAdapterError::HttpRequest(ExecServerError::HttpRequest(
"error sending request for url".to_string(),
)),
)),
),
context: context.into(),
}
}

View File

@@ -0,0 +1,105 @@
//! Exercises pending MRTR input cleanup over a real duplex transport.
use super::ElicitationClientService;
use crate::request_input::call_tool;
use crate::rmcp_client::ElicitationPauseState;
use codex_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use rmcp::RoleServer;
use rmcp::model::CallToolRequestParams;
use rmcp::model::ClientConfig;
use rmcp::model::ClientJsonRpcMessage;
use rmcp::model::CustomResult;
use rmcp::model::ServerJsonRpcMessage;
use rmcp::model::ServerResult;
use rmcp::service::ServiceError;
use rmcp::service::serve_directly;
use rmcp::transport::IntoTransport;
use rmcp::transport::Transport;
use serde_json::json;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::timeout;
#[tokio::test]
async fn connection_closure_releases_pending_inputs_and_timeout_pause() -> anyhow::Result<()> {
for mode in ["form", "openai/userVerification"] {
for close_transport in [false, true] {
let pause_state = ElicitationPauseState::new();
let mut paused = pause_state.subscribe();
let (route_tx, mut route_rx) = mpsc::unbounded_channel();
let mut info = ClientConfig::default();
info.capabilities.extensions = Some(
[(
OPENAI_ELICITATION_EXTENSION_ID.into(),
serde_json::Map::from_iter([
("userVerification".into(), json!({})),
("form".into(), json!({})),
]),
)]
.into_iter()
.collect(),
);
let service = ElicitationClientService::new(
info,
Box::new(move |_, _| {
let (tx, rx) = oneshot::channel();
route_tx.send(tx).unwrap();
Box::pin(async move { Ok(rx.await?) })
}),
pause_state,
);
let (client_transport, server_transport) =
tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service, client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
let call = call_tool(
&client,
client.service(),
CallToolRequestParams::new("test"),
);
tokio::pin!(call);
let request = tokio::select! {
result = &mut call => panic!("tool completed before input: {result:?}"),
request = timeout(Duration::from_secs(/*secs*/ 5), server.receive()) => request?,
};
let Some(ClientJsonRpcMessage::Request(request)) = request else {
anyhow::bail!("expected tool call");
};
let params = match mode {
"form" => json!({
"mode": mode, "message": "Confirm",
"requestedSchema": {"type": "object", "properties": {}},
}),
_ => json!({
"mode": mode, "title": "Verify", "description": "", "challenge": "AQID",
}),
};
server.send(ServerJsonRpcMessage::response(
ServerResult::CustomResult(CustomResult(json!({
"resultType": "input_required",
"inputRequests": {"input": {"method": "openai/elicitation/create", "params": params}},
}))),
request.id,
)).await?;
let reply = tokio::select! {
result = &mut call => panic!("tool completed before prompting: {result:?}"),
reply = timeout(Duration::from_secs(/*secs*/ 5), route_rx.recv()) => reply?.unwrap(),
};
assert!(*paused.borrow());
if close_transport {
drop(server);
} else {
client.cancellation_token().cancel();
}
let result = timeout(Duration::from_secs(/*secs*/ 5), call).await?;
assert!(
matches!(result, Err(ServiceError::TransportClosed)),
"{result:?}"
);
assert!(reply.is_closed());
assert!(!*paused.borrow_and_update());
}
}
Ok(())
}

View File

@@ -0,0 +1,73 @@
//! Records catalog invalidations in transport order, before a later tool response can
//! let inference continue. The SDK still receives and handles every message normally.
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use rmcp::model::JsonRpcMessage;
use rmcp::model::ServerNotification;
use rmcp::service::RoleClient;
use rmcp::service::RxJsonRpcMessage;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::IntoTransport;
use rmcp::transport::Transport;
/// Read-only observation of notifications received by one connection. Retaining this
/// handle does not keep the connection alive.
#[derive(Clone)]
pub struct ToolListRevision(pub(crate) Arc<AtomicU64>);
impl ToolListRevision {
pub fn current(&self) -> u64 {
self.0.load(Ordering::Acquire)
}
}
pub(crate) fn track_tool_list_changes<T, E, A>(
transport: T,
revision: Arc<AtomicU64>,
) -> impl Transport<RoleClient, Error = E> + 'static
where
T: IntoTransport<RoleClient, E, A>,
E: std::error::Error + Send + Sync + 'static,
{
ToolListChanges {
inner: transport.into_transport(),
revision,
}
}
struct ToolListChanges<T> {
inner: T,
revision: Arc<AtomicU64>,
}
impl<T: Transport<RoleClient> + 'static> Transport<RoleClient> for ToolListChanges<T> {
type Error = T::Error;
fn send(
&mut self,
message: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
self.inner.send(message)
}
async fn receive(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
let message = self.inner.receive().await?;
if let JsonRpcMessage::Notification(notification) = &message
&& matches!(
notification.notification,
ServerNotification::ToolListChangedNotification(_)
)
{
self.revision.fetch_add(1, Ordering::AcqRel);
}
Some(message)
}
fn close(&mut self) -> impl Future<Output = Result<(), Self::Error>> + Send {
self.inner.close()
}
}

View File

@@ -0,0 +1,91 @@
//! Carries request-local W3C snapshots through RMCP's background transport queues.
//! Metadata does not retain caller spans or change the SDK's cursor-based cache keys.
use codex_protocol::protocol::W3cTraceContext;
use rmcp::model::CustomRequest;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::RequestMetaObject;
use serde_json::Value;
use tracing::Span;
/// Reads metadata from an SDK-serialized message, where envelope extensions have
/// already been merged with params._meta and take precedence on key conflicts.
/// Unlike RMCP's GetMeta, this also includes metadata supplied in typed params.
fn merged_request_meta(message: &Value) -> Option<&serde_json::Map<String, Value>> {
message.pointer("/params/_meta").and_then(Value::as_object)
}
pub(crate) fn with_current_trace(mut meta: Option<RequestMetaObject>) -> Option<RequestMetaObject> {
if let Some(trace) = codex_otel::current_span_w3c_trace_context() {
let meta = meta.get_or_insert_default();
if let Some(traceparent) = trace.traceparent {
meta.set_traceparent(traceparent);
}
// A supplied tracestate must not be paired with a different caller's parent.
meta.remove("tracestate");
if let Some(tracestate) = trace.tracestate {
meta.set_tracestate(tracestate);
}
}
meta
}
pub(crate) fn traced_pagination(
mut params: Option<PaginatedRequestParams>,
) -> Option<PaginatedRequestParams> {
let meta = with_current_trace(params.as_mut().and_then(|params| params.meta.take()));
if params.is_none() && meta.is_none() {
return None;
}
let mut params = params.unwrap_or_default();
params.meta = meta;
Some(params)
}
pub(crate) fn traced_custom_request(method: &str, params: Option<Value>) -> CustomRequest {
let mut request = CustomRequest::new(method, params);
let existing_meta = request
.params
.as_mut()
.and_then(|params| params.get_mut("_meta"))
.and_then(Value::as_object_mut)
.map(std::mem::take)
.map(RequestMetaObject::from);
if let Some(meta) = with_current_trace(existing_meta) {
// Move valid metadata into the canonical SDK extension slot. Otherwise
// its merge could retain an old params.tracestate beside the new parent.
request.extensions.insert(meta);
}
request
}
pub(crate) fn request_span(message: &Value) -> Span {
let Some(meta) = merged_request_meta(message) else {
return Span::none();
};
let trace = W3cTraceContext {
traceparent: meta
.get("traceparent")
.and_then(Value::as_str)
.map(str::to_owned),
tracestate: meta
.get("tracestate")
.and_then(Value::as_str)
.map(str::to_owned),
};
let Some(context) = codex_otel::context_from_w3c_trace_context(&trace) else {
return Span::none();
};
let method = message
.get("method")
.and_then(Value::as_str)
.unwrap_or("unknown");
let span = tracing::info_span!("mcp.http.request", mcp.method = method);
// Set the parent before the span is entered; never reparent the shared worker.
codex_otel::set_parent_from_context(&span, context);
span
}
#[cfg(test)]
#[path = "trace_context_tests.rs"]
mod tests;

View File

@@ -0,0 +1,45 @@
//! Checks that trace metadata uses the SDK's envelope/params merge precedence.
use super::merged_request_meta;
use pretty_assertions::assert_eq;
use rmcp::model::ClientRequest;
use rmcp::model::CustomRequest;
use rmcp::model::GetMeta;
use rmcp::model::ListToolsRequest;
use rmcp::model::PaginatedRequestParams;
use rmcp::model::RequestMetaObject;
use serde_json::json;
#[test]
fn merged_metadata_preserves_params_and_prefers_extensions() -> serde_json::Result<()> {
let params_meta = json!({"application": "preserved", "traceparent": "params-parent"});
let mut params = PaginatedRequestParams::default();
params.meta = Some(serde_json::from_value::<RequestMetaObject>(
params_meta.clone(),
)?);
let requests = [
ClientRequest::ListToolsRequest(ListToolsRequest::with_param(params)),
ClientRequest::CustomRequest(CustomRequest::new(
"test/custom",
Some(json!({"_meta": params_meta})),
)),
];
for mut request in requests {
let params_only = serde_json::to_value(&request)?;
assert_eq!(merged_request_meta(&params_only), params_meta.as_object());
request.get_meta_mut().set_traceparent("extension-parent");
request.get_meta_mut().set_tracestate("vendor=value");
let merged = serde_json::to_value(&request)?;
assert_eq!(
merged_request_meta(&merged),
json!({
"application": "preserved",
"traceparent": "extension-parent",
"tracestate": "vendor=value",
})
.as_object(),
);
}
Ok(())
}

View File

@@ -0,0 +1,134 @@
//! Validation for the user-verification elicitation extension.
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use rmcp::model::CustomRequest;
use rmcp::model::ElicitationAction;
use serde::Deserialize;
use serde::Serialize;
use crate::rmcp_client::Elicitation;
use crate::rmcp_client::ElicitationResponse;
pub(crate) const MODE: &str = "openai/userVerification";
/// Bounded diagnostic reason only; never a proof or an authorization decision.
#[derive(Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum UserVerificationReason {
UserCancelled,
UserDeclined,
CredentialMissing,
BiometricsUnavailable,
ProviderUnavailable,
AuthenticationFailed,
Timeout,
ProviderError,
ServiceError,
InvalidParams,
InvalidProof,
InvalidResponse,
ResponseError,
ResponseChannelClosed,
Interrupted,
ApprovalUnavailable,
}
impl UserVerificationReason {
pub fn from_meta(meta: Option<&serde_json::Value>) -> Option<Self> {
Self::deserialize(meta?.get("openai/userVerificationReason")?).ok()
}
pub fn into_meta(self) -> serde_json::Value {
serde_json::json!({"openai/userVerificationReason": self})
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct RequestParams {
mode: String,
#[serde(rename = "_meta")]
meta: Option<serde_json::Map<String, serde_json::Value>>,
title: String,
description: String,
challenge: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Proof<'a> {
credential_id: &'a str,
signature: &'a str,
}
pub(crate) fn parse_request(request: CustomRequest) -> Result<Elicitation, rmcp::ErrorData> {
let params = request
.params_as::<RequestParams>()
.ok()
.flatten()
.ok_or_else(invalid_request)?;
if params.mode != MODE
|| params.title.is_empty()
|| params.title.len() > 256
|| params.description.len() > 4096
|| !valid_bytes(&params.challenge, /*max_decoded_bytes*/ 4096)
{
return Err(invalid_request());
}
Ok(Elicitation::UserVerification {
meta: params.meta.map(serde_json::Value::Object),
title: params.title,
description: params.description,
challenge: params.challenge,
})
}
/// Accept only a bounded proof, and never return proof material for cancellation or rejection.
pub(crate) fn validate_response(mut response: ElicitationResponse) -> ElicitationResponse {
let reason = UserVerificationReason::from_meta(response.meta.as_ref());
response.meta = None;
match response.action {
ElicitationAction::Accept => {
let proof = response
.content
.as_ref()
.and_then(|content| Proof::deserialize(content).ok());
if proof.is_some_and(|proof| {
!proof.credential_id.is_empty()
&& proof.credential_id.len() <= 1024
&& valid_bytes(proof.signature, /*max_decoded_bytes*/ 128)
}) {
return response;
}
tracing::warn!("user-verification acceptance omitted a valid proof; cancelling");
response.action = ElicitationAction::Cancel;
response.meta = Some(UserVerificationReason::InvalidProof.into_meta());
}
ElicitationAction::Decline | ElicitationAction::Cancel => {
response.meta = reason.map(UserVerificationReason::into_meta);
}
_ => {
response.action = ElicitationAction::Cancel;
response.meta = Some(UserVerificationReason::InvalidResponse.into_meta());
}
}
response.content = None;
response
}
fn valid_bytes(encoded: &str, max_decoded_bytes: usize) -> bool {
!encoded.is_empty()
&& encoded.len() <= max_decoded_bytes.div_ceil(3) * 4
&& URL_SAFE_NO_PAD
.decode(encoded)
.is_ok_and(|bytes| !bytes.is_empty() && bytes.len() <= max_decoded_bytes)
}
fn invalid_request() -> rmcp::ErrorData {
rmcp::ErrorData::invalid_params("invalid user-verification request", /*data*/ None)
}
#[cfg(test)]
#[path = "user_verification_tests.rs"]
mod tests;

View File

@@ -0,0 +1,640 @@
//! Ensures MCP cancellation stops remote tool work and releases pending elicitation routes.
use super::ElicitationClientService;
use super::ElicitationPauseState;
use super::ElicitationResponse;
use super::RmcpClient;
use crate::InProcessTransportFactory;
use crate::McpProtocolMode;
use codex_protocol::mcp::OPENAI_ELICITATION_EXTENSION_ID;
use futures::FutureExt;
use futures::TryFutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::RoleServer;
use rmcp::ServerHandler;
use rmcp::ServiceExt;
use rmcp::model::CallToolResult;
use rmcp::model::CancelledNotification;
use rmcp::model::CancelledNotificationParam;
use rmcp::model::ClientConfig;
use rmcp::model::ClientJsonRpcMessage;
use rmcp::model::ClientNotification;
use rmcp::model::ClientRequest;
use rmcp::model::CustomRequest;
use rmcp::model::DiscoverResult;
use rmcp::model::ElicitationAction;
use rmcp::model::InitializeResult;
use rmcp::model::ProtocolVersion;
use rmcp::model::ReadResourceRequestParams;
use rmcp::model::RequestId;
use rmcp::model::ServerJsonRpcMessage;
use rmcp::model::ServerNotification;
use rmcp::model::ServerRequest;
use rmcp::model::ServerResult;
use rmcp::service::PeerRequestOptions;
use rmcp::service::QuitReason;
use rmcp::service::serve_directly;
use rmcp::transport::IntoTransport;
use rmcp::transport::Transport;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::timeout;
use tracing_test::traced_test;
struct ElicitationTestServer;
impl ServerHandler for ElicitationTestServer {}
struct ElicitationTestTransport {
servers: mpsc::UnboundedSender<tokio::io::DuplexStream>,
}
impl InProcessTransportFactory for ElicitationTestTransport {
fn open(&self) -> BoxFuture<'static, std::io::Result<tokio::io::DuplexStream>> {
let servers = self.servers.clone();
Box::pin(async move {
let (client, server) = tokio::io::duplex(/*max_buf_size*/ 4096);
servers.send(server).map_err(std::io::Error::other)?;
Ok(client)
})
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn dropping_tool_call_cancels_remote_request() -> anyhow::Result<()> {
// Run on the sole worker so independently spawned sends can be polled in reverse order.
tokio::spawn(async {
let (servers, mut server_rx) = mpsc::unbounded_channel();
let client = RmcpClient::new_in_process_client(Arc::new(ElicitationTestTransport { servers }))
.await?;
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_rx.recv().await.unwrap());
let mut initialize = Box::pin(client.initialize(
ClientConfig::default().with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(5)),
Box::new(|_, _| Box::pin(async { anyhow::bail!("unexpected elicitation") })),
));
let request = tokio::select! {
result = &mut initialize => panic!("client initialized before handshake: {result:?}"),
request = timeout(Duration::from_secs(5), server.receive()) => request?,
};
let Some(ClientJsonRpcMessage::Request(request)) = request else {
anyhow::bail!("expected initialize request");
};
assert!(matches!(request.request, ClientRequest::InitializeRequest(_)));
server
.send(ServerJsonRpcMessage::response(
ServerResult::InitializeResult(
InitializeResult::default().with_protocol_version(ProtocolVersion::V_2025_06_18),
),
request.id,
))
.await?;
timeout(Duration::from_secs(5), initialize).await??;
let initialized = timeout(Duration::from_secs(5), server.receive()).await?;
assert!(matches!(
initialized,
Some(ClientJsonRpcMessage::Notification(notification))
if matches!(notification.notification, ClientNotification::InitializedNotification(_))
));
let mut call = Box::pin(client.call_tool(
"wait".into(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
));
// Drop before yielding to the transport's independently scheduled send tasks.
assert!(futures::poll!(call.as_mut()).is_pending());
drop(call);
let request = timeout(Duration::from_secs(5), server.receive()).await?;
let Some(ClientJsonRpcMessage::Request(request)) = request else {
anyhow::bail!("expected tool call before cancellation");
};
assert!(matches!(request.request, ClientRequest::CallToolRequest(_)));
let notification = timeout(Duration::from_secs(1), server.receive())
.await
.map_err(|_| anyhow::anyhow!("dropping the call did not cancel the server request"))?;
let Some(ClientJsonRpcMessage::Notification(notification)) = notification else {
anyhow::bail!("expected cancellation notification");
};
let ClientNotification::CancelledNotification(cancelled) = notification.notification else {
anyhow::bail!("expected cancellation notification");
};
assert_eq!(cancelled.params.request_id, Some(request.id));
// Cancellation applies to this request, not the shared MCP connection.
let mut next = Box::pin(client.call_tool(
"next".into(),
/*arguments*/ None,
|_| Ok(None),
/*timeout*/ None,
));
let request = tokio::select! {
result = &mut next => panic!("tool completed before response: {result:?}"),
request = timeout(Duration::from_secs(5), server.receive()) => request?,
};
let Some(ClientJsonRpcMessage::Request(request)) = request else {
anyhow::bail!("expected next tool call");
};
let result = CallToolResult::success(Vec::new());
server
.send(ServerJsonRpcMessage::response(
ServerResult::CallToolResult(result.clone()),
request.id,
))
.await?;
assert_eq!(timeout(Duration::from_secs(5), next).await??, result);
client.shutdown().await;
Ok(())
})
.await?
}
#[tokio::test]
async fn dropping_shared_resource_and_custom_requests_cancels_the_pending_request()
-> anyhow::Result<()> {
let (servers, mut server_rx) = mpsc::unbounded_channel();
let mut client =
RmcpClient::new_in_process_client(Arc::new(ElicitationTestTransport { servers })).await?;
client.protocol_mode = McpProtocolMode::V20260728;
let mut server =
IntoTransport::<RoleServer, _, _>::into_transport(server_rx.recv().await.unwrap());
let (initialized, discovery) = tokio::join!(
client.initialize(
ClientConfig::default(),
Some(Duration::from_secs(5)),
Box::new(|_, _| panic!("unexpected startup elicitation")),
),
async {
let Some(ClientJsonRpcMessage::Request(request)) = server.receive().await else {
anyhow::bail!("expected discovery");
};
assert!(matches!(request.request, ClientRequest::DiscoverRequest(_)));
let result = DiscoverResult::from_server_info(
vec![ProtocolVersion::V_2026_07_28],
InitializeResult::default(),
);
server
.send(ServerJsonRpcMessage::response(
ServerResult::DiscoverResult(result),
request.id,
))
.await?;
anyhow::Ok(())
},
);
discovery?;
initialized?;
client.enable_request_cancellation();
for mut pending in [
client
.read_resource_with_elicitation(
ReadResourceRequestParams::new("test://pending"),
/*timeout*/ None,
Arc::new(Box::new(|_, _| panic!("unexpected input"))),
)
.map_ok(|_| ())
.boxed(),
client
.send_custom_request("test/pending", /*params*/ None)
.map_ok(|_| ())
.boxed(),
] {
let request = tokio::select! {
result = &mut pending => panic!("request completed before a response: {result:?}"),
message = timeout(Duration::from_secs(5), server.receive()) => message?,
};
let Some(ClientJsonRpcMessage::Request(request)) = request else {
anyhow::bail!("expected pending request");
};
drop(pending);
let Some(ClientJsonRpcMessage::Notification(notification)) =
timeout(Duration::from_secs(5), server.receive()).await?
else {
anyhow::bail!("expected cancellation");
};
let ClientNotification::CancelledNotification(cancelled) = notification.notification else {
anyhow::bail!("expected cancellation");
};
assert_eq!(cancelled.params.request_id, Some(request.id));
}
client.shutdown().await;
Ok(())
}
#[traced_test]
#[tokio::test]
async fn recovered_connections_accept_elicitations_with_previously_cancelled_ids()
-> anyhow::Result<()> {
for params in [
json!({
"mode": "form",
"message": "Confirm",
"requestedSchema": {"type": "object", "properties": {}},
}),
json!({
"mode": "url",
"message": "Authorize",
"url": "https://example.com/authorize",
"elicitationId": "authorization",
}),
] {
let (servers, mut transport_rx) = mpsc::unbounded_channel();
let (ready_tx, mut server_rx) = mpsc::unbounded_channel();
tokio::spawn(async move {
while let Some(server) = transport_rx.recv().await {
let _ = ready_tx.send(ElicitationTestServer.serve(server).await);
}
});
let client =
RmcpClient::new_in_process_client(Arc::new(ElicitationTestTransport { servers }))
.await?;
client
.initialize(
ClientConfig::default().with_protocol_version(ProtocolVersion::V_2025_06_18),
Some(Duration::from_secs(/*secs*/ 5)),
Box::new(|_, _| {
Box::pin(async {
Ok(ElicitationResponse {
action: ElicitationAction::Accept,
content: None,
meta: None,
})
})
}),
)
.await?;
let server = timeout(Duration::from_secs(/*secs*/ 5), server_rx.recv())
.await?
.unwrap()?;
let reason = format!("late cancellation for {}", params["mode"]);
let request =
ServerRequest::CustomRequest(CustomRequest::new("elicitation/create", Some(params)));
let original = server
.send_request_with_option(request.clone(), PeerRequestOptions::no_options())
.await?;
let id = original.id.clone();
assert_eq!(
serde_json::to_value(
timeout(Duration::from_secs(/*secs*/ 5), original.await_response()).await??
)?,
json!({"action": "accept"}),
);
server
.notify_cancelled(CancelledNotificationParam::new(
Some(id.clone()),
Some(reason.clone()),
))
.await?;
// Notifications run in independent tasks. The handler logs only after recording
// the cancellation, so wait for that acknowledgement before starting recovery.
let handled = format!(
"MCP server cancelled request (request_id: Some({id:?}), reason: Some({reason:?}))"
);
timeout(Duration::from_secs(/*secs*/ 5), async {
while !logs_contain(&handled) {
tokio::task::yield_now().await;
}
})
.await?;
let previous = client.service().await?;
client.reinitialize_after_session_expiry(&previous).await?;
let recovered_server = timeout(Duration::from_secs(/*secs*/ 5), server_rx.recv())
.await?
.unwrap()?;
let recovered = recovered_server
.send_request_with_option(request, PeerRequestOptions::no_options())
.await?;
assert_eq!(recovered.id, id);
assert_eq!(
serde_json::to_value(
timeout(Duration::from_secs(/*secs*/ 5), recovered.await_response()).await??
)?,
json!({"action": "accept"}),
);
client.shutdown().await;
drop(previous);
server.cancel().await?;
recovered_server.cancel().await?;
}
Ok(())
}
#[tokio::test]
async fn ordinary_elicitations_release_pending_responses_on_cancellation() -> anyhow::Result<()> {
for params in [
json!({
"mode": "form",
"message": "Confirm",
"requestedSchema": {"type": "object", "properties": {}},
}),
json!({
"mode": "url",
"message": "Authorize",
"url": "https://example.com/authorize",
"elicitationId": "authorization",
}),
] {
let pause_state = ElicitationPauseState::new();
let mut paused = pause_state.subscribe();
let (route_tx, mut route_rx) = mpsc::unbounded_channel();
let service = ElicitationClientService::new(
ClientConfig::default(),
Box::new(move |_, _| {
let (response_tx, response_rx) = oneshot::channel();
route_tx.send(response_tx).expect("observe elicitation");
Box::pin(async move { Ok(response_rx.await?) })
}),
pause_state,
);
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service, client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
let request =
ServerRequest::CustomRequest(CustomRequest::new("elicitation/create", Some(params)));
server
.send(ServerJsonRpcMessage::request(
request.clone(),
RequestId::Number(1),
))
.await?;
let mut response_tx = timeout(Duration::from_secs(/*secs*/ 5), route_rx.recv())
.await?
.expect("elicitation reached UI without user-verification capability");
assert!(*paused.borrow());
server
.send(ServerJsonRpcMessage::notification(
ServerNotification::CancelledNotification(CancelledNotification::new(
CancelledNotificationParam::new(
Some(RequestId::Number(1)),
/*reason*/ None,
),
)),
))
.await?;
timeout(Duration::from_secs(/*secs*/ 5), response_tx.closed()).await?;
timeout(
Duration::from_secs(/*secs*/ 5),
paused.wait_for(|paused| !*paused),
)
.await??;
server
.send(ServerJsonRpcMessage::request(request, RequestId::Number(2)))
.await?;
let mut response_tx = timeout(Duration::from_secs(/*secs*/ 5), route_rx.recv())
.await?
.expect("connection still accepts elicitations after cancellation");
assert!(*paused.borrow());
client.cancel().await?;
timeout(Duration::from_secs(/*secs*/ 5), response_tx.closed()).await?;
timeout(
Duration::from_secs(/*secs*/ 5),
paused.wait_for(|paused| !*paused),
)
.await??;
}
Ok(())
}
#[tokio::test(start_paused = true)]
async fn transport_eof_releases_pending_elicitations_without_dropping_client() -> anyhow::Result<()>
{
for (method, params) in [
(
"elicitation/create",
json!({
"mode": "form",
"message": "Confirm",
"requestedSchema": {"type": "object", "properties": {}},
}),
),
(
"openai/elicitation/create",
json!({
"mode": "openai/userVerification",
"title": "Approve",
"description": "",
"challenge": "AQID",
}),
),
] {
let pause_state = ElicitationPauseState::new();
let mut paused = pause_state.subscribe();
let (route_tx, mut route_rx) = mpsc::unbounded_channel();
let mut client_info = ClientConfig::default();
client_info.capabilities.extensions = Some(
[(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
serde_json::Map::from_iter([("userVerification".to_string(), json!({}))]),
)]
.into_iter()
.collect(),
);
let service = ElicitationClientService::new(
client_info,
Box::new(move |_, _| {
let (response_tx, response_rx) = oneshot::channel();
route_tx
.send(response_tx)
.expect("observe pending elicitation");
Box::pin(async move { Ok(response_rx.await?) })
}),
pause_state,
);
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service, client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
// A server can request approval without an outgoing tools/call to detect EOF.
server
.send(serde_json::from_value::<ServerJsonRpcMessage>(json!({
"jsonrpc": "2.0", "id": 1, "method": method, "params": params,
}))?)
.await?;
let mut response_tx = timeout(Duration::from_secs(/*secs*/ 5), route_rx.recv())
.await?
.expect("elicitation reached the UI");
assert!(*paused.borrow());
drop(server);
// RMCP allows five seconds to drain responses after EOF. Retain the client
// throughout cleanup: dropping it would cancel the handler and hide the bug.
timeout(Duration::from_secs(/*secs*/ 7), response_tx.closed()).await?;
timeout(
Duration::from_secs(/*secs*/ 1),
paused.wait_for(|paused| !*paused),
)
.await??;
// Only consume the retained client after observing handler cleanup.
let reason = timeout(Duration::from_secs(/*secs*/ 1), client.waiting()).await??;
assert!(matches!(reason, QuitReason::Closed));
}
Ok(())
}
#[tokio::test]
async fn user_verification_service_cancellation_drops_pending_response() -> anyhow::Result<()> {
let pause_state = ElicitationPauseState::new();
let mut paused = pause_state.subscribe();
let (route_tx, mut route_rx) = mpsc::unbounded_channel();
let mut client_info = ClientConfig::default();
client_info.capabilities.extensions = Some(
[(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
serde_json::Map::from_iter([("userVerification".to_string(), json!({}))]),
)]
.into_iter()
.collect(),
);
let service = ElicitationClientService::new(
client_info,
Box::new(move |_, _| {
let (response_tx, response_rx) = oneshot::channel();
route_tx
.send(response_tx)
.expect("observe pending verification");
Box::pin(async move { Ok(response_rx.await?) })
}),
pause_state,
);
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service, client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
server
.send(ServerJsonRpcMessage::request(
ServerRequest::CustomRequest(CustomRequest::new(
"openai/elicitation/create",
Some(json!({
"mode": "openai/userVerification",
"title": "Approve",
"description": "",
"challenge": "AQID",
})),
)),
RequestId::Number(1),
))
.await?;
let mut response_tx = timeout(Duration::from_secs(/*secs*/ 5), route_rx.recv())
.await?
.expect("verification was routed to the UI");
assert!(*paused.borrow());
client.cancel().await?;
timeout(Duration::from_secs(/*secs*/ 5), response_tx.closed()).await?;
timeout(
Duration::from_secs(/*secs*/ 5),
paused.wait_for(|paused| !*paused),
)
.await??;
Ok(())
}
#[tokio::test]
async fn cancelling_one_verification_leaves_the_mcp_connection_and_other_requests_alive()
-> anyhow::Result<()> {
let pause_state = ElicitationPauseState::new();
let mut paused = pause_state.subscribe();
let (route_tx, mut route_rx) = mpsc::unbounded_channel();
let mut client_info = ClientConfig::default();
client_info.capabilities.extensions = Some(
[(
OPENAI_ELICITATION_EXTENSION_ID.to_string(),
serde_json::Map::from_iter([("userVerification".to_string(), json!({}))]),
)]
.into_iter()
.collect(),
);
let service = ElicitationClientService::new(
client_info,
Box::new(move |id, _| {
let (response_tx, response_rx) = oneshot::channel();
route_tx
.send((id, response_tx))
.expect("observe verification");
Box::pin(async move { Ok(response_rx.await?) })
}),
pause_state,
);
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service, client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
for id in [1, 2] {
server
.send(ServerJsonRpcMessage::request(
ServerRequest::CustomRequest(CustomRequest::new(
"openai/elicitation/create",
Some(json!({
"mode": "openai/userVerification",
"title": "Approve",
"description": "",
"challenge": "AQID",
})),
)),
RequestId::Number(id),
))
.await?;
}
let (first_id, mut first) = timeout(Duration::from_secs(/*secs*/ 5), route_rx.recv())
.await?
.expect("first verification reached UI");
let (second_id, second) = timeout(Duration::from_secs(/*secs*/ 5), route_rx.recv())
.await?
.expect("second verification reached UI");
assert_ne!(first_id, second_id);
assert!(*paused.borrow());
server
.send(ServerJsonRpcMessage::notification(
ServerNotification::CancelledNotification(CancelledNotification::new(
CancelledNotificationParam::new(Some(first_id.clone()), None),
)),
))
.await?;
timeout(Duration::from_secs(/*secs*/ 5), first.closed()).await?;
assert!(!second.is_closed());
assert!(*paused.borrow());
for request_id in [first_id, RequestId::Number(999)] {
server
.send(ServerJsonRpcMessage::notification(
ServerNotification::CancelledNotification(CancelledNotification::new(
CancelledNotificationParam::new(Some(request_id), None),
)),
))
.await?;
}
assert!(!second.is_closed());
second
.send(ElicitationResponse {
action: ElicitationAction::Accept,
content: Some(json!({"credentialId": "AQID", "signature": "BAUG"})),
meta: None,
})
.expect("second verification remains pending");
let accepted = timeout(Duration::from_secs(/*secs*/ 5), server.receive())
.await?
.expect("second request survived cancellation");
let ClientJsonRpcMessage::Response(accepted) = accepted else {
anyhow::bail!("expected the second verification response");
};
assert_eq!(accepted.id, second_id);
assert_eq!(serde_json::to_value(accepted.result)?["action"], "accept");
timeout(
Duration::from_secs(/*secs*/ 5),
paused.wait_for(|paused| !*paused),
)
.await??;
client.cancel().await?;
Ok(())
}

View File

@@ -0,0 +1,216 @@
use super::*;
use pretty_assertions::assert_eq;
use rmcp::RoleServer;
use rmcp::model::ClientJsonRpcMessage;
use rmcp::model::ServerJsonRpcMessage;
use rmcp::service::serve_directly;
use rmcp::transport::IntoTransport;
use rmcp::transport::Transport;
use serde_json::json;
use std::time::Duration;
use tokio::time::timeout;
fn service() -> ElicitationClientService {
let mut info = ClientConfig::default();
info.capabilities.extensions = Some(
[(
OPENAI_ELICITATION_EXTENSION_ID.into(),
Map::from_iter([("userVerification".into(), json!({}))]),
)]
.into_iter()
.collect(),
);
ElicitationClientService::new(
info,
Box::new(|_, _| panic!("cancelled or malformed verification must not reach the UI")),
ElicitationPauseState::new(),
)
}
#[tokio::test]
async fn user_verification_dispatch_preserves_context_metadata() -> anyhow::Result<()> {
let mut service = service();
service.send_elicitation = Arc::new(Box::new(|_, request| {
assert_eq!(
request,
Elicitation::UserVerification {
meta: Some(json!({"example/display": {"label": "Operation"}})),
title: "Approve".into(),
description: "Review operation".into(),
challenge: "AQID".into(),
}
);
Box::pin(async {
Ok(ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: None,
})
})
}));
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service, client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
server
.send(serde_json::from_value::<ServerJsonRpcMessage>(json!({
"jsonrpc": "2.0", "id": 1, "method": OPENAI_ELICITATION_METHOD,
"params": {
"mode": crate::user_verification::MODE,
"title": "Approve", "description": "Review operation", "challenge": "AQID",
"_meta": {"progressToken": 7, "example/display": {"label": "Operation"}}
}
}))?)
.await?;
let response = timeout(Duration::from_secs(/*secs*/ 5), server.receive())
.await?
.unwrap();
assert_eq!(
serde_json::to_value(response)?,
json!({"jsonrpc": "2.0", "id": 1, "result": {"action": "cancel"}})
);
client.cancel().await?;
Ok(())
}
#[tokio::test]
async fn user_verification_remembers_cancellation_before_request_handler_runs() -> anyhow::Result<()>
{
let service = service();
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service.clone(), client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
server
.send(serde_json::from_value::<ServerJsonRpcMessage>(json!({
"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 1}
}))?)
.await?;
// Force the scheduling order that RMCP's independently spawned handlers allow.
timeout(Duration::from_secs(/*secs*/ 5), async {
loop {
if service
.pending_verifications
.lock()
.unwrap()
.early
.contains(&RequestId::Number(1))
{
break;
}
tokio::task::yield_now().await;
}
})
.await?;
server.send(serde_json::from_value::<ServerJsonRpcMessage>(json!({
"jsonrpc": "2.0", "id": 1, "method": OPENAI_ELICITATION_METHOD,
"params": {"mode": crate::user_verification::MODE, "title": "Approve", "description": "", "challenge": "AQID"}
}))?).await?;
let response = timeout(Duration::from_secs(/*secs*/ 5), server.receive())
.await?
.unwrap();
assert_eq!(
serde_json::to_value(response)?,
json!({
"jsonrpc": "2.0", "id": 1, "result": {
"action": "cancel", "_meta": {"openai/userVerificationReason": "interrupted"}
}
})
);
assert!(
service
.pending_verifications
.lock()
.unwrap()
.early
.is_empty()
);
client.cancel().await?;
Ok(())
}
#[tokio::test]
async fn user_verification_early_cancellation_storage_fails_closed_at_capacity()
-> anyhow::Result<()> {
let service = service();
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service.clone(), client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
for id in 0..=MAX_EARLY_CANCELLATIONS {
server
.send(serde_json::from_value::<ServerJsonRpcMessage>(json!({
"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": id}
}))?)
.await?;
}
timeout(Duration::from_secs(/*secs*/ 5), async {
while !service.pending_verifications.lock().unwrap().saturated {
tokio::task::yield_now().await;
}
})
.await?;
assert!(
service
.pending_verifications
.lock()
.unwrap()
.early
.is_empty()
);
let response = service.handle_request(
ServerRequest::CustomRequest(CustomRequest::new(OPENAI_ELICITATION_METHOD, Some(json!({
"mode": crate::user_verification::MODE, "title": "Approve", "description": "", "challenge": "AQID"
})))),
RequestContext::new(RequestId::Number(5000), client.peer().clone()),
).await?;
assert_eq!(
serde_json::to_value(response)?,
json!({
"action": "cancel", "_meta": {"openai/userVerificationReason": "approvalUnavailable"}
})
);
// Ordinary requests still work after verification fails closed.
server
.send(serde_json::from_value::<ServerJsonRpcMessage>(json!({
"jsonrpc": "2.0", "id": 5001, "method": "ping"
}))?)
.await?;
let response = timeout(Duration::from_secs(/*secs*/ 5), server.receive())
.await?
.unwrap();
assert_eq!(
serde_json::to_value(response)?,
json!({"jsonrpc": "2.0", "id": 5001, "result": {}})
);
client.cancel().await?;
Ok(())
}
#[tokio::test]
async fn user_verification_dispatch_rejects_malformed_modes_as_invalid_params() -> anyhow::Result<()>
{
let (client_transport, server_transport) = tokio::io::duplex(/*max_buf_size*/ 4096);
let client = serve_directly(service(), client_transport, /*peer_info*/ None);
let mut server = IntoTransport::<RoleServer, _, _>::into_transport(server_transport);
for params in [json!({}), json!({"mode": 7}), json!({"mode": "unknown"})] {
server
.send(ServerJsonRpcMessage::request(
ServerRequest::CustomRequest(CustomRequest::new(
OPENAI_ELICITATION_METHOD,
Some(params),
)),
RequestId::Number(1),
))
.await?;
let response = timeout(Duration::from_secs(/*secs*/ 5), server.receive())
.await?
.unwrap();
let ClientJsonRpcMessage::Error(response) = response else {
anyhow::bail!("expected invalid params");
};
assert_eq!(
response.error,
rmcp::ErrorData::invalid_params("invalid elicitation mode", /*data*/ None)
);
}
client.cancel().await?;
Ok(())
}

View File

@@ -0,0 +1,163 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn user_verification_request_preserves_signed_bytes_and_display_text() {
assert_eq!(
parse_request(CustomRequest::new(
"openai/elicitation/create",
Some(json!({
"mode": MODE,
"title": "Approve purchase",
"description": "Pay $200 to Example Store",
"challenge": "AQID",
})),
))
.unwrap(),
Elicitation::UserVerification {
meta: None,
title: "Approve purchase".to_string(),
description: "Pay $200 to Example Store".to_string(),
challenge: "AQID".to_string(),
}
);
}
#[test]
fn user_verification_request_metadata_matches_mcp_elicitation() {
for meta in [
None,
Some(json!(null)),
Some(json!({})),
Some(json!({"example/display": {"label": "Operation", "details": [1, true, null]}})),
Some(json!(true)),
Some(json!(7)),
Some(json!("scalar")),
Some(json!([])),
] {
let mut params = json!({
"mode": MODE,
"title": "Approve",
"description": "Review operation",
"challenge": "AQID",
});
let mut mcp_params = json!({
"mode": "form",
"message": "Approve",
"requestedSchema": {"type": "object", "properties": {}},
});
if let Some(meta) = &meta {
params["_meta"] = meta.clone();
mcp_params["_meta"] = meta.clone();
}
let mcp_request = serde_json::from_value::<rmcp::model::ElicitRequestParams>(mcp_params);
let expected = if mcp_request.is_ok() {
Ok(Elicitation::UserVerification {
meta: meta.filter(serde_json::Value::is_object),
title: "Approve".into(),
description: "Review operation".into(),
challenge: "AQID".into(),
})
} else {
Err(invalid_request())
};
assert_eq!(
parse_request(CustomRequest::new(
"openai/elicitation/create",
Some(params),
)),
expected,
);
}
}
#[test]
fn user_verification_rejects_invalid_or_unbounded_requests_without_echoing_values() {
for (field, value) in [
("mode", json!("unknown")),
("title", json!("")),
("title", json!("x".repeat(257))),
("description", json!("x".repeat(4097))),
("challenge", json!("")),
("challenge", json!("not base64url!")),
("challenge", json!(URL_SAFE_NO_PAD.encode(vec![0; 4097]))),
("unexpected", json!("secret")),
] {
let mut params = json!({
"mode": MODE, "title": "Approve", "description": "", "challenge": "AQID"
});
params[field] = value;
assert_eq!(
parse_request(CustomRequest::new(
"openai/elicitation/create",
Some(params)
)),
Err(invalid_request()),
);
}
}
#[test]
fn user_verification_acceptance_returns_proof_only_in_content() {
let content = Some(json!({"credentialId": "credential:用户/1=", "signature": "BAUG"}));
assert_eq!(
validate_response(ElicitationResponse {
action: ElicitationAction::Accept,
content: content.clone(),
meta: Some(json!({"untrusted": "ignored"})),
}),
ElicitationResponse {
action: ElicitationAction::Accept,
content,
meta: None,
}
);
}
#[test]
fn user_verification_cancels_acceptance_without_a_valid_bounded_proof() {
for content in [
None,
Some(json!({})),
Some(json!({"credentialId": "AQID", "signature": ""})),
Some(json!({"credentialId": "AQID", "signature": "BAUG="})),
Some(json!({"credentialId": "é".repeat(513), "signature": "BAUG"})),
Some(json!({"credentialId": "", "signature": "BAUG"})),
Some(json!({"credentialId": "AQID", "signature": URL_SAFE_NO_PAD.encode(vec![0; 129])})),
Some(json!({"credentialId": "AQID", "signature": "BAUG", "extra": true})),
] {
assert_eq!(
validate_response(ElicitationResponse {
action: ElicitationAction::Accept,
content,
meta: Some(json!({"openai/userVerificationReason": "userCancelled"})),
}),
ElicitationResponse {
action: ElicitationAction::Cancel,
content: None,
meta: Some(json!({"openai/userVerificationReason": "invalidProof"})),
}
);
}
}
#[test]
fn user_verification_decline_and_cancel_discard_proof_material() {
for action in [ElicitationAction::Decline, ElicitationAction::Cancel] {
assert_eq!(
validate_response(ElicitationResponse {
action: action.clone(),
content: Some(json!({"credentialId": "AQID", "signature": "BAUG"})),
meta: Some(
json!({"secret": "discarded", "openai/userVerificationReason": "timeout"})
),
}),
ElicitationResponse {
action,
content: None,
meta: Some(json!({"openai/userVerificationReason": "timeout"}))
}
);
}
}

View File

@@ -0,0 +1,357 @@
use anyhow::Result;
use anyhow::anyhow;
use codex_config::types::McpServerEnvVar;
use codex_network_proxy::CUSTOM_CA_ENV_KEYS;
use codex_protocol::shell_environment::is_non_inheritable_env_var;
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use http::header::USER_AGENT;
use std::collections::HashMap;
use std::env;
use std::ffi::OsString;
pub(crate) const MCP_USER_AGENT: &str = concat!("codex-mcp-client/", env!("CARGO_PKG_VERSION"));
pub(crate) fn create_env_for_mcp_server(
extra_env: Option<HashMap<OsString, OsString>>,
env_vars: &[McpServerEnvVar],
) -> Result<HashMap<OsString, OsString>> {
let additional_env_vars = local_stdio_env_var_names(env_vars)?;
let mut env: HashMap<OsString, OsString> = DEFAULT_ENV_VARS
.iter()
.copied()
.chain(additional_env_vars)
.filter_map(|var| env::var_os(var).map(|value| (OsString::from(var), value)))
.collect();
for name in CUSTOM_CA_ENV_KEYS {
let Some(value) = env::var_os(name) else {
continue;
};
if value.is_empty() {
continue;
}
let value = std::path::absolute(value)?.into_os_string();
#[cfg(windows)]
env.retain(|key, _| !key.to_string_lossy().eq_ignore_ascii_case(name));
env.insert(OsString::from(name), value);
}
for (name, value) in extra_env.unwrap_or_default() {
if cfg!(windows)
|| name.to_str().is_some_and(|name| {
CUSTOM_CA_ENV_KEYS
.iter()
.any(|ca_name| ca_name.eq_ignore_ascii_case(name))
})
{
env.retain(|key, _| {
!key.to_string_lossy()
.eq_ignore_ascii_case(&name.to_string_lossy())
});
}
env.insert(name, value);
}
env.retain(|name, _| {
name.to_str()
.is_none_or(|name| !is_non_inheritable_env_var(name))
});
Ok(env)
}
pub(crate) fn create_env_overlay_for_remote_mcp_server(
extra_env: Option<HashMap<OsString, OsString>>,
env_vars: &[McpServerEnvVar],
) -> HashMap<OsString, OsString> {
// Remote stdio should inherit PATH/HOME/etc. from the executor side, not
// from the orchestrator process. Only forward variables explicitly named
// by the MCP config plus literal env overrides from that config.
let mut env: HashMap<OsString, OsString> = env_vars
.iter()
.filter(|var| !var.is_remote_source())
.filter_map(|var| env::var_os(var.name()).map(|value| (OsString::from(var.name()), value)))
.chain(extra_env.unwrap_or_default())
.collect();
env.retain(|name, _| {
name.to_str()
.is_none_or(|name| !is_non_inheritable_env_var(name))
});
env
}
pub(crate) fn remote_mcp_env_var_names(env_vars: &[McpServerEnvVar]) -> Vec<String> {
env_vars
.iter()
.filter(|var| var.is_remote_source())
.filter(|var| !is_non_inheritable_env_var(var.name()))
.map(|var| var.name().to_string())
.collect()
}
fn local_stdio_env_var_names(env_vars: &[McpServerEnvVar]) -> Result<impl Iterator<Item = &str>> {
if let Some(remote_var) = env_vars.iter().find(|var| var.is_remote_source()) {
return Err(anyhow!(
"env_vars entry `{}` uses source `remote`, which requires remote MCP stdio",
remote_var.name()
));
}
Ok(env_vars
.iter()
.map(McpServerEnvVar::name)
.filter(|name| !is_non_inheritable_env_var(name)))
}
pub(crate) fn build_default_headers(
http_headers: Option<HashMap<String, String>>,
env_http_headers: Option<HashMap<String, String>>,
) -> Result<HeaderMap> {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static(MCP_USER_AGENT));
if let Some(static_headers) = http_headers {
for (name, value) in static_headers {
let header_name = match HeaderName::from_bytes(name.as_bytes()) {
Ok(name) => name,
Err(err) => {
tracing::warn!("invalid HTTP header name `{name}`: {err}");
continue;
}
};
let header_value = match HeaderValue::from_str(value.as_str()) {
Ok(value) => value,
Err(err) => {
tracing::warn!("invalid HTTP header value for `{name}`: {err}");
continue;
}
};
headers.insert(header_name, header_value);
}
}
if let Some(env_headers) = env_http_headers {
for (name, env_var) in env_headers {
if let Ok(value) = env::var(&env_var) {
if value.trim().is_empty() {
continue;
}
let header_name = match HeaderName::from_bytes(name.as_bytes()) {
Ok(name) => name,
Err(err) => {
tracing::warn!("invalid HTTP header name `{name}`: {err}");
continue;
}
};
let header_value = match HeaderValue::from_str(value.as_str()) {
Ok(value) => value,
Err(err) => {
tracing::warn!(
"invalid HTTP header value read from {env_var} for `{name}`: {err}"
);
continue;
}
};
headers.insert(header_name, header_value);
}
}
}
Ok(headers)
}
#[cfg(unix)]
pub(crate) const DEFAULT_ENV_VARS: &[&str] = &[
"HOME",
"LOGNAME",
"PATH",
"SHELL",
"USER",
"__CF_USER_TEXT_ENCODING",
"LANG",
"LC_ALL",
"TERM",
"TMPDIR",
"TZ",
];
#[cfg(windows)]
pub(crate) const DEFAULT_ENV_VARS: &[&str] =
codex_protocol::shell_environment::WINDOWS_CORE_ENV_VARS;
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serial_test::serial;
use std::ffi::OsStr;
struct EnvVarGuard {
key: String,
original: Option<OsString>,
}
impl EnvVarGuard {
fn set(key: &str, value: impl AsRef<OsStr>) -> Self {
let original = std::env::var_os(key);
unsafe {
std::env::set_var(key, value.as_ref());
}
Self {
key: key.to_string(),
original,
}
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
if let Some(value) = &self.original {
unsafe {
std::env::set_var(&self.key, value);
}
} else {
unsafe {
std::env::remove_var(&self.key);
}
}
}
}
#[tokio::test]
async fn create_env_honors_overrides() {
let value = "custom".to_string();
let expected = OsString::from(&value);
let env = create_env_for_mcp_server(
Some(HashMap::from([
(OsString::from("TZ"), expected.clone()),
(
OsString::from("openai_identity_token_file"),
OsString::from("/run/identity-token"),
),
])),
&[],
)
.expect("local MCP env should build");
assert_eq!(env.get(OsStr::new("TZ")), Some(&expected));
assert!(!env.contains_key(OsStr::new("openai_identity_token_file")));
}
#[test]
#[serial(extra_rmcp_env)]
fn create_env_includes_additional_whitelisted_variables() {
let custom_var = "EXTRA_RMCP_ENV";
let value = "from-env";
let expected = OsString::from(value);
let _guard = EnvVarGuard::set(custom_var, value);
let env = create_env_for_mcp_server(/*extra_env*/ None, &[custom_var.into()])
.expect("local MCP env should build");
assert_eq!(env.get(OsStr::new(custom_var)), Some(&expected));
}
#[test]
#[serial(extra_rmcp_env)]
fn create_remote_env_overlay_only_forwards_explicit_variables() {
let default_var = DEFAULT_ENV_VARS[0];
let custom_var = "EXTRA_REMOTE_RMCP_ENV";
let custom_value = OsString::from("from-env");
let _default_guard = EnvVarGuard::set(default_var, "from-default");
let _custom_guard = EnvVarGuard::set(custom_var, &custom_value);
let env = create_env_overlay_for_remote_mcp_server(
Some(HashMap::from([(
OsString::from("OpenAI_Federation_Rule_Id"),
OsString::from("rule"),
)])),
&[custom_var.into()],
);
assert_eq!(
env,
HashMap::from([(OsString::from(custom_var), custom_value)])
);
}
#[test]
#[serial(extra_rmcp_env)]
fn create_remote_env_overlay_does_not_copy_remote_source_variables() {
let remote_var = "REMOTE_ONLY_RMCP_ENV";
let local_var = "LOCAL_RMCP_ENV";
let local_value = OsString::from("from-local-env");
let _remote_guard = EnvVarGuard::set(remote_var, "should-not-be-copied");
let _local_guard = EnvVarGuard::set(local_var, &local_value);
let env = create_env_overlay_for_remote_mcp_server(
/*extra_env*/ None,
&[
McpServerEnvVar::Config {
name: remote_var.to_string(),
source: Some("remote".to_string()),
},
McpServerEnvVar::Config {
name: local_var.to_string(),
source: Some("local".to_string()),
},
],
);
assert_eq!(
env,
HashMap::from([(OsString::from(local_var), local_value)])
);
}
#[test]
fn remote_mcp_env_var_names_returns_remote_source_names() {
let names = remote_mcp_env_var_names(&[
"LEGACY".into(),
McpServerEnvVar::Config {
name: "LOCAL".to_string(),
source: Some("local".to_string()),
},
McpServerEnvVar::Config {
name: "REMOTE".to_string(),
source: Some("remote".to_string()),
},
McpServerEnvVar::Config {
name: "openai_identity_token_file".to_string(),
source: Some("remote".to_string()),
},
]);
assert_eq!(names, vec!["REMOTE".to_string()]);
}
#[test]
fn create_local_env_rejects_remote_source_variables() {
let err = create_env_for_mcp_server(
/*extra_env*/ None,
&[McpServerEnvVar::Config {
name: "REMOTE".to_string(),
source: Some("remote".to_string()),
}],
)
.expect_err("remote source should require remote stdio");
assert!(
err.to_string().contains("requires remote MCP stdio"),
"unexpected error: {err}"
);
}
#[cfg(unix)]
#[test]
#[serial(extra_rmcp_env)]
fn create_env_preserves_path_when_it_is_not_utf8() {
use std::os::unix::ffi::OsStrExt;
let raw_path = std::ffi::OsStr::from_bytes(b"/tmp/codex-\xFF/bin");
let expected = raw_path.to_os_string();
let _guard = EnvVarGuard::set("PATH", raw_path);
let env =
create_env_for_mcp_server(/*extra_env*/ None, &[]).expect("local MCP env should build");
assert_eq!(env.get(OsStr::new("PATH")), Some(&expected));
}
}

View File

@@ -0,0 +1,233 @@
use codex_exec_server::HttpHeader;
use http::header::WWW_AUTHENTICATE;
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct InsufficientScopeChallenge {
pub(crate) www_authenticate_header: String,
pub(crate) required_scope: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
struct BearerInsufficientScope {
required_scope: Option<String>,
}
type AuthParameter<'a> = (&'a str, Option<String>);
type ChallengeStart<'a> = (&'a str, Option<AuthParameter<'a>>);
#[derive(Default)]
enum Parameter {
#[default]
Missing,
Value(String),
Invalid,
}
#[derive(Default)]
struct BearerChallenge {
error: Parameter,
scope: Parameter,
}
impl BearerChallenge {
fn add_parameter(&mut self, name: &str, value: Option<String>) {
let parameter = if name.eq_ignore_ascii_case("error") {
&mut self.error
} else if name.eq_ignore_ascii_case("scope") {
&mut self.scope
} else {
return;
};
*parameter = match (&*parameter, value) {
(Parameter::Missing, Some(value)) => Parameter::Value(value),
(Parameter::Missing, None) | (Parameter::Value(_), _) | (Parameter::Invalid, _) => {
Parameter::Invalid
}
};
}
fn into_insufficient_scope(self) -> Option<BearerInsufficientScope> {
match self.error {
Parameter::Value(error) if error == "insufficient_scope" => {
Some(BearerInsufficientScope {
required_scope: match self.scope {
Parameter::Value(scope) if valid_scope(&scope) => Some(scope),
Parameter::Missing | Parameter::Value(_) | Parameter::Invalid => None,
},
})
}
Parameter::Missing | Parameter::Value(_) | Parameter::Invalid => None,
}
}
}
/// Finds a Bearer insufficient-scope challenge among all `WWW-Authenticate`
/// response header field values.
pub(crate) fn insufficient_scope_challenge(
headers: &[HttpHeader],
) -> Option<InsufficientScopeChallenge> {
headers
.iter()
.filter(|header| header.name.eq_ignore_ascii_case(WWW_AUTHENTICATE.as_str()))
.find_map(|header| {
parse_bearer_insufficient_scope(&header.value).map(|challenge| {
InsufficientScopeChallenge {
www_authenticate_header: header.value.clone(),
required_scope: challenge.required_scope,
}
})
})
}
/// Parses a Bearer `WWW-Authenticate` challenge with an `insufficient_scope`
/// error and extracts its optional required scope.
///
/// RFC 9110 section 11.2 defines challenge parameters as `auth-param` values
/// whose values are either `token` or `quoted-string`. Quoted strings use HTTP
/// syntax rather than JSON: section 5.6.4 requires recipients to replace each
/// `quoted-pair` with its escaped octet.
///
/// RFC 6750 section 3 permits `scope` in the Bearer challenge at most once.
/// After HTTP quoted-string processing, each scope token can contain `%x21`,
/// `%x23-5B`, or `%x5D-7E`, with `%x20` separating multiple tokens. Therefore
/// returned scopes cannot contain `"` or `\`, even when those characters occur
/// in the header encoding.
///
/// RMCP has related parsing logic, but it is private to that crate.
fn parse_bearer_insufficient_scope(header: &str) -> Option<BearerInsufficientScope> {
let segments = split_unquoted_segments(header)?;
let mut bearer_challenge: Option<BearerChallenge> = None;
for segment in segments {
if let Some((name, value)) = parse_auth_param(segment) {
if let Some(challenge) = bearer_challenge.as_mut() {
challenge.add_parameter(name, value);
}
continue;
}
if let Some(challenge) = bearer_challenge
.take()
.and_then(BearerChallenge::into_insufficient_scope)
{
return Some(challenge);
}
let (scheme, parameter) = parse_challenge_start(segment)?;
if scheme.eq_ignore_ascii_case("Bearer") {
let mut challenge = BearerChallenge::default();
if let Some((name, value)) = parameter {
challenge.add_parameter(name, value);
}
bearer_challenge = Some(challenge);
}
}
bearer_challenge.and_then(BearerChallenge::into_insufficient_scope)
}
fn parse_challenge_start(segment: &str) -> Option<ChallengeStart<'_>> {
let segment = segment.trim();
let parameter_start = segment.find(char::is_whitespace);
let (scheme, parameter) = match parameter_start {
Some(parameter_start) => (
&segment[..parameter_start],
parse_auth_param(&segment[parameter_start..]),
),
None => (segment, None),
};
is_http_token(scheme).then_some((scheme, parameter))
}
fn parse_auth_param(segment: &str) -> Option<AuthParameter<'_>> {
let (name, value) = segment.trim().split_once('=')?;
let name = name.trim();
is_http_token(name).then_some((name, parse_auth_param_value(value.trim())))
}
fn parse_auth_param_value(value: &str) -> Option<String> {
if let Some(quoted_value) = value.strip_prefix('"') {
let quoted_value = quoted_value.strip_suffix('"')?;
let mut decoded = String::with_capacity(quoted_value.len());
let mut characters = quoted_value.chars();
while let Some(character) = characters.next() {
if character == '\\' {
decoded.push(characters.next()?);
} else {
decoded.push(character);
}
}
Some(decoded)
} else {
is_http_token(value).then(|| value.to_string())
}
}
fn split_unquoted_segments(header: &str) -> Option<Vec<&str>> {
let mut segments = Vec::new();
let mut segment_start = 0;
let mut in_quotes = false;
let mut escaped = false;
for (position, character) in header.char_indices() {
if escaped {
escaped = false;
continue;
}
match character {
'\\' if in_quotes => escaped = true,
'"' => in_quotes = !in_quotes,
',' | ';' if !in_quotes => {
segments.push(&header[segment_start..position]);
segment_start = position + character.len_utf8();
}
_ => {}
}
}
if in_quotes || escaped {
None
} else {
segments.push(&header[segment_start..]);
Some(segments)
}
}
fn valid_scope(scope: &str) -> bool {
scope.split(' ').all(|token| {
!token.is_empty()
&& token
.bytes()
.all(|byte| matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~'))
})
}
fn is_http_token(value: &str) -> bool {
!value.is_empty()
&& value.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
)
})
}
#[cfg(test)]
#[path = "www_authenticate_tests.rs"]
mod tests;

View File

@@ -0,0 +1,126 @@
use codex_exec_server::HttpHeader;
use pretty_assertions::assert_eq;
use super::BearerInsufficientScope;
use super::InsufficientScopeChallenge;
use super::insufficient_scope_challenge;
use super::parse_bearer_insufficient_scope;
#[test]
fn extracts_scope_from_bearer_insufficient_scope_challenges() {
let cases = [
(
r#"Bearer error="insufficient_scope", scope="files:read files:write""#,
"files:read files:write",
),
(
r#"Bearer error="insufficient_scope", ScOpE = "files:read""#,
"files:read",
),
(
r#"Bearer scope="read:data", error="insufficient_scope""#,
"read:data",
),
(r#"Bearer error="insufficient_scope", scope=read"#, "read"),
(
r#"Bearer error="insufficient_scope", scope="files:read\ files:write""#,
"files:read files:write",
),
(
r#"Bearer error="insufficient_scope", error_description="request scope=admin, not \"root\"", scope="files:read""#,
"files:read",
),
(
r#"Basic realm="example", Bearer error="insufficient_scope", scope="files:read""#,
"files:read",
),
(
r#"Newauth scope="wrong", Bearer error="insufficient_scope", scope="files:read""#,
"files:read",
),
];
for (header, expected_scope) in cases {
assert_eq!(
parse_bearer_insufficient_scope(header),
Some(BearerInsufficientScope {
required_scope: Some(expected_scope.to_string()),
}),
"header: {header}"
);
}
}
#[test]
fn does_not_treat_other_bearer_errors_as_insufficient_scope() {
assert_eq!(
parse_bearer_insufficient_scope(r#"Bearer error="invalid_token", scope="files:read""#),
None
);
}
#[test]
fn rejects_invalid_or_ambiguous_scope_parameters() {
let cases = [
r#"Bearer error="insufficient_scope", scope="#,
r#"Bearer error="insufficient_scope", scope="read\"write""#,
r#"Bearer error="insufficient_scope", scope="read\\write""#,
r#"Bearer error="insufficient_scope", scope="read write""#,
r#"Bearer error="insufficient_scope", scope=read:data"#,
r#"Bearer error="insufficient_scope", scope=files:read files:write"#,
r#"Bearer error="insufficient_scope", scope=read=value"#,
r#"Bearer error="insufficient_scope", scope="read", scope="write""#,
];
for header in cases {
assert_eq!(
parse_bearer_insufficient_scope(header),
Some(BearerInsufficientScope {
required_scope: None,
}),
"header: {header}"
);
}
}
#[test]
fn ignores_scope_text_outside_a_scope_parameter() {
let cases = [
r#"Bearer error_description="request scope=admin""#,
r#"Bearer resource_scope="admin""#,
r#"Bearer "scope=admin""#,
r#"Bearer error_description="unterminated scope=admin"#,
];
for header in cases {
assert_eq!(
parse_bearer_insufficient_scope(header),
None,
"header: {header}"
);
}
}
#[test]
fn selects_bearer_challenge_from_a_later_www_authenticate_field_value() {
let headers = vec![
HttpHeader {
name: "www-authenticate".to_string(),
value: r#"Basic realm="example""#.to_string(),
value_env_var: None,
},
HttpHeader {
name: "WWW-Authenticate".to_string(),
value: r#"Bearer error="insufficient_scope", scope="files:read""#.to_string(),
value_env_var: None,
},
];
assert_eq!(
insufficient_scope_challenge(&headers),
Some(InsufficientScopeChallenge {
www_authenticate_header: headers[1].value.clone(),
required_scope: Some("files:read".to_string()),
})
);
}