Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,926 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use akode_exec_server::HttpClient;
use akode_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 akode_config::types::AuthKeyringBackendKind;
use akode_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 akode_exec_server::ExecServerError;
use akode_exec_server::HttpRedirectPolicy;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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("AKODE_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(),
"AKODE_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("AKODE_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("AKODE_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 akode_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,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 akode_exec_server::ExecOutputStream;
use akode_exec_server::ExecProcess;
use akode_exec_server::ExecProcessEvent;
use akode_exec_server::ExecProcessEventReceiver;
use akode_exec_server::ProcessId;
use akode_exec_server::ProcessOutputChunk;
use akode_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 akode_exec_server::ExecOutputStream;
use akode_exec_server::ExecProcess;
use akode_exec_server::ExecProcessEventReceiver;
use akode_exec_server::ExecProcessFuture;
use akode_exec_server::ProcessId;
use akode_exec_server::ProcessOutputChunk;
use akode_exec_server::ProcessSignal;
use akode_exec_server::ReadResponse;
use akode_exec_server::WriteResponse;
use akode_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 akode_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<akode_api::SharedAuthProvider, akode_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 akode_api::SharedAuthProvider)
})
}
}
struct SelectedRequestAuth(usize);
impl akode_api::AuthProvider for SelectedRequestAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), akode_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) -> akode_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 akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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 akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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 akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpHeader;
use akode_exec_server::HttpRedirectPolicy;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_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 akode_exec_server::Environment;
use akode_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 akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpHeader;
use akode_exec_server::HttpRedirectPolicy;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
#[cfg(unix)]
use akode_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: akode_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 = akode_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 akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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 akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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 akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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 akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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 akode_api::AuthError;
use akode_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,86 @@
mod auth_status;
mod bounded_stdio_transport;
mod elicitation_client_service;
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 akode_protocol::protocol::McpAuthStatus;
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::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 akode_utils_pty::Child;
use akode_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 akode_utils_pty::ChildStdin;
use akode_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 akode_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,441 @@
//! 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 akode_config::McpServerOAuthConfig;
use akode_config::types::AuthKeyringBackendKind;
use akode_keyring_store::DefaultKeyringStore;
use akode_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) {
// Direct-keyring entries are shared across AKODE_HOMEs, but their
// refresh locks are not. Do not risk overwriting another home's newer login.
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,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 akode_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 = "akode_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 AKODE_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 akode_config::McpServerOAuthConfig;
use akode_keyring_store::DefaultKeyringStore;
use akode_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 akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_keyring_store::KeyringStore;
use akode_otel::auth_storage::AuthStorageOriginator;
use akode_otel::auth_storage::Operation;
use akode_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 akode_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 = "akode_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 AKODE_HOME-backed today: if AKODE_HOME is unset they use
// the default home (`~/.akode`), 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 AKODE_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 akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_otel::auth_storage::AuthStorageOriginator;
use akode_otel::auth_storage::CredentialKind;
use akode_otel::auth_storage::Operation;
use akode_otel::auth_storage::StoragePhase;
use akode_otel::auth_storage::StorageTelemetry;
use akode_otel::auth_storage::Store;
use akode_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 akode_exec_server::HttpClient,
) -> anyhow::Result<()> {
let server = wiremock::MockServer::start().await;
client
.http_request(akode_exec_server::HttpRequestParams {
method: "GET".to_string(),
url: server.uri(),
headers: Vec::new(),
body: None,
timeout_ms: None,
redirect_policy: akode_exec_server::HttpRedirectPolicy::Stop,
request_id: "test-client-warmup".to_string(),
stream_response: false,
})
.await?;
Ok(())
}
/// Serializes tests that mutate process-wide AKODE_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 AKODE_HOME temp dir");
unsafe {
std::env::set_var("AKODE_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("AKODE_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 akode_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 akode_config::types::AuthKeyringBackendKind;
use akode_keyring_store::KeyringStore;
use akode_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 akode_config::types::OAuthCredentialsStoreMode;
const STORE_LOCK_CONTENTION_EVENT_TARGET: &str = "akode_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: akode_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 = "AKODE_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("AKODE_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 akode_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("AKODE_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("AKODE_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: &akode_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<akode_otel::MetricsClient> {
Ok(akode_otel::install_global_metrics(
akode_otel::MetricsClient::new(
akode_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,177 @@
//! 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::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 akode_config::McpServerOAuthConfig;
use akode_config::types::AuthKeyringBackendKind;
use akode_config::types::OAuthCredentialsStoreMode;
use akode_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,
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 akode_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,84 @@
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 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 {
/// Use the advertised Dynamic Client Registration endpoint.
// aKode: upstream preferred a ChatGPT-hosted CIMD here; only DCR is used now.
#[default]
Auto,
/// Client ID Metadata Document registration.
// aKode: always rejected; upstream pointed at a ChatGPT-hosted 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> {
// aKode: CIMD is disabled because its client identifier was a ChatGPT-hosted document.
if client_registration == McpOAuthClientRegistration::Cimd {
bail!("MCP OAuth CIMD client registration is not supported; use dynamic client registration");
}
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 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)?
};
validate_callback_redirect(&redirect_uri, callback_id, callback_mode)?;
// Pre-registered clients never reach this path; rmcp uses the advertised DCR endpoint.
auth_manager.set_metadata(metadata);
let request = AuthorizationRequest::new(redirect_uri.clone())
.with_scopes(scopes.iter().copied())
.with_client_name("Codex");
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,495 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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))
}
// aKode: CIMD (a ChatGPT-hosted client metadata document) is never offered; automatic
// registration always uses DCR, even when the server advertises CIMD support.
#[tokio::test]
async fn automatic_registration_uses_dcr_even_when_cimd_is_advertised() -> Result<()> {
for (host, supports_issuer, expected_redirect) in [
(
"127.0.0.1",
false,
"http://127.0.0.1:43123/callback/abc123ABC_-x",
),
("127.0.0.1", true, "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 (_, query) =
authorization(&server, &redirect, McpOAuthClientRegistration::Auto).await?;
assert_eq!(query["client_id"], "dcr-client");
assert_eq!(query["redirect_uri"], expected_redirect);
assert_eq!(requests_to(&server, "/register").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 explicit_cimd_is_rejected_without_contacting_the_server() {
let valid = "http://127.0.0.1:43123/callback/abc123ABC_-x";
let server = oauth_server(json!({})).await;
let error = authorization(&server, valid, McpOAuthClientRegistration::Cimd)
.await
.err()
.expect("CIMD should be rejected");
assert!(error.to_string().contains("CIMD client registration is not supported"));
assert!(
server
.received_requests()
.await
.expect("mock server should record requests")
.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 akode_exec_server::HttpClient;
use akode_exec_server::HttpHeader;
use akode_exec_server::HttpRedirectPolicy;
use akode_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 akode_exec_server::ExecServerError;
use akode_exec_server::HttpClient;
use akode_exec_server::HttpRequestParams;
use akode_exec_server::HttpRequestResponse;
use akode_exec_server::HttpResponseBodyStream;
use akode_exec_server::RouteAwareHttpClient;
use akode_http_client::HttpClientFactory;
use akode_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 akode_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);
akode_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 AKODE_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,72 @@
use anyhow::Error;
use akode_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::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| {
source
.downcast_ref::<AuthError>()
.is_some_and(auth_error_requires_authentication)
|| 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 akode_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(
akode_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(
akode_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 akode_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(
akode_api::AuthError::Transient("credential refresh unavailable".to_string()),
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::Auth(
akode_api::AuthError::Build("invalid authentication".to_string()),
)),
StreamableHttpError::Client(StreamableHttpClientAdapterError::Auth(
akode_api::AuthError::Policy(akode_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 akode_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 akode_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) = akode_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) = akode_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.
akode_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 akode_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 akode_config::types::McpServerEnvVar;
use akode_network_proxy::CUSTOM_CA_ENV_KEYS;
use akode_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] =
akode_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 akode_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 akode_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()),
})
);
}