use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::*;
use crate::env::Os;
use crate::fs::RealFs;
#[derive(Debug, Clone)]
struct Seen {
method: String,
path: String,
headers: Vec<(String, String)>,
body: String,
}
impl Seen {
fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_str())
}
}
type Route = dyn Fn(&Seen, &str) -> (Vec<u8>, Duration) + Send + Sync;
struct Stub {
base: String,
seen: Arc<Mutex<Vec<Seen>>>,
}
impl Stub {
fn start(route: impl Fn(&Seen, &str) -> (Vec<u8>, Duration) + Send + Sync + 'static) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let seen = Arc::new(Mutex::new(Vec::new()));
let route: Arc<Route> = Arc::new(route);
let (thread_seen, thread_base) = (seen.clone(), base.clone());
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let (seen, route, base) = (thread_seen.clone(), route.clone(), thread_base.clone());
std::thread::spawn(move || {
let Some(request) = read_request(&mut stream) else {
return;
};
seen.lock().unwrap().push(request.clone());
let (answer, hold) = route(&request, &base);
let _ = stream.write_all(&answer);
let _ = stream.flush();
std::thread::sleep(hold);
});
}
});
Self { base, seen }
}
fn url(&self, path: &str) -> String {
format!("{}{path}", self.base)
}
fn seen(&self) -> Vec<Seen> {
self.seen.lock().unwrap().clone()
}
}
fn read_request(stream: &mut std::net::TcpStream) -> Option<Seen> {
let mut data = Vec::new();
let mut buf = [0u8; 4096];
let end = loop {
if let Some(at) = data.windows(4).position(|w| w == b"\r\n\r\n") {
break at + 4;
}
match stream.read(&mut buf) {
Ok(0) | Err(_) => return None,
Ok(n) => data.extend_from_slice(&buf[..n]),
}
};
let head = String::from_utf8_lossy(&data[..end]).into_owned();
let mut lines = head.split("\r\n");
let mut first = lines.next()?.split(' ');
let method = first.next()?.to_owned();
let path = first.next()?.to_owned();
let headers: Vec<(String, String)> = lines
.filter_map(|line| line.split_once(':'))
.map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))
.collect();
let length: usize = headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
.and_then(|(_, v)| v.parse().ok())
.unwrap_or(0);
while data.len() < end + length {
match stream.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => data.extend_from_slice(&buf[..n]),
}
}
let body = String::from_utf8_lossy(&data[end..]).into_owned();
Some(Seen {
method,
path,
headers,
body,
})
}
fn answer(status: &str, headers: &[(&str, &str)], body: &str) -> (Vec<u8>, Duration) {
let mut text = format!("HTTP/1.1 {status}\r\n");
for (name, value) in headers {
text.push_str(&format!("{name}: {value}\r\n"));
}
text.push_str(&format!(
"Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
));
(text.into_bytes(), Duration::ZERO)
}
fn json(status: &str, body: &str) -> (Vec<u8>, Duration) {
answer(status, &[("Content-Type", "application/json")], body)
}
fn not_found() -> (Vec<u8>, Duration) {
answer(
"404 Not Found",
&[("Content-Type", "text/html")],
"<h1>no</h1>",
)
}
fn env() -> Env {
Env::builder(Os::Linux, "/home/me").build()
}
fn run(url: &str) -> AddressCheck {
let parsed = checked_url(url).unwrap();
probe(
&env(),
&parsed,
Duration::from_secs(2),
Duration::from_secs(8),
Vec::new(),
)
}
fn assert_no_credentials(stub: &Stub) {
for seen in stub.seen() {
for name in ["authorization", "cookie", "proxy-authorization"] {
assert!(seen.header(name).is_none(), "{name} sent: {seen:?}");
}
}
}
#[test]
fn oauth_from_the_challenge_with_dynamic_registration() {
let stub = Stub::start(
|seen, base| match (seen.method.as_str(), seen.path.as_str()) {
("POST", "/mcp") => answer(
"401 Unauthorized",
&[(
"WWW-Authenticate",
&format!(
"Bearer realm=\"mcp\", resource_metadata=\"{base}/.well-known/oauth-protected-resource/mcp\", scope=\"a b\""
),
)],
"",
),
("GET", "/.well-known/oauth-protected-resource/mcp") => json(
"200 OK",
&format!(r#"{{"resource":"{base}/mcp","authorization_servers":["{base}"]}}"#),
),
("GET", "/.well-known/oauth-authorization-server") => json(
"200 OK",
&format!(
r#"{{"issuer":"{base}","authorization_endpoint":"{base}/authorize","registration_endpoint":"{base}/register"}}"#
),
),
_ => not_found(),
},
);
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::OAuth, "{check:?}");
assert_eq!(check.status, Some(401));
let oauth = check.oauth.unwrap();
assert_eq!(oauth.authorization_server, stub.base);
assert!(oauth.dynamic_registration && !oauth.client_id_metadata_document);
assert!(oauth.registration_supported());
assert!(
check.detail.contains("dynamic client registration"),
"{}",
check.detail
);
let seen = stub.seen();
assert_eq!(seen[0].header("Mcp-Method"), Some("server/discover"));
assert_eq!(
seen[0].header("MCP-Protocol-Version"),
Some(PROTOCOL_VERSION)
);
assert!(
seen[0]
.header("Accept")
.unwrap()
.contains("text/event-stream")
);
assert!(seen[0].body.contains("server/discover"));
assert_no_credentials(&stub);
}
#[test]
fn oauth_from_the_well_known_uris_with_an_issuer_path_and_cimd() {
let stub = Stub::start(
|seen, base| match (seen.method.as_str(), seen.path.as_str()) {
("POST", "/tools/mcp") => {
answer("401 Unauthorized", &[("WWW-Authenticate", "Bearer")], "")
}
("GET", "/.well-known/oauth-protected-resource") => json(
"200 OK",
&format!(r#"{{"resource":"{base}","authorization_servers":["{base}/tenant1"]}}"#),
),
("GET", "/tenant1/.well-known/openid-configuration") => json(
"200 OK",
&format!(
r#"{{"issuer":"{base}/tenant1","client_id_metadata_document_supported":true}}"#
),
),
_ => not_found(),
},
);
let check = run(&stub.url("/tools/mcp"));
assert_eq!(check.outcome, Outcome::OAuth, "{check:?}");
let oauth = check.oauth.unwrap();
assert!(oauth.client_id_metadata_document && !oauth.dynamic_registration);
let paths: Vec<String> = stub.seen().into_iter().map(|s| s.path).collect();
assert_eq!(
paths,
[
"/tools/mcp",
"/.well-known/oauth-protected-resource/tools/mcp",
"/.well-known/oauth-protected-resource",
"/.well-known/oauth-authorization-server/tenant1",
"/.well-known/openid-configuration/tenant1",
"/tenant1/.well-known/openid-configuration",
]
);
}
#[test]
fn metadata_with_another_issuer_is_not_used() {
let stub = Stub::start(
|seen, base| match (seen.method.as_str(), seen.path.as_str()) {
("POST", "/mcp") => answer("401 Unauthorized", &[], ""),
("GET", "/.well-known/oauth-protected-resource/mcp") => json(
"200 OK",
&format!(r#"{{"resource":"{base}/mcp","authorization_servers":["{base}"]}}"#),
),
("GET", "/.well-known/oauth-authorization-server") => json(
"200 OK",
r#"{"issuer":"https://honest.example","registration_endpoint":"https://honest.example/r"}"#,
),
_ => not_found(),
},
);
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::OAuth);
assert!(!check.oauth.unwrap().registration_supported());
assert!(
check.detail.contains("could not be read"),
"{}",
check.detail
);
}
#[test]
fn a_denied_authorization_server_is_not_contacted() {
let auth = Stub::start(|_, _| json("200 OK", "{}"));
let issuer = auth.base.replace("127.0.0.1", "localhost");
let denied = issuer.trim_start_matches("http://").to_owned();
let stub = Stub::start(move |seen, base| match seen.path.as_str() {
"/mcp" => answer("401 Unauthorized", &[("WWW-Authenticate", "Bearer")], ""),
"/.well-known/oauth-protected-resource/mcp" => json(
"200 OK",
&format!(r#"{{"resource":"{base}/mcp","authorization_servers":["{issuer}"]}}"#),
),
_ => not_found(),
});
let parsed = checked_url(&stub.url("/mcp")).unwrap();
let check = probe(
&env(),
&parsed,
Duration::from_secs(2),
Duration::from_secs(8),
vec![denied],
);
assert_eq!(check.outcome, Outcome::OAuth, "{check:?}");
let oauth = check.oauth.unwrap();
assert!(!oauth.registration_known);
assert!(
check.detail.contains("chose not to contact"),
"{}",
check.detail
);
assert!(auth.seen().is_empty());
}
#[test]
fn a_priming_event_before_the_answer_is_skipped() {
let stub = Stub::start(|seen, _| {
if seen.body.contains("\"initialize\"") {
answer(
"200 OK",
&[("Content-Type", "text/event-stream")],
"id: 1\ndata: \n\nevent: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"serverInfo\":{\"name\":\"primed\"}}}\n\n",
)
} else {
answer("400 Bad Request", &[], "")
}
});
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::Open, "{check:?}");
assert!(check.detail.contains("(primed)"), "{}", check.detail);
}
#[test]
fn a_challenge_without_oauth_metadata_needs_a_token() {
let stub = Stub::start(|seen, _| match seen.path.as_str() {
"/mcp" => answer(
"401 Unauthorized",
&[(
"WWW-Authenticate",
"Bearer realm=\"api\", error=\"invalid_token\"",
)],
r#"{"error":"unauthorized"}"#,
),
_ => not_found(),
});
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::Token, "{check:?}");
assert_eq!(check.status, Some(401));
assert!(check.oauth.is_none());
assert!(check.detail.contains("Bearer"), "{}", check.detail);
assert_no_credentials(&stub);
}
#[test]
fn resource_metadata_on_another_host_is_not_followed() {
let other = Stub::start(|_, _| json("200 OK", "{}"));
let pointer = other.url("/.well-known/oauth-protected-resource");
let pointer = pointer.replace("127.0.0.1", "localhost");
let stub = Stub::start(move |seen, _| match seen.path.as_str() {
"/mcp" => answer(
"401 Unauthorized",
&[(
"WWW-Authenticate",
&format!("Bearer resource_metadata=\"{pointer}\""),
)],
"",
),
_ => not_found(),
});
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::Token);
assert!(check.detail.contains("another host"), "{}", check.detail);
assert!(other.seen().is_empty());
}
#[test]
fn a_modern_server_answering_without_credentials_is_open() {
let stub = Stub::start(|seen, _| match seen.path.as_str() {
"/mcp" => json(
"200 OK",
r#"{"jsonrpc":"2.0","id":1,"result":{"resultType":"complete","supportedVersions":["2026-07-28"],"serverInfo":{"name":"weather","version":"1.2.0"}}}"#,
),
_ => not_found(),
});
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::Open, "{check:?}");
assert_eq!(check.status, Some(200));
assert!(check.detail.contains("weather 1.2.0"), "{}", check.detail);
assert_eq!(stub.seen().len(), 1);
}
#[test]
fn a_legacy_server_is_tried_with_initialize() {
let stub = Stub::start(|seen, _| {
if seen.body.contains("\"initialize\"") {
answer(
"200 OK",
&[
("Content-Type", "text/event-stream"),
("Mcp-Session-Id", "s1"),
],
"event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":\"2025-11-25\",\"serverInfo\":{\"name\":\"old\"}}}\n\n",
)
} else {
json(
"400 Bad Request",
r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32000,"message":"Bad Request: No valid session ID provided"}}"#,
)
}
});
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::Open, "{check:?}");
assert!(check.detail.contains("(old)"), "{}", check.detail);
let seen = stub.seen();
assert_eq!(seen.len(), 2);
assert!(seen[1].body.contains(LEGACY_PROTOCOL_VERSION));
assert_eq!(seen[1].header("Mcp-Method"), None);
}
#[test]
fn a_modern_error_is_an_mcp_answer_without_a_fallback() {
let stub = Stub::start(|_, _| {
json(
"400 Bad Request",
r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32022,"message":"Unsupported protocol version","data":{"supported":["2027-01-01"]}}}"#,
)
});
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::Open, "{check:?}");
assert_eq!(stub.seen().len(), 1);
}
#[test]
fn a_page_that_is_not_mcp_is_unexpected() {
let stub = Stub::start(|_, _| not_found());
let check = run(&stub.url("/mcp"));
assert_eq!(check.outcome, Outcome::Unexpected, "{check:?}");
assert_eq!(check.status, Some(404));
assert_eq!(stub.seen().len(), 2);
}
#[test]
fn a_closed_port_is_unreachable() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/mcp", listener.local_addr().unwrap());
drop(listener);
let check = run(&url);
assert_eq!(check.outcome, Outcome::Unreachable, "{check:?}");
assert_eq!(check.status, None);
}
#[test]
fn a_silent_server_is_unreachable_after_the_timeout() {
let stub = Stub::start(|_, _| (Vec::new(), Duration::from_secs(4)));
let parsed = checked_url(&stub.url("/mcp")).unwrap();
let started = Instant::now();
let check = probe(
&env(),
&parsed,
Duration::from_millis(500),
Duration::from_secs(5),
Vec::new(),
);
assert_eq!(check.outcome, Outcome::Unreachable, "{check:?}");
assert!(
started.elapsed() < Duration::from_secs(3),
"{:?}",
started.elapsed()
);
}
#[test]
fn redirects_stay_on_the_same_host() {
let target = Stub::start(|_, _| json("200 OK", r#"{"jsonrpc":"2.0","id":1,"result":{}}"#));
let elsewhere = target.url("/mcp").replace("127.0.0.1", "localhost");
let stub = Stub::start(move |seen, base| match seen.path.as_str() {
"/old" => answer(
"307 Temporary Redirect",
&[("Location", &format!("{base}/mcp"))],
"",
),
"/mcp" => json("200 OK", r#"{"jsonrpc":"2.0","id":1,"result":{}}"#),
"/away" => answer("307 Temporary Redirect", &[("Location", &elsewhere)], ""),
_ => not_found(),
});
let same = run(&stub.url("/old"));
assert_eq!(same.outcome, Outcome::Open, "{same:?}");
let away = run(&stub.url("/away"));
assert_eq!(away.outcome, Outcome::Unexpected, "{away:?}");
assert!(away.detail.contains("another host"), "{}", away.detail);
assert!(target.seen().is_empty());
}
#[test]
fn an_sse_address_is_open_when_the_endpoint_event_arrives() {
let stub = Stub::start(|seen, _| match seen.path.as_str() {
"/sse" => {
let mut bytes = Vec::new();
bytes.extend_from_slice(
b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\nevent: endpoint\ndata: /messages?sessionId=1\n\n",
);
(bytes, Duration::from_secs(4))
}
_ => not_found(),
});
let started = Instant::now();
let check = run(&stub.url("/sse"));
assert_eq!(check.outcome, Outcome::Open, "{check:?}");
assert!(
started.elapsed() < Duration::from_secs(2),
"{:?}",
started.elapsed()
);
assert_eq!(stub.seen()[0].method, "GET");
}
#[test]
fn addresses_must_be_https_or_loopback_without_credentials() {
for bad in [
"http://example.com/mcp",
"ftp://example.com/mcp",
"https://user:pass@example.com/mcp",
"https://token@example.com/mcp",
"not a url",
] {
let err = checked_url(bad).unwrap_err();
assert_eq!(err.code(), ErrorCode::InvalidValue, "{bad}");
}
for good in [
"https://example.com/mcp",
"http://localhost:3000/mcp",
"http://127.0.0.1/mcp",
"http://[::1]:8080/mcp",
"https://mcp.example.com/mcp?tenant=acme",
] {
assert!(checked_url(good).is_ok(), "{good}");
}
for secret in [
"https://mcp.example.com/mcp?api_key=sk-1a2b3c4d5e6f7a8b9c0d1e2f",
"https://mcp.example.com/mcp?token=ghp_abcdefghijklmnopqrstuvwxyz0123456789",
"https://mcp.example.com/mcp?key=${secret:API_KEY}",
] {
let err = checked_url(secret).unwrap_err();
assert!(err.message().contains("credential"), "{secret}: {err}");
}
let key = |url: &str| host_key(&checked_url(url).unwrap());
assert_eq!(key("https://MCP.Example.com/x"), "mcp.example.com");
assert_eq!(key("https://mcp.example.com:443/x"), "mcp.example.com");
assert_eq!(key("http://localhost:3000/x"), "localhost:3000");
assert_eq!(key("http://[::1]:8080/x"), "[::1]:8080");
}
#[test]
fn nothing_is_sent_until_the_host_is_allowed() {
let stub = Stub::start(|_, _| json("200 OK", r#"{"jsonrpc":"2.0","id":1,"result":{}}"#));
let temp = surjection_testkit::TempHome::new();
let state = temp.root().join("state");
let url = stub.url("/mcp");
let host = host_key(&checked_url(&url).unwrap());
let waiting = check(&env(), &RealFs, &state, &url).unwrap();
assert_eq!(waiting.outcome, Outcome::HostWaiting);
assert_eq!(waiting.host, host);
assert!(stub.seen().is_empty());
answer_host(&RealFs, &state, &host, false).unwrap();
let denied = check(&env(), &RealFs, &state, &url).unwrap();
assert_eq!(denied.outcome, Outcome::HostWaiting);
assert!(denied.detail.contains("chose not to"), "{}", denied.detail);
assert!(stub.seen().is_empty());
assert_eq!(hosts(&RealFs, &state).unwrap(), [(host.clone(), false)]);
answer_host(&RealFs, &state, &host, true).unwrap();
assert_eq!(
consent(&RealFs, &state, &host).unwrap(),
HostConsent::Allowed
);
let open = check(&env(), &RealFs, &state, &url).unwrap();
assert_eq!(open.outcome, Outcome::Open, "{open:?}");
assert_eq!(stub.seen().len(), 1);
assert_eq!(hosts(&RealFs, &state).unwrap(), [(host.clone(), true)]);
clear_host(&RealFs, &state, &host).unwrap();
assert!(hosts(&RealFs, &state).unwrap().is_empty());
assert_eq!(
consent(&RealFs, &state, &host).unwrap(),
HostConsent::Unanswered
);
let text = std::fs::read_to_string(state.join("local-settings.toml")).unwrap();
assert!(!text.contains(&host), "{text}");
}
#[test]
fn challenges_are_parsed_with_quoted_commas() {
let challenge = Challenge::parse(&[
r#"Basic realm="a, b", Bearer error="invalid_token", resource_metadata="https://x.example/.well-known/oauth-protected-resource""#
.to_owned(),
]);
assert_eq!(challenge.schemes, ["Basic", "Bearer"]);
assert_eq!(
challenge.resource_metadata.as_deref(),
Some("https://x.example/.well-known/oauth-protected-resource")
);
}