Drop the claude.ai CORS grant from /mcp and the raw plan bytes from operations.get_plan

The connector check does not run in the browser: claude.ai connects from
Anthropic's servers on port 443 only, so CORS did not help. Clients connect
locally with a bearer header. The JSON 401 with a Bearer challenge and the
2025-06-18 negotiation stay. MCP plan previews keep plan_payload and
plan_hash and omit the byte array the WebUI uses for its exact comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 14:45:05 +01:00
co-authored by Claude Opus 5.5
parent 06c4b5a9aa
commit 9cd1bf1a6c
+18 -90
View File
@@ -3,7 +3,7 @@
use axum::{
Json, Router,
extract::{Request, State},
http::{HeaderMap, HeaderValue, Method, StatusCode},
http::{HeaderMap, HeaderValue, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
};
@@ -399,7 +399,13 @@ impl Adapter {
}
"operations.get_plan" => {
let i: GetPlan = parse(args)?;
crate::jobs::plan_preview(&self.state, &p, i.tenant_id, i.plan_id).await
// The WebUI compares these raw bytes; MCP gets plan_payload and plan_hash.
let mut view =
crate::jobs::plan_preview(&self.state, &p, i.tenant_id, i.plan_id).await?;
if let Some(map) = view.as_object_mut() {
map.remove("plan_payload_bytes");
}
Ok(view)
}
"operations.plan" => {
let i: Plan = parse(args)?;
@@ -523,54 +529,8 @@ impl ServerHandler for Adapter {
Ok(match result{Ok(value)=>CallToolResult::structured(value),Err(e)=>CallToolResult::structured_error(json!({"code":e.1,"retryable":e.0.is_server_error(),"message":"tool request failed","correlation_id":Uuid::new_v4(),"details":{}}))}.into())
}
}
/// Browser-based MCP clients, such as the claude.ai connector dialog, send a CORS
/// preflight and an Origin header. MCP authenticates only with a bearer token and
/// never with cookies, so these origins may read responses without credentials.
const BROWSER_ORIGINS: [&str; 1] = ["https://claude.ai"];
const PREFLIGHT_HEADERS: &str =
"authorization, content-type, accept, mcp-protocol-version, mcp-session-id, last-event-id";
const EXPOSED_HEADERS: &str = "mcp-session-id, mcp-protocol-version, www-authenticate";
fn browser_origin(h: &HeaderMap) -> Option<HeaderValue> {
let origin = h.get("origin")?;
BROWSER_ORIGINS
.iter()
.any(|allowed| origin.as_bytes() == allowed.as_bytes())
.then(|| origin.clone())
}
async fn cors(request: Request, next: Next) -> Response {
let origin = browser_origin(request.headers());
let preflight = request.method() == Method::OPTIONS;
let mut response = if preflight {
StatusCode::NO_CONTENT.into_response()
} else {
next.run(request).await
};
let headers = response.headers_mut();
headers.append("vary", HeaderValue::from_static("origin"));
if let Some(origin) = origin {
headers.insert("access-control-allow-origin", origin);
if preflight {
headers.insert(
"access-control-allow-methods",
HeaderValue::from_static("GET, POST, DELETE, OPTIONS"),
);
headers.insert(
"access-control-allow-headers",
HeaderValue::from_static(PREFLIGHT_HEADERS),
);
headers.insert("access-control-max-age", HeaderValue::from_static("600"));
} else {
headers.insert(
"access-control-expose-headers",
HeaderValue::from_static(EXPOSED_HEADERS),
);
}
}
response
}
/// JSON error that the global sanitizer passes through unchanged, so the
/// bearer challenge and CORS headers survive.
/// bearer challenge survives.
fn rejected(status: StatusCode) -> Response {
let mut response = (
status,
@@ -602,19 +562,15 @@ pub fn routes(r: Router<crate::State>, state: crate::State) -> Router<crate::Sta
let s = state.clone();
let origin = state.auth.origin.clone();
let host = origin.trim_start_matches("https://").to_owned();
let origins = std::iter::once(origin)
.chain(BROWSER_ORIGINS.iter().map(|o| format!("{o}:443")))
.collect::<Vec<_>>();
let service = StreamableHttpService::new(
move || Ok(Adapter { state: s.clone() }),
Arc::new(LocalSessionManager::default()),
StreamableHttpServerConfig::default()
.with_allowed_hosts([host])
.with_allowed_origins(origins),
.with_allowed_origins([origin]),
);
r.nest_service("/mcp", service)
.route_layer(middleware::from_fn_with_state(state, guard))
.layer(middleware::from_fn(cors))
}
#[cfg(test)]
@@ -650,44 +606,16 @@ mod tests {
assert!(tools.iter().all(|tool| tool.name != "sessions.request"));
}
#[tokio::test]
async fn browser_clients_get_preflight_and_bearer_challenge() {
let app = Router::new()
.route(
"/mcp",
axum::routing::post(|| async { rejected(StatusCode::UNAUTHORIZED) }),
)
.layer(middleware::from_fn(cors));
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let url = format!("http://{}/mcp", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let client = reqwest::Client::new();
let send = |method: reqwest::Method, origin: &'static str| {
client
.request(method, &url)
.header("origin", origin)
.header("access-control-request-method", "POST")
.send()
};
let preflight = send(reqwest::Method::OPTIONS, "https://claude.ai").await.unwrap();
assert_eq!(preflight.status(), StatusCode::NO_CONTENT);
let h = preflight.headers();
assert_eq!(h["access-control-allow-origin"], "https://claude.ai");
assert!(h["access-control-allow-headers"].to_str().unwrap().contains("authorization"));
assert!(h.get("access-control-allow-credentials").is_none());
let challenge = send(reqwest::Method::POST, "https://claude.ai").await.unwrap();
assert_eq!(challenge.status(), StatusCode::UNAUTHORIZED);
let h = challenge.headers();
assert_eq!(h["access-control-allow-origin"], "https://claude.ai");
#[test]
fn unauthenticated_requests_get_a_json_bearer_challenge() {
let response = rejected(StatusCode::UNAUTHORIZED);
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let h = response.headers();
assert!(h["www-authenticate"].to_str().unwrap().starts_with("Bearer "));
assert!(h["access-control-expose-headers"].to_str().unwrap().contains("www-authenticate"));
assert_eq!(h["content-type"], "application/json");
// Other sites receive no CORS grant, so a browser cannot read the response.
for origin in ["https://evil.example", "https://claude.ai.evil.example", "null"] {
let denied = send(reqwest::Method::OPTIONS, origin).await.unwrap();
assert!(denied.headers().get("access-control-allow-origin").is_none(), "{origin}");
}
server.abort();
assert!(h.get("access-control-allow-origin").is_none());
let forbidden = rejected(StatusCode::FORBIDDEN);
assert!(forbidden.headers().get("www-authenticate").is_none());
}
#[test]