~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
244 lines · 8.5 KB Raw History
//! An MCP client's document, held to MCP's rules rather than atproto's
//! (`spec/OAUTH-MCP.md`, "Clients"): fetched and kept as any discoverable
//! client's is (`super::load_mcp`), then checked here; and the redirect URIs
//! its requests may name.

use super::document::{Form, form};
use super::{Failure, META};
use serde_json::{Map, Value as Json};
use std::net::{Ipv4Addr, Ipv6Addr};
use url::{Host, Url};

/// A document that fails a rule.
const REFUSED: Failure = Failure::Check(META);

/// A document the MCP issuer took.
#[derive(Debug)]
pub(super) struct Taken {
    pub redirect_uris: Vec<String>,
    /// Whether its grant types include `refresh_token`.
    pub refresh: bool,
    /// What the authorization page shows of it.
    pub shown: Json,
}

/// An `http:` URL on `127.0.0.1`, `[::1]` or `localhost`.
fn loopback(u: &Url) -> bool {
    u.scheme() == "http"
        && match u.host() {
            Some(Host::Ipv4(a)) => a == Ipv4Addr::LOCALHOST,
            Some(Host::Ipv6(a)) => a == Ipv6Addr::LOCALHOST,
            Some(Host::Domain(d)) => d == "localhost",
            None => false,
        }
}

/// Whether a redirect URI is of a form an MCP client's document may name:
/// an `https:` URL, an `http:` one on a loopback host, or a private-use
/// URI, none with a user, password or fragment.
fn redirect_form(uri: &str) -> bool {
    let Ok(u) = Url::parse(uri) else { return false };
    if !u.username().is_empty() || u.password().is_some() || u.fragment().is_some() {
        return false;
    }
    match u.scheme() {
        "https" => u.host().is_some(),
        "http" => loopback(&u),
        _ => matches!(form(uri), Some(Form::PrivateUse(_))),
    }
}

/// A JSON array of strings, as strings.
fn strings(v: Option<&Json>) -> Option<Vec<String>> {
    v?.as_array()?
        .iter()
        .map(|s| s.as_str().map(str::to_string))
        .collect()
}

/// Check the document fetched for MCP client `id`, by the rules in their
/// order: any failing is `invalid_client_metadata`.
pub(super) fn check(id: &str, doc: &Map<String, Json>) -> Result<Taken, Failure> {
    // 1. Its own client ID, character for character.
    if doc.get("client_id").and_then(Json::as_str) != Some(id) {
        return Err(REFUSED);
    }
    // 2. Redirect URIs, each of a form taken.
    let redirect_uris = strings(doc.get("redirect_uris"))
        .filter(|r| !r.is_empty() && r.iter().all(|u| redirect_form(u)))
        .ok_or(REFUSED)?;
    // 3. A public client.
    if doc.get("token_endpoint_auth_method").and_then(Json::as_str) != Some("none") {
        return Err(REFUSED);
    }
    // 4. Grant and response types, if given, with the code's.
    let listed = |k: &str, needed: &str| match doc.get(k) {
        None => Ok(None),
        v => strings(v)
            .filter(|l| l.iter().any(|t| t == needed))
            .map(Some)
            .ok_or(REFUSED),
    };
    let grants = listed("grant_types", "authorization_code")?;
    let responses = listed("response_types", "code")?;
    // What the page shows: the fields it shows of an https client, where
    // they are of their type.
    let mut shown = Map::new();
    shown.insert("client_id".into(), id.into());
    shown.insert("redirect_uris".into(), redirect_uris.clone().into());
    shown.insert("token_endpoint_auth_method".into(), "none".into());
    if let Some(g) = &grants {
        shown.insert("grant_types".into(), g.clone().into());
    }
    if let Some(r) = responses {
        shown.insert("response_types".into(), r.into());
    }
    if let Some(Json::String(n)) = doc.get("client_name") {
        shown.insert("client_name".into(), n.clone().into());
    }
    for k in ["client_uri", "logo_uri", "tos_uri", "policy_uri"] {
        if let Some(u) = doc.get(k).and_then(Json::as_str).filter(|u| {
            u.starts_with("https://") && Url::parse(u).is_ok_and(|u| u.host().is_some())
        }) {
            shown.insert(k.into(), u.into());
        }
    }
    Ok(Taken {
        redirect_uris,
        refresh: grants.is_some_and(|g| g.iter().any(|t| t == "refresh_token")),
        shown: Json::Object(shown),
    })
}

/// The redirect URI a request of an MCP client gets: the one given, if it
/// matches one of `mine`, or its only one if none is given.
pub(in crate::oauth) fn redirect_uri(mine: &[String], given: Option<&str>) -> Option<String> {
    match given {
        None => match mine {
            [only] => Some(only.clone()),
            _ => None,
        },
        Some(g) => mine.iter().any(|m| matches(m, g)).then(|| g.to_string()),
    }
}

/// Whether a redirect URI given matches one of the document's: equal, or
/// both on the same loopback host, the document's with no port, and equal
/// but for the port.
fn matches(mine: &str, given: &str) -> bool {
    if mine == given {
        return true;
    }
    let (Ok(m), Ok(mut g)) = (Url::parse(mine), Url::parse(given)) else {
        return false;
    };
    loopback(&m)
        && loopback(&g)
        && m.port().is_none()
        && g.set_port(None).is_ok()
        && m.as_str() == g.as_str()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    const ID: &str = "https://claude.example.net/oauth/client";

    fn doc(over: Json) -> Map<String, Json> {
        let mut d = json!({
            "client_id": ID, "client_name": "Claude", "client_uri": "https://claude.ai",
            "redirect_uris": ["https://claude.example.net/cb", "http://localhost/callback"],
            "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"],
            "token_endpoint_auth_method": "none",
        });
        for (k, v) in over.as_object().unwrap() {
            if v.is_null() {
                d.as_object_mut().unwrap().remove(k);
            } else {
                d[k] = v.clone();
            }
        }
        d.as_object().unwrap().clone()
    }

    /// Claude's shape is taken, with no scope, DPoP or application type;
    /// each rule refuses what it says.
    #[test]
    fn rules() {
        let t = check(ID, &doc(json!({}))).unwrap();
        assert!(t.refresh);
        assert_eq!(t.shown["client_name"], "Claude");
        assert!(
            !check(ID, &doc(json!({ "grant_types": null })))
                .unwrap()
                .refresh
        );
        for (why, over) in [
            (
                "another client_id",
                json!({ "client_id": format!("{ID}/") }),
            ),
            ("no client_id", json!({ "client_id": null })),
            ("no redirect URIs", json!({ "redirect_uris": [] })),
            (
                "an http redirect off loopback",
                json!({ "redirect_uris": ["http://example.net/cb"] }),
            ),
            (
                "a fragment",
                json!({ "redirect_uris": ["https://claude.example.net/cb#x"] }),
            ),
            (
                "a user",
                json!({ "redirect_uris": ["https://u@claude.example.net/cb"] }),
            ),
            (
                "no auth method",
                json!({ "token_endpoint_auth_method": null }),
            ),
            (
                "a confidential client",
                json!({ "token_endpoint_auth_method": "private_key_jwt" }),
            ),
            ("no code grant", json!({ "grant_types": ["refresh_token"] })),
            ("no code response", json!({ "response_types": ["token"] })),
        ] {
            assert_eq!(check(ID, &doc(over)).err(), Some(REFUSED), "{why}");
        }
        for ok in [
            "http://127.0.0.1:8080/cb",
            "http://[::1]/cb",
            "net.example.claude:/cb",
        ] {
            assert!(
                check(ID, &doc(json!({ "redirect_uris": [ok] }))).is_ok(),
                "{ok}"
            );
        }
    }

    /// A loopback redirect URI with no port matches any port on its host.
    #[test]
    fn redirects() {
        let mine = ["http://localhost/callback".to_string()];
        assert_eq!(
            redirect_uri(&mine, Some("http://localhost:51234/callback")).as_deref(),
            Some("http://localhost:51234/callback")
        );
        assert_eq!(redirect_uri(&mine, None).as_deref(), Some(mine[0].as_str()));
        for no in [
            "http://127.0.0.1:51234/callback",
            "http://localhost:1/other",
            "https://localhost/callback",
        ] {
            assert_eq!(redirect_uri(&mine, Some(no)), None, "{no}");
        }
        let ported = ["http://localhost:1/callback".to_string()];
        assert_eq!(
            redirect_uri(&ported, Some("http://localhost:2/callback")),
            None
        );
    }
}