Skip to main content

surjection_core/
address_check.rs

1//! "Check this address" (#47): what a remote MCP server asks of a client
2//! before it answers, found without credentials, following the MCP
3//! authorization specification (revision 2026-07-28,
4//! <https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization>):
5//!
6//! 1. One MCP request to the address: a `server/discover` POST (Streamable
7//!    HTTP), falling back to a legacy `initialize` POST when the answer is
8//!    a `400`, `404` or `405` without a modern JSON-RPC error (the
9//!    transport's backward compatibility rules); a `GET` expecting the
10//!    `endpoint` event for an address whose path ends in `/sse` (the
11//!    deprecated HTTP+SSE transport).
12//! 2. A `401` (or a `403` with a challenge): the protected resource
13//!    metadata (RFC 9728) from the `resource_metadata` of
14//!    `WWW-Authenticate`, else the well-known URIs (path insertion, then
15//!    the root), on the same host only.
16//! 3. The first authorization server it names: its metadata (RFC 8414,
17//!    then OpenID Connect Discovery, in the order the specification
18//!    gives), whose `issuer` must be that server. `registration_endpoint`
19//!    means dynamic client registration (RFC 7591, deprecated by MCP
20//!    2026-07-28), `client_id_metadata_document_supported` means Client ID
21//!    Metadata Documents.
22//!
23//! Outcomes: `oauth` (protected resource metadata found), `token` (asks
24//! for credentials without OAuth metadata), `open` (answered MCP without
25//! credentials), `unreachable`, `unexpected`, and `host_waiting` when the
26//! user has not allowed the host (nothing is sent).
27//!
28//! Rules: `https://` only (`http://` only for `localhost`, `127.0.0.1`,
29//! `::1`), no user name or password in the address, no cookies, no
30//! credentials of any kind, 5 seconds per request and 20 for the whole
31//! check, redirects followed only within the same scheme, host and port,
32//! bodies capped. Proxies come from the injected [`Env`] as for catalogs.
33//! Logs name the host only.
34
35use std::io::Read;
36use std::path::Path;
37use std::time::{Duration, Instant};
38
39use serde_json::{Value, json};
40use ureq::tls::{RootCerts, TlsConfig};
41
42use crate::catalog::http::proxy;
43use crate::diagnostics::log;
44use crate::env::Env;
45use crate::error::{CoreError, ErrorCode};
46use crate::fs::Fs;
47use crate::local_settings::{AddressCheckHosts, LocalSettings};
48use crate::model::server::Transport;
49use crate::secrets::classify::classify_import;
50use crate::server_input::transport_from_url;
51
52/// Longest wait for one request.
53pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
54/// Longest wait for the whole check.
55pub const CHECK_TIMEOUT: Duration = Duration::from_secs(20);
56/// The protocol revision of the modern request.
57pub const PROTOCOL_VERSION: &str = "2026-07-28";
58/// The revision a legacy `initialize` asks for.
59pub const LEGACY_PROTOCOL_VERSION: &str = "2025-11-25";
60/// Largest body read from any answer.
61const MAX_BODY: usize = 256 * 1024;
62/// Same-origin redirects followed per request.
63const MAX_REDIRECTS: usize = 3;
64
65/// What the check found.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum Outcome {
68    /// The server signs in with OAuth (protected resource metadata).
69    OAuth,
70    /// The server asks for credentials, without OAuth metadata: a token in
71    /// a header.
72    Token,
73    /// The server answered MCP without credentials.
74    Open,
75    /// No answer (host not found, connection refused, timeout, TLS).
76    Unreachable,
77    /// An answer that is none of the above.
78    Unexpected,
79    /// The user has not allowed this host; nothing was sent.
80    HostWaiting,
81}
82
83impl Outcome {
84    pub const fn as_str(self) -> &'static str {
85        match self {
86            Outcome::OAuth => "oauth",
87            Outcome::Token => "token",
88            Outcome::Open => "open",
89            Outcome::Unreachable => "unreachable",
90            Outcome::Unexpected => "unexpected",
91            Outcome::HostWaiting => "host_waiting",
92        }
93    }
94}
95
96/// The OAuth details of an [`Outcome::OAuth`] server.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct OAuthInfo {
99    /// The authorization server's identifier (issuer URL).
100    pub authorization_server: String,
101    /// Its metadata has a `registration_endpoint` (RFC 7591).
102    pub dynamic_registration: bool,
103    /// Its metadata says `client_id_metadata_document_supported`.
104    pub client_id_metadata_document: bool,
105    /// The authorization server's metadata was read: the two flags above
106    /// are known (otherwise both are `false` for "not known").
107    pub registration_known: bool,
108}
109
110impl OAuthInfo {
111    /// A client can register itself (either way), so signing in needs no
112    /// client id from the user.
113    pub fn registration_supported(&self) -> bool {
114        self.dynamic_registration || self.client_id_metadata_document
115    }
116}
117
118/// The result of a check.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct AddressCheck {
121    pub outcome: Outcome,
122    /// The host (with a non-default port) the check contacts.
123    pub host: String,
124    /// The HTTP status of the MCP request's answer, when there was one.
125    pub status: Option<u16>,
126    pub oauth: Option<OAuthInfo>,
127    /// What happened, in English (no secret: the check sends none).
128    pub detail: String,
129}
130
131/// The user's answer for a host.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum HostConsent {
134    Allowed,
135    Denied,
136    Unanswered,
137}
138
139/// `url` checked against the rules (see the module docs): `invalid_value`
140/// when it breaks one.
141pub fn checked_url(url: &str) -> Result<url::Url, CoreError> {
142    let invalid = |why: &str| CoreError::new(ErrorCode::InvalidValue, why.to_owned());
143    let parsed = url::Url::parse(url.trim())
144        .map_err(|_| invalid("the address is not a URL; use https://host/path"))?;
145    if !matches!(parsed.scheme(), "http" | "https") || parsed.host().is_none() {
146        return Err(invalid("the address must start with https://"));
147    }
148    if !parsed.username().is_empty() || parsed.password().is_some() {
149        return Err(invalid(
150            "the address holds a user name or password; remove it (the check sends no credentials)",
151        ));
152    }
153    if parsed.scheme() == "http" && !is_loopback(&parsed) {
154        return Err(invalid(
155            "the check uses https:// only (http:// only for localhost, 127.0.0.1 and ::1)",
156        ));
157    }
158    let flagged = url.contains("${")
159        || classify_import(None, url.trim()).is_some()
160        || parsed
161            .query_pairs()
162            .any(|(key, value)| classify_import(Some(&key), &value).is_some());
163    if flagged {
164        return Err(invalid(
165            "the address holds what looks like a credential or a reference (${...}); remove it \
166             first: the check sends no credentials",
167        ));
168    }
169    Ok(parsed)
170}
171
172fn is_loopback(url: &url::Url) -> bool {
173    match url.host() {
174        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
175        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
176        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
177        None => false,
178    }
179}
180
181/// The host consent is asked for: the host in lower case, with its port
182/// when it is not the scheme's default (`localhost:8080`, `[::1]:3000`).
183pub fn host_key(url: &url::Url) -> String {
184    let host = match url.host() {
185        Some(url::Host::Ipv6(ip)) => format!("[{ip}]"),
186        Some(host) => host.to_string().to_ascii_lowercase(),
187        None => String::new(),
188    };
189    match url.port() {
190        Some(port) => format!("{host}:{port}"),
191        None => host,
192    }
193}
194
195fn hosts_of(settings: &LocalSettings) -> AddressCheckHosts {
196    settings.address_check_hosts.clone().unwrap_or_default()
197}
198
199/// The user's answer for `host` on this machine.
200pub fn consent(fs: &dyn Fs, state_dir: &Path, host: &str) -> Result<HostConsent, CoreError> {
201    let hosts = hosts_of(&LocalSettings::load(fs, state_dir)?);
202    Ok(if hosts.allowed.iter().any(|h| h == host) {
203        HostConsent::Allowed
204    } else if hosts.denied.iter().any(|h| h == host) {
205        HostConsent::Denied
206    } else {
207        HostConsent::Unanswered
208    })
209}
210
211/// Records the answer for `host` (machine-local, never synced); a new
212/// answer replaces the old one.
213pub fn answer_host(
214    fs: &dyn Fs,
215    state_dir: &Path,
216    host: &str,
217    allow: bool,
218) -> Result<(), CoreError> {
219    let host = host.trim().to_ascii_lowercase();
220    if host.is_empty() || host.contains(['/', ' ']) {
221        return Err(CoreError::new(
222            ErrorCode::InvalidValue,
223            format!("{host:?} is not a host name"),
224        ));
225    }
226    edit_hosts(fs, state_dir, |hosts| {
227        hosts.allowed.retain(|h| *h != host);
228        hosts.denied.retain(|h| *h != host);
229        if allow {
230            hosts.allowed.push(host.clone());
231        } else {
232            hosts.denied.push(host.clone());
233        }
234    })
235}
236
237/// Forgets the answer for `host`: the next check asks again. Unknown
238/// hosts are fine.
239pub fn clear_host(fs: &dyn Fs, state_dir: &Path, host: &str) -> Result<(), CoreError> {
240    let host = host.trim().to_ascii_lowercase();
241    edit_hosts(fs, state_dir, |hosts| {
242        hosts.allowed.retain(|h| *h != host);
243        hosts.denied.retain(|h| *h != host);
244    })
245}
246
247fn edit_hosts(
248    fs: &dyn Fs,
249    state_dir: &Path,
250    edit: impl FnOnce(&mut AddressCheckHosts),
251) -> Result<(), CoreError> {
252    let mut settings = LocalSettings::load(fs, state_dir)?;
253    let mut hosts = hosts_of(&settings);
254    let before = hosts.clone();
255    edit(&mut hosts);
256    if hosts == before {
257        return Ok(());
258    }
259    settings.address_check_hosts =
260        (!hosts.allowed.is_empty() || !hosts.denied.is_empty()).then_some(hosts);
261    settings.save(fs, state_dir)
262}
263
264/// Every answered host and whether it is allowed, sorted by host.
265pub fn hosts(fs: &dyn Fs, state_dir: &Path) -> Result<Vec<(String, bool)>, CoreError> {
266    let hosts = hosts_of(&LocalSettings::load(fs, state_dir)?);
267    let mut out: Vec<(String, bool)> = hosts
268        .allowed
269        .into_iter()
270        .map(|h| (h, true))
271        .chain(hosts.denied.into_iter().map(|h| (h, false)))
272        .collect();
273    out.sort();
274    out.dedup_by(|a, b| a.0 == b.0);
275    Ok(out)
276}
277
278/// Checks `url` (see the module docs) when the user allowed its host on
279/// this machine; otherwise [`Outcome::HostWaiting`] and nothing is sent.
280pub fn check(
281    env: &Env,
282    fs: &dyn Fs,
283    state_dir: &Path,
284    url: &str,
285) -> Result<AddressCheck, CoreError> {
286    let parsed = checked_url(url)?;
287    let host = host_key(&parsed);
288    match consent(fs, state_dir, &host)? {
289        HostConsent::Allowed => {
290            let denied = hosts_of(&LocalSettings::load(fs, state_dir)?).denied;
291            Ok(probe(env, &parsed, REQUEST_TIMEOUT, CHECK_TIMEOUT, denied))
292        }
293        answer => Ok(AddressCheck {
294            outcome: Outcome::HostWaiting,
295            detail: if answer == HostConsent::Denied {
296                format!("You chose not to check addresses on {host}. Allow it to check this one.")
297            } else {
298                format!("Checking sends a request to {host}. Allow it first.")
299            },
300            host,
301            status: None,
302            oauth: None,
303        }),
304    }
305}
306
307/// The check itself, with no consent lookup (`check` asks first);
308/// `denied`: hosts not to contact for authorization server metadata.
309pub fn probe(
310    env: &Env,
311    url: &url::Url,
312    per_request: Duration,
313    total: Duration,
314    denied: Vec<String>,
315) -> AddressCheck {
316    let client = Client::new(
317        env,
318        per_request,
319        Instant::now() + total,
320        is_loopback(url),
321        denied,
322    );
323    client.run(url)
324}
325
326/// An IP address in a private, link-local, loopback or unspecified range
327/// (an authorization server there is not contacted from a public check).
328fn is_private_ip(url: &url::Url) -> bool {
329    match url.host() {
330        Some(url::Host::Ipv4(ip)) => {
331            ip.is_private() || ip.is_link_local() || ip.is_loopback() || ip.is_unspecified()
332        }
333        Some(url::Host::Ipv6(ip)) => {
334            ip.is_loopback()
335                || ip.is_unspecified()
336                || ip.is_unique_local()
337                || ip.is_unicast_link_local()
338                || ip
339                    .to_ipv4_mapped()
340                    .is_some_and(|v4| v4.is_private() || v4.is_loopback())
341        }
342        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
343        None => false,
344    }
345}
346
347/// An answer, with what the check reads of it.
348#[derive(Debug, Default)]
349struct Answer {
350    status: u16,
351    challenges: Vec<String>,
352    content_type: String,
353    body: Vec<u8>,
354}
355
356/// Why a request got no usable answer.
357#[derive(Debug)]
358enum Failure {
359    /// No answer at all.
360    Unreachable(String),
361    /// A redirect off the origin, or another answer the check does not
362    /// follow.
363    Refused(String),
364}
365
366struct Client {
367    https: ureq::Agent,
368    loopback: ureq::Agent,
369    https_problem: Option<String>,
370    per_request: Duration,
371    deadline: Instant,
372    /// The address is a loopback one: an authorization server may be a
373    /// loopback `http://` one too.
374    local: bool,
375    /// Hosts the user denied: an authorization server there is not read.
376    denied: Vec<String>,
377}
378
379impl Client {
380    fn new(
381        env: &Env,
382        per_request: Duration,
383        deadline: Instant,
384        local: bool,
385        denied: Vec<String>,
386    ) -> Self {
387        let agent = |proxy: Option<ureq::Proxy>, https_only: bool| {
388            ureq::Agent::config_builder()
389                .http_status_as_error(false)
390                .timeout_connect(Some(per_request))
391                .timeout_global(Some(per_request))
392                .https_only(https_only)
393                .max_redirects(0)
394                .user_agent(format!("Surjection/{}", env!("CARGO_PKG_VERSION")))
395                .proxy(proxy)
396                .tls_config(
397                    TlsConfig::builder()
398                        .root_certs(RootCerts::PlatformVerifier)
399                        .build(),
400                )
401                .build()
402                .new_agent()
403        };
404        let https = proxy(
405            env,
406            &["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"],
407        );
408        let (https_proxy, https_problem) = match https {
409            Ok(proxy) => (proxy, None),
410            Err(why) => (None, Some(why)),
411        };
412        Self {
413            https: agent(https_proxy, true),
414            // Loopback addresses never go through a proxy.
415            loopback: agent(None, false),
416            https_problem,
417            per_request,
418            deadline,
419            local,
420            denied,
421        }
422    }
423
424    /// Whether `url` may be contacted at all: https, or loopback http.
425    fn allowed(&self, url: &url::Url) -> bool {
426        url.scheme() == "https" || (url.scheme() == "http" && is_loopback(url))
427    }
428
429    /// One request, following redirects within the origin. `body`: a POST
430    /// of that JSON with `headers`; otherwise a GET.
431    fn send(
432        &self,
433        url: &url::Url,
434        body: Option<&Value>,
435        headers: &[(&str, &str)],
436    ) -> Result<Answer, Failure> {
437        let mut current = url.clone();
438        for _ in 0..=MAX_REDIRECTS {
439            let (answer, location) = self.send_once(&current, body, headers)?;
440            let redirect = matches!(answer.status, 301 | 302 | 303 | 307 | 308);
441            let Some(location) = location.filter(|_| redirect) else {
442                return Ok(answer);
443            };
444            let next = current
445                .join(&location)
446                .map_err(|_| Failure::Refused("it redirected to an invalid address".to_owned()))?;
447            if next.origin() != current.origin() {
448                return Err(Failure::Refused(format!(
449                    "it redirected to another host ({}), which the check does not follow",
450                    host_key(&next)
451                )));
452            }
453            if body.is_some() && !matches!(answer.status, 307 | 308) {
454                return Err(Failure::Refused(format!(
455                    "it answered the request with a redirect ({})",
456                    answer.status
457                )));
458            }
459            current = next;
460        }
461        Err(Failure::Refused("too many redirects".to_owned()))
462    }
463
464    fn send_once(
465        &self,
466        url: &url::Url,
467        body: Option<&Value>,
468        headers: &[(&str, &str)],
469    ) -> Result<(Answer, Option<String>), Failure> {
470        if !self.allowed(url) {
471            return Err(Failure::Refused(
472                "the address must use https:// (http:// only for localhost)".to_owned(),
473            ));
474        }
475        let remaining = self.deadline.saturating_duration_since(Instant::now());
476        if remaining.is_zero() {
477            return Err(Failure::Unreachable("the check ran out of time".to_owned()));
478        }
479        let timeout = remaining.min(self.per_request);
480        let agent = if url.scheme() == "http" {
481            &self.loopback
482        } else {
483            if let Some(why) = &self.https_problem {
484                return Err(Failure::Unreachable(why.clone()));
485            }
486            &self.https
487        };
488        let started = Instant::now();
489        let result = match body {
490            Some(body) => {
491                let mut request = agent
492                    .post(url.as_str())
493                    .config()
494                    .timeout_global(Some(timeout))
495                    .build()
496                    .header("Content-Type", "application/json");
497                for (name, value) in headers {
498                    request = request.header(*name, *value);
499                }
500                request.send(body.to_string())
501            }
502            None => {
503                let mut request = agent
504                    .get(url.as_str())
505                    .config()
506                    .timeout_global(Some(timeout))
507                    .build();
508                for (name, value) in headers {
509                    request = request.header(*name, *value);
510                }
511                request.call()
512            }
513        };
514        let response = match result {
515            Ok(response) => response,
516            Err(err) => {
517                let failure = transport_failure(err);
518                log::http(
519                    "address_check",
520                    url.as_str(),
521                    Err(&CoreError::new(ErrorCode::IoError, "no answer")),
522                    started,
523                );
524                return Err(failure);
525            }
526        };
527        let status = response.status().as_u16();
528        log::http("address_check", url.as_str(), Ok(status), started);
529        let header = |name: &str| {
530            response
531                .headers()
532                .get_all(name)
533                .iter()
534                .filter_map(|value| value.to_str().ok().map(str::to_owned))
535                .collect::<Vec<_>>()
536        };
537        let challenges = header("www-authenticate");
538        let content_type = header("content-type")
539            .into_iter()
540            .next()
541            .unwrap_or_default()
542            .to_ascii_lowercase();
543        let location = header("location").into_iter().next();
544        let stream = content_type.starts_with("text/event-stream");
545        let body = read_body(response.into_body().into_reader(), stream);
546        Ok((
547            Answer {
548                status,
549                challenges,
550                content_type,
551                body,
552            },
553            location,
554        ))
555    }
556
557    fn run(&self, url: &url::Url) -> AddressCheck {
558        let host = host_key(url);
559        let result = |outcome, status, oauth, detail: String| AddressCheck {
560            outcome,
561            host: host.clone(),
562            status,
563            oauth,
564            detail,
565        };
566        let sse = transport_from_url(url.as_str()) == Transport::Sse;
567        let first = if sse {
568            self.send(url, None, &[("Accept", "text/event-stream")])
569        } else {
570            self.send(url, Some(&discover_request()), &MODERN_HEADERS)
571        };
572        let answer = match first {
573            Ok(answer) => answer,
574            Err(Failure::Unreachable(why)) => {
575                return result(
576                    Outcome::Unreachable,
577                    None,
578                    None,
579                    format!("{host} could not be reached: {why}."),
580                );
581            }
582            Err(Failure::Refused(why)) => {
583                return result(
584                    Outcome::Unexpected,
585                    None,
586                    None,
587                    format!("Not checked: {why}."),
588                );
589            }
590        };
591        if let Some(check) = self.classify(url, &answer, sse) {
592            return check;
593        }
594        // The legacy fallback of Streamable HTTP: a 400, 404 or 405 that is
595        // not a modern JSON-RPC error.
596        if !sse && matches!(answer.status, 400 | 404 | 405) && !modern_error(&answer) {
597            let legacy = self.send(url, Some(&initialize_request()), &LEGACY_HEADERS);
598            match legacy {
599                Ok(legacy) => {
600                    if let Some(check) = self.classify(url, &legacy, false) {
601                        return check;
602                    }
603                    return result(
604                        Outcome::Unexpected,
605                        Some(legacy.status),
606                        None,
607                        format!(
608                            "{host} answered {} to an MCP request, without asking for credentials. \
609                             Check the address (the path too).",
610                            legacy.status
611                        ),
612                    );
613                }
614                Err(Failure::Unreachable(why)) => {
615                    return result(
616                        Outcome::Unreachable,
617                        None,
618                        None,
619                        format!("{host} could not be reached: {why}."),
620                    );
621                }
622                Err(Failure::Refused(why)) => {
623                    return result(
624                        Outcome::Unexpected,
625                        Some(answer.status),
626                        None,
627                        format!("Not checked: {why}."),
628                    );
629                }
630            }
631        }
632        result(
633            Outcome::Unexpected,
634            Some(answer.status),
635            None,
636            format!(
637                "{host} answered {} to an MCP request, without asking for credentials. Check the \
638                 address (the path too).",
639                answer.status
640            ),
641        )
642    }
643
644    /// The outcome an answer gives: sign-in (`401`, or `403` with a
645    /// challenge), or an MCP answer; `None` for anything else.
646    fn classify(&self, url: &url::Url, answer: &Answer, sse: bool) -> Option<AddressCheck> {
647        let host = host_key(url);
648        if answer.status == 401 || (answer.status == 403 && !answer.challenges.is_empty()) {
649            return Some(self.sign_in(url, answer));
650        }
651        let answered = if sse {
652            (200..300).contains(&answer.status) && sse_endpoint(&answer.body)
653        } else {
654            ((200..300).contains(&answer.status) && json_rpc_answer(answer).is_some())
655                || modern_error(answer)
656        };
657        answered.then(|| {
658            let name = json_rpc_answer(answer)
659                .as_ref()
660                .and_then(server_name)
661                .map(|name| format!(" ({name})"))
662                .unwrap_or_default();
663            AddressCheck {
664                outcome: Outcome::Open,
665                host: host.clone(),
666                status: Some(answer.status),
667                oauth: None,
668                detail: format!("{host} answered as an MCP server{name} without credentials."),
669            }
670        })
671    }
672
673    /// A `401`/`403`: OAuth when protected resource metadata is found,
674    /// else a token.
675    fn sign_in(&self, url: &url::Url, answer: &Answer) -> AddressCheck {
676        let host = host_key(url);
677        let challenge = Challenge::parse(&answer.challenges);
678        let mut notes: Vec<String> = Vec::new();
679        let mut candidates: Vec<url::Url> = Vec::new();
680        if let Some(pointer) = &challenge.resource_metadata {
681            match url.join(pointer) {
682                Ok(target) if target.origin() == url.origin() => candidates.push(target),
683                Ok(target) => notes.push(format!(
684                    "its resource_metadata points to another host ({}), which the check does not \
685                     contact",
686                    host_key(&target)
687                )),
688                Err(_) => notes.push("its resource_metadata is not a valid address".to_owned()),
689            }
690        }
691        candidates.extend(well_known(url, "oauth-protected-resource"));
692        let metadata = candidates.iter().find_map(|candidate| {
693            let answer = self
694                .send(candidate, None, &[("Accept", "application/json")])
695                .ok()?;
696            let doc = json_body(&answer)?;
697            let valid = (200..300).contains(&answer.status) && resource_matches(&doc, url);
698            valid.then_some(doc)
699        });
700        let authorization_server = metadata.as_ref().and_then(|doc| {
701            doc.get("authorization_servers")?
702                .as_array()?
703                .iter()
704                .filter_map(Value::as_str)
705                .next()
706                .map(str::to_owned)
707        });
708        let status = Some(answer.status);
709        let Some(authorization_server) = authorization_server else {
710            let schemes = if challenge.schemes.is_empty() {
711                String::new()
712            } else {
713                format!(" ({})", challenge.schemes.join(", "))
714            };
715            let notes = if notes.is_empty() {
716                String::new()
717            } else {
718                format!(" Note: {}.", notes.join("; "))
719            };
720            return AddressCheck {
721                outcome: Outcome::Token,
722                host: host.clone(),
723                status,
724                oauth: None,
725                detail: format!(
726                    "{host} asks for credentials{schemes} and publishes no OAuth metadata: it \
727                     needs a token, usually in an Authorization header kept as a secret.{notes}"
728                ),
729            };
730        };
731        let (info, detail) = self.authorization_server(&authorization_server);
732        AddressCheck {
733            outcome: Outcome::OAuth,
734            host,
735            status,
736            oauth: Some(info),
737            detail,
738        }
739    }
740
741    /// The authorization server's metadata, tried in the specification's
742    /// order; the first document whose `issuer` is the server counts.
743    fn authorization_server(&self, issuer: &str) -> (OAuthInfo, String) {
744        let mut info = OAuthInfo {
745            authorization_server: issuer.to_owned(),
746            dynamic_registration: false,
747            client_id_metadata_document: false,
748            registration_known: false,
749        };
750        let parsed = url::Url::parse(issuer).ok().filter(|parsed| {
751            parsed.scheme() == "https"
752                || (self.local && parsed.scheme() == "http" && is_loopback(parsed))
753        });
754        let Some(parsed) = parsed else {
755            return (
756                info,
757                format!(
758                    "Signs in with OAuth. Its authorization server ({issuer}) is not an https:// \
759                     address, so the check did not read its metadata."
760                ),
761            );
762        };
763        let as_host = host_key(&parsed);
764        if self.denied.contains(&as_host) {
765            return (
766                info,
767                format!(
768                    "Signs in with OAuth through {as_host}. You chose not to contact that host, \
769                     so whether clients can register themselves is not known."
770                ),
771            );
772        }
773        if is_private_ip(&parsed) && !self.local {
774            return (
775                info,
776                format!(
777                    "Signs in with OAuth through {as_host}, a private address the check does not \
778                     contact, so whether clients can register themselves is not known."
779                ),
780            );
781        }
782        let found = authorization_server_urls(&parsed)
783            .into_iter()
784            .find_map(|candidate| {
785                let answer = self
786                    .send(&candidate, None, &[("Accept", "application/json")])
787                    .ok()?;
788                let doc = json_body(&answer)?;
789                let issued = doc.get("issuer").and_then(Value::as_str)?;
790                ((200..300).contains(&answer.status) && same_identifier(issued, issuer))
791                    .then_some(doc)
792            });
793        let Some(doc) = found else {
794            return (
795                info,
796                format!(
797                    "Signs in with OAuth through {as_host}. Its authorization server metadata \
798                     could not be read, so whether clients can register themselves is not known."
799                ),
800            );
801        };
802        info.registration_known = true;
803        info.dynamic_registration = doc
804            .get("registration_endpoint")
805            .and_then(Value::as_str)
806            .is_some_and(|endpoint| !endpoint.is_empty());
807        info.client_id_metadata_document = doc
808            .get("client_id_metadata_document_supported")
809            .and_then(Value::as_bool)
810            .unwrap_or(false);
811        let how = match (info.client_id_metadata_document, info.dynamic_registration) {
812            (true, true) => {
813                "Clients can register themselves (Client ID Metadata Documents and dynamic client \
814                 registration)."
815            }
816            (true, false) => "Clients can register themselves (Client ID Metadata Documents).",
817            (false, true) => "Clients can register themselves (dynamic client registration).",
818            (false, false) => {
819                "It offers no self-registration: a client may need a client id from the server's \
820                 owner."
821            }
822        };
823        (
824            info,
825            format!(
826                "Signs in with OAuth through {as_host}. {how} Each client signs in on its own."
827            ),
828        )
829    }
830}
831
832const MODERN_HEADERS: [(&str, &str); 3] = [
833    ("Accept", "application/json, text/event-stream"),
834    ("MCP-Protocol-Version", PROTOCOL_VERSION),
835    ("Mcp-Method", "server/discover"),
836];
837
838const LEGACY_HEADERS: [(&str, &str); 1] = [("Accept", "application/json, text/event-stream")];
839
840fn client_info() -> Value {
841    json!({"name": "Surjection", "version": env!("CARGO_PKG_VERSION")})
842}
843
844/// The modern request: `server/discover` with the per-request metadata.
845fn discover_request() -> Value {
846    json!({
847        "jsonrpc": "2.0",
848        "id": 1,
849        "method": "server/discover",
850        "params": {
851            "_meta": {
852                "io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
853                "io.modelcontextprotocol/clientCapabilities": {},
854                "io.modelcontextprotocol/clientInfo": client_info(),
855            }
856        }
857    })
858}
859
860/// The legacy request: `initialize`.
861fn initialize_request() -> Value {
862    json!({
863        "jsonrpc": "2.0",
864        "id": 1,
865        "method": "initialize",
866        "params": {
867            "protocolVersion": LEGACY_PROTOCOL_VERSION,
868            "capabilities": {},
869            "clientInfo": client_info(),
870        }
871    })
872}
873
874fn transport_failure(err: ureq::Error) -> Failure {
875    let why = match err {
876        ureq::Error::Timeout(_) => "it did not answer in time".to_owned(),
877        ureq::Error::HostNotFound => "the host was not found".to_owned(),
878        ureq::Error::ConnectionFailed => "the connection failed".to_owned(),
879        ureq::Error::RequireHttpsOnly(_) => {
880            return Failure::Refused("it needs an address without encryption".to_owned());
881        }
882        ureq::Error::Io(err) => format!("the connection failed ({})", err.kind()),
883        other => format!("the secure connection failed or was cut ({other})"),
884    };
885    Failure::Unreachable(why)
886}
887
888/// The body, at most [`MAX_BODY`] bytes; for an event stream, only up to
889/// the end of its first event (the stream may stay open).
890fn read_body(mut reader: impl Read, stream: bool) -> Vec<u8> {
891    let mut body = Vec::new();
892    let mut buf = [0u8; 4096];
893    while body.len() < MAX_BODY {
894        match reader.read(&mut buf) {
895            Ok(0) | Err(_) => break,
896            Ok(n) => {
897                body.extend_from_slice(&buf[..n.min(MAX_BODY - body.len())]);
898                if stream && first_event(&body).is_some() {
899                    break;
900                }
901            }
902        }
903    }
904    body
905}
906
907/// The first complete event of an event stream that carries data: its
908/// `event` name and its `data` lines joined. Events without data (the
909/// "priming" event a server may send first: an `id` and an empty `data`)
910/// are skipped.
911fn first_event(body: &[u8]) -> Option<(String, String)> {
912    let text = String::from_utf8_lossy(body).replace("\r\n", "\n");
913    let mut event = String::new();
914    let mut data: Vec<&str> = Vec::new();
915    let mut lines = text.split('\n').peekable();
916    while let Some(line) = lines.next() {
917        if line.is_empty() {
918            // Complete only when the blank line was read.
919            if data.iter().any(|d| !d.is_empty()) {
920                return Some((event, data.join("\n")));
921            }
922            event.clear();
923            data.clear();
924            continue;
925        }
926        lines.peek()?;
927        if let Some(value) = line.strip_prefix("event:") {
928            event = value.trim().to_owned();
929        } else if let Some(value) = line.strip_prefix("data:") {
930            data.push(value.strip_prefix(' ').unwrap_or(value));
931        }
932    }
933    None
934}
935
936/// The JSON of an answer: the body, or the data of its first event.
937fn json_body(answer: &Answer) -> Option<Value> {
938    if answer.content_type.starts_with("text/event-stream") {
939        let (_, data) = first_event(&answer.body)?;
940        serde_json::from_str(&data).ok()
941    } else {
942        serde_json::from_slice(&answer.body).ok()
943    }
944}
945
946/// A JSON-RPC 2.0 response (a result or an error) in the answer.
947fn json_rpc_answer(answer: &Answer) -> Option<Value> {
948    json_body(answer).filter(|doc| {
949        doc.get("jsonrpc").and_then(Value::as_str) == Some("2.0")
950            && (doc.get("result").is_some() || doc.get("error").is_some())
951    })
952}
953
954/// A JSON-RPC error only a modern server sends: header mismatch,
955/// missing capability, unsupported version, or method not found on a 404.
956fn modern_error(answer: &Answer) -> bool {
957    let code = json_rpc_answer(answer).and_then(|doc| doc.get("error")?.get("code")?.as_i64());
958    match code {
959        Some(-32022..=-32020) => true,
960        Some(-32601) => answer.status == 404,
961        _ => false,
962    }
963}
964
965/// The server's name and version from a `server/discover` or
966/// `initialize` result, shortened and printable.
967fn server_name(doc: &Value) -> Option<String> {
968    let result = doc.get("result")?;
969    let info = result.get("serverInfo").or_else(|| {
970        result
971            .get("_meta")?
972            .get("io.modelcontextprotocol/serverInfo")
973    })?;
974    let name = info.get("name")?.as_str()?;
975    let version = info.get("version").and_then(Value::as_str);
976    let text = match version {
977        Some(version) => format!("{name} {version}"),
978        None => name.to_owned(),
979    };
980    let clean: String = text.chars().filter(|c| !c.is_control()).take(80).collect();
981    (!clean.trim().is_empty()).then_some(clean)
982}
983
984/// Whether an event stream begins with the HTTP+SSE `endpoint` event.
985fn sse_endpoint(body: &[u8]) -> bool {
986    first_event(body).is_some_and(|(event, _)| event == "endpoint")
987}
988
989/// The well-known metadata URIs for `url`: with the path inserted (when
990/// it has one), then at the root.
991fn well_known(url: &url::Url, suffix: &str) -> Vec<url::Url> {
992    let path = url.path().trim_end_matches('/');
993    let mut out = Vec::new();
994    let mut base = url.clone();
995    base.set_query(None);
996    base.set_fragment(None);
997    if !path.is_empty() {
998        let mut inserted = base.clone();
999        inserted.set_path(&format!("/.well-known/{suffix}{path}"));
1000        out.push(inserted);
1001    }
1002    let mut root = base;
1003    root.set_path(&format!("/.well-known/{suffix}"));
1004    out.push(root);
1005    out
1006}
1007
1008/// The authorization server metadata URIs for issuer `issuer`, in the
1009/// order the MCP specification gives.
1010fn authorization_server_urls(issuer: &url::Url) -> Vec<url::Url> {
1011    let path = issuer.path().trim_end_matches('/');
1012    let mut base = issuer.clone();
1013    base.set_query(None);
1014    base.set_fragment(None);
1015    let at = |p: String| {
1016        let mut url = base.clone();
1017        url.set_path(&p);
1018        url
1019    };
1020    if path.is_empty() {
1021        vec![
1022            at("/.well-known/oauth-authorization-server".to_owned()),
1023            at("/.well-known/openid-configuration".to_owned()),
1024        ]
1025    } else {
1026        vec![
1027            at(format!("/.well-known/oauth-authorization-server{path}")),
1028            at(format!("/.well-known/openid-configuration{path}")),
1029            at(format!("{path}/.well-known/openid-configuration")),
1030        ]
1031    }
1032}
1033
1034/// Whether protected resource metadata is for `url`: its `resource` is
1035/// the address, its origin, or a path prefix of it on the same origin
1036/// (RFC 9728 3.3, read leniently for the root well-known URI). A document
1037/// without `resource` is not used.
1038fn resource_matches(doc: &Value, url: &url::Url) -> bool {
1039    let Some(resource) = doc.get("resource").and_then(Value::as_str) else {
1040        return false;
1041    };
1042    let Ok(resource) = url::Url::parse(resource) else {
1043        return false;
1044    };
1045    if resource.origin() != url.origin() {
1046        return false;
1047    }
1048    let wanted = url.path().trim_end_matches('/');
1049    let given = resource.path().trim_end_matches('/');
1050    given.is_empty() || wanted == given || wanted.starts_with(&format!("{given}/"))
1051}
1052
1053/// Issuer identifiers compared as the specification requires, a single
1054/// trailing `/` aside.
1055fn same_identifier(a: &str, b: &str) -> bool {
1056    a.trim_end_matches('/') == b.trim_end_matches('/')
1057}
1058
1059/// What `WWW-Authenticate` says.
1060#[derive(Debug, Default, PartialEq, Eq)]
1061struct Challenge {
1062    /// Auth schemes, as given (`Bearer`, `Basic`).
1063    schemes: Vec<String>,
1064    resource_metadata: Option<String>,
1065}
1066
1067impl Challenge {
1068    fn parse(headers: &[String]) -> Self {
1069        let mut challenge = Self::default();
1070        for header in headers {
1071            for piece in split_outside_quotes(header) {
1072                let piece = piece.trim();
1073                let (first, rest) = piece.split_once(' ').unwrap_or((piece, ""));
1074                let param = if first.contains('=') {
1075                    piece
1076                } else {
1077                    if !first.is_empty() && !challenge.schemes.iter().any(|s| s == first) {
1078                        challenge.schemes.push(first.to_owned());
1079                    }
1080                    rest.trim()
1081                };
1082                if let Some((name, value)) = param.split_once('=')
1083                    && name.trim().eq_ignore_ascii_case("resource_metadata")
1084                {
1085                    let value = value.trim().trim_matches('"').to_owned();
1086                    if !value.is_empty() && challenge.resource_metadata.is_none() {
1087                        challenge.resource_metadata = Some(value);
1088                    }
1089                }
1090            }
1091        }
1092        challenge
1093    }
1094}
1095
1096/// `text` split at commas outside double quotes.
1097fn split_outside_quotes(text: &str) -> Vec<&str> {
1098    let mut out = Vec::new();
1099    let mut start = 0;
1100    let mut quoted = false;
1101    let mut escaped = false;
1102    for (i, c) in text.char_indices() {
1103        match c {
1104            _ if escaped => escaped = false,
1105            '\\' if quoted => escaped = true,
1106            '"' => quoted = !quoted,
1107            ',' if !quoted => {
1108                out.push(&text[start..i]);
1109                start = i + 1;
1110            }
1111            _ => {}
1112        }
1113    }
1114    out.push(&text[start..]);
1115    out
1116}
1117
1118#[cfg(test)]
1119mod tests;