~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
506 lines · 18.1 KB Raw History
//! The MCP issuer (`spec/OAUTH-MCP.md`): a second issuer beside the atproto
//! one, for MCP clients, whose tokens are for the MCP endpoint alone. Its
//! metadata and the MCP endpoint's; its authorization endpoint, which keeps
//! a request as PAR does and sends the browser on to the authorization
//! page, which serves it as any other (`super::page`); its token and
//! revocation endpoints, with no DPoP; and what `/mcp` asks of a bearer
//! token (`access`).
//!
//! An MCP issuer's request is one with a `resource` (`Request::mcp`), and an
//! MCP session one marked `mcp`; each is kept, logged and ended as an
//! atproto one is, with no DPoP key. Its tokens are sealed for labels of
//! their own (`super::labels`), and each issuer takes only its own codes,
//! so that neither takes the other's.

use super::{
    Out, Params, REQUEST_LIFE, REQUEST_URI, Tx, clients, document, exchange, finish, json_response,
    labels, low, ok, page, pending_key, refresh, refuse, scope, session_of, set, sets, too_large,
    unavailable, valid_locales,
};
use crate::{Service, Shared};
use axum::{
    Extension,
    extract::State as AxState,
    http::{HeaderMap, Method, StatusCode, Uri},
    response::{IntoResponse, Response},
};
use serde_json::{Value as Json, json};

/// The scope a request that names none asks for.
const DEFAULT_SCOPE: &str = "atproto transition:generic";

/// The resource: the MCP endpoint, `<origin>/mcp`.
fn resource(svc: &Service) -> String {
    format!("{}/mcp", svc.oauth.issuer)
}

/// The URL of the resource's metadata, which the endpoint's challenge names.
pub(crate) fn resource_metadata(svc: &Service) -> String {
    format!(
        "{}/.well-known/oauth-protected-resource/mcp",
        svc.oauth.issuer
    )
}

/// Whether `given` names the resource of the server at `issuer`: equal to
/// it, but for its scheme and host, which may be in any case.
fn is_resource(issuer: &str, given: &str) -> bool {
    let want = format!("{issuer}/mcp");
    let (Some((ws, wrest)), Some((gs, grest))) = (want.split_once("://"), given.split_once("://"))
    else {
        return false;
    };
    let authority = |r: &str| r.find(['/', '?', '#']).unwrap_or(r.len());
    let (wa, wp) = wrest.split_at(authority(wrest));
    let (ga, gp) = grest.split_at(authority(grest));
    gs.eq_ignore_ascii_case(ws) && ga.eq_ignore_ascii_case(wa) && gp == wp
}

/// `GET /.well-known/oauth-protected-resource/mcp`.
pub(super) async fn protected_resource(AxState(svc): AxState<Shared>) -> Response {
    let doc = json!({
        "resource": resource(&svc), "authorization_servers": [svc.oauth.mcp_issuer()],
        "scopes_supported": ["atproto", "transition:generic"],
        "bearer_methods_supported": ["header"], "resource_documentation": "https://atproto.com",
    });
    let mut r = json_response(200, &doc);
    set(&mut r, "access-control-allow-origin", "*");
    r
}

/// `/.well-known/oauth-authorization-server/oauth/mcp`.
pub(super) async fn authorization_server(
    AxState(svc): AxState<Shared>,
    method: Method,
) -> Response {
    let iss = svc.oauth.mcp_issuer();
    let resource = resource(&svc);
    document(&method, || {
        json!({
            "issuer": iss,
            "authorization_endpoint": format!("{iss}/authorize"),
            "token_endpoint": format!("{iss}/token"),
            "revocation_endpoint": format!("{iss}/revoke"),
            "scopes_supported": super::SCOPES_SUPPORTED,
            "response_types_supported": ["code"],
            "response_modes_supported": ["query"],
            "grant_types_supported": ["authorization_code", "refresh_token"],
            "code_challenge_methods_supported": ["S256"],
            "token_endpoint_auth_methods_supported": ["none"],
            "client_id_metadata_document_supported": true,
            "authorization_response_iss_parameter_supported": true,
            "protected_resources": [resource],
        })
    })
}

/// `GET /oauth/mcp/authorize`: the request checked in the order
/// `spec/OAUTH-MCP.md` gives, kept as PAR keeps one, and the browser sent
/// on to the authorization page.
pub(super) async fn authorize(
    AxState(svc): AxState<Shared>,
    method: Method,
    headers: HeaderMap,
    uri: Uri,
    peer: Option<Extension<crate::limits::Peer>>,
) -> Response {
    if method != Method::GET {
        return StatusCode::NOT_FOUND.into_response();
    }
    let address = crate::limits::client(
        &svc.config.trusted_proxies,
        &headers,
        peer.map(|Extension(p)| p.0),
    );
    finish(async move { request(&svc, &uri, &address).await }).await
}

async fn request(svc: &Shared, uri: &Uri, address: &str) -> Response {
    let q = page::query(uri);
    if let Some((k, _)) = q
        .iter()
        .enumerate()
        .find(|(i, (k, _))| q[..*i].iter().any(|(j, _)| j == k))
        .map(|(_, p)| p)
    {
        return page::bad_page(&format!("Parameter {k} is given more than once"));
    }
    let p = Params(q.into_iter().map(|(k, v)| (k, Json::String(v))).collect());
    let text = |k: &str| p.text(k).ok().flatten();
    // 1. Its client.
    let Some(client_id) = p.filled("client_id") else {
        return page::bad_page("client_id is required");
    };
    let client = match clients::load_mcp(svc, client_id).await {
        Ok(c) => c,
        Err(f) => return page::error_page(400, f.error(), "Invalid client_id"),
    };
    // 2. Its redirect URI.
    let Some(redirect_uri) = clients::mcp_redirect_uri(&client.redirect_uris, text("redirect_uri"))
    else {
        return page::bad_page("redirect_uri is not one of the client's");
    };
    // Past those, a refusal goes back to the client.
    let state = text("state").unwrap_or_default();
    let issuer = svc.oauth.mcp_issuer();
    let refused = |error: &str, description: &str| {
        let mut params = vec![
            ("error", error.to_string()),
            ("error_description", description.to_string()),
            ("iss", issuer.clone()),
        ];
        if !state.is_empty() {
            params.push(("state", state.to_string()));
        }
        page::redirect_to("query", &redirect_uri, &params)
    };
    // 3-6.
    if text("response_type") != Some("code") {
        return refused(
            "unsupported_response_type",
            "Only the code response type is supported",
        );
    }
    let Some(challenge) = p
        .filled("code_challenge")
        .filter(|_| text("code_challenge_method") == Some("S256"))
    else {
        return refused(
            "invalid_request",
            "code_challenge is required, with code_challenge_method S256",
        );
    };
    if !text("resource").is_some_and(|r| is_resource(&svc.oauth.issuer, r)) {
        return refused(
            "invalid_target",
            "resource must be this server's MCP endpoint",
        );
    }
    let scope_string = text("scope").unwrap_or(DEFAULT_SCOPE);
    let tokens = scope::tokens(scope_string);
    if !scope::valid(scope_string) || !tokens.contains(&"atproto") {
        return refused("invalid_scope", "The atproto scope is required");
    }
    if tokens.contains(&"openid") {
        return refused("invalid_scope", "OpenID is not supported");
    }
    let kept_scope = scope::kept(&tokens);
    if let Err((nsid, why)) = svc.oauth.sets.resolve_all(svc, &kept_scope).await {
        let description = match why {
            sets::Unresolved::Fails(_) => format!("Permission set {nsid} could not be resolved"),
            sets::Unresolved::NotASet | sets::Unresolved::NotASpace => {
                format!("{nsid} is not a permission set")
            }
        };
        return refused("invalid_scope", &description);
    }
    // The rest as PAR takes them, of a public client.
    let login_hint = text("login_hint").map(str::to_lowercase);
    if login_hint.as_deref().is_some_and(|h| {
        h.is_empty() || (!pds_repo::data::valid_handle(h) && !pds_repo::data::valid_did(h))
    }) {
        return refused(
            "invalid_request",
            "login_hint is neither a handle nor a DID",
        );
    }
    match text("prompt") {
        None | Some("login" | "consent" | "select_account" | "create") => {}
        Some("none") => {
            return refused(
                "invalid_request",
                "A public client may not sign in silently",
            );
        }
        Some(_) => return refused("invalid_request", "prompt is not a prompt"),
    }
    if text("ui_locales").is_some_and(|l| !valid_locales(l)) {
        return refused("invalid_request", "ui_locales is not language tags");
    }
    if let Some(why) = too_large(&p) {
        return refused("invalid_request", why);
    }
    // Kept as PAR keeps a request, the MCP issuer's.
    let addr = pending_key(address);
    let id = format!("req-{}", hex::encode(rand::random::<[u8; 16]>()));
    let low = low(svc);
    let resource = resource(svc);
    let mut tx = Tx::new(svc);
    let kept = tx.change(|st, now| {
        if let Some(why) = st.pending.full(&addr) {
            return (vec![], Err((429, "invalid_request", why)));
        }
        if low {
            return (
                vec![],
                Err((
                    507,
                    "temporarily_unavailable",
                    "Not enough free space to store this",
                )),
            );
        }
        let entry = json!({
            "t": "oauthRequest", "id": id, "client": client_id, "redirectUri": redirect_uri, "scope": kept_scope,
            "state": state, "codeChallenge": challenge, "loginHint": login_hint,
            "prompt": if text("prompt") == Some("create") { "create" } else { "consent" },
            "responseMode": "query", "uiLocales": text("ui_locales"),
            "jkt": "", "expires": now + REQUEST_LIFE, "addr": addr, "resource": resource,
        });
        (vec![entry], Ok(()))
    });
    if !tx.done().await {
        return page::error_page(500, "server_error", "Internal server error");
    }
    if let Err((status, error, why)) = kept {
        return page::error_page(status, error, why);
    }
    let q = url::form_urlencoded::Serializer::new(String::new())
        .append_pair("client_id", client_id)
        .append_pair("request_uri", &format!("{REQUEST_URI}{id}"))
        .finish();
    let mut r = StatusCode::SEE_OTHER.into_response();
    set(&mut r, "location", &format!("/oauth/authorize?{q}"));
    set(&mut r, "cache-control", "no-store");
    r
}

/// What would keep something, below the free-space floor: refused with
/// `507`, changing nothing (`spec/OAUTH.md`, "Free space").
fn unless_low(low: bool, (entries, out): (Vec<Json>, Out)) -> (Vec<Json>, Out) {
    if low && !entries.is_empty() {
        return (vec![], unavailable());
    }
    (entries, out)
}

/// `POST /oauth/mcp/token`, checked in the order `spec/OAUTH-MCP.md` gives:
/// `OAUTH.md`'s grants, but for the DPoP key, of the MCP issuer's codes and
/// sessions alone.
pub(super) async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) -> Out {
    let p = match Params::of(headers, body) {
        Ok(p) => p,
        Err(out) => return out,
    };
    let Some(client_id) = p.filled("client_id") else {
        return refuse(400, "invalid_request", "client_id is required");
    };
    let Ok(client) = clients::load_mcp(svc, client_id).await else {
        return refuse(400, "invalid_client", "Invalid client_id");
    };
    let filled = |k: &str| p.filled(k).is_some();
    let grant_type = p.filled("grant_type");
    match grant_type {
        Some("authorization_code")
            if filled("code") && filled("redirect_uri") && filled("code_verifier") => {}
        Some("refresh_token") if filled("refresh_token") => {}
        None | Some("authorization_code" | "refresh_token") => {
            return refuse(
                400,
                "invalid_request",
                "grant_type and its parameters are required",
            );
        }
        Some(_) => return refuse(400, "unsupported_grant_type", "Unsupported grant_type"),
    }
    if p.get("resource").is_some_and(|r| {
        !r.as_str()
            .is_some_and(|r| is_resource(&svc.oauth.issuer, r))
    }) {
        return refuse(
            400,
            "invalid_target",
            "resource must be this server's MCP endpoint",
        );
    }
    let low = low(svc);
    if grant_type == Some("authorization_code") {
        let (code, redirect_uri, verifier) = (
            p.filled("code").unwrap_or_default(),
            p.filled("redirect_uri").unwrap_or_default(),
            p.filled("code_verifier"),
        );
        // The sets and declarations the code's scope names, resolved again, with no lock held.
        let approved = svc.oauth.approved_scope(code);
        let sets = svc.oauth.sets.for_token(svc, &approved).await.ok();
        let mut out = tx.change(|st, now| {
            unless_low(
                low,
                exchange(
                    svc,
                    st,
                    now,
                    low,
                    client_id,
                    true,
                    "",
                    None,
                    code,
                    redirect_uri,
                    verifier,
                    sets.as_ref(),
                ),
            )
        });
        // A client without the refresh grant is given no refresh token.
        if !client.refresh
            && let Some(body) = out.body.as_object_mut()
        {
            body.remove("refresh_token");
        }
        return out;
    }
    if !client.refresh {
        return refuse(
            400,
            "unauthorized_client",
            "The client does not have the refresh_token grant",
        );
    }
    let token = p.filled("refresh_token").unwrap_or_default();
    // The session's sets and declarations, resolved again, with no lock held.
    let consented = svc.oauth.session_scope(labels(true).1, token);
    let sets = svc.oauth.sets.for_token(svc, &consented).await.ok();
    tx.change(|st, now| {
        unless_low(
            low,
            refresh(
                svc,
                st,
                now,
                client_id,
                true,
                "",
                None,
                token,
                sets.as_ref(),
            ),
        )
    })
}

/// `POST /oauth/mcp/revoke` (RFC 7009): `200 {}` whatever the token; an MCP
/// session's current access token, or a refresh token of it current or
/// replaced, ends it if it is this client's.
pub(super) fn revoke(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) -> Out {
    let p = match Params::of(headers, body) {
        Ok(p) => p,
        Err(out) => return out,
    };
    let hint = p.text("token_type_hint");
    let (Some(client_id), Some(token)) = (p.filled("client_id"), p.filled("token")) else {
        return refuse(
            400,
            "invalid_request",
            "client_id and token are required, and token_type_hint must be a token type",
        );
    };
    if !hint.is_ok_and(|h| h.is_none_or(|h| ["access_token", "refresh_token"].contains(&h))) {
        return refuse(
            400,
            "invalid_request",
            "client_id and token are required, and token_type_hint must be a token type",
        );
    }
    let low = low(svc);
    tx.change(|st, _| {
        let end = session_of(svc, st, token, true)
            .filter(|(_, s)| s.client_id == client_id)
            .map(|(sid, _)| json!({ "t": "oauthEndSession", "sid": sid }));
        unless_low(low, (end.into_iter().collect(), ok(200, json!({}))))
    })
}

/// What a `Bearer` token at the MCP endpoint is, of the MCP issuer's.
pub(crate) enum Token {
    /// None it gave: answered as XRPC answers it.
    Not,
    /// One it gave that no longer works: expired, replaced, or its session
    /// ended.
    Gone,
    /// An MCP session's current access token, unexpired: its account and scope.
    Good(super::Access),
}

/// What `/mcp` makes of `Authorization: Bearer <token>` (`spec/OAUTH-MCP.md`,
/// "Tokens at the MCP endpoint").
pub(crate) fn access(svc: &Service, token: &str) -> Token {
    let Some((sid, jti)) = svc.oauth.token_of(labels(true).0, token) else {
        return Token::Not;
    };
    let now = svc.sessions.now();
    let session = svc
        .oauth
        .lock()
        .sessions
        .get(&sid)
        .filter(|s| s.mcp && s.access == jti && now < s.access_exp)
        .cloned();
    match session {
        Some(s) if svc.account(&s.did).is_some() => Token::Good(super::Access {
            did: s.did,
            scope: s.granted,
        }),
        _ => Token::Gone,
    }
}

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

    #[test]
    fn resources() {
        let iss = "http://127.0.0.1:2583";
        for ok in [
            "http://127.0.0.1:2583/mcp",
            "HTTP://127.0.0.1:2583/mcp",
            "Http://127.0.0.1:2583/mcp",
        ] {
            assert!(is_resource(iss, ok), "{ok}");
        }
        assert!(is_resource(
            "https://pds.example.net",
            "https://PDS.Example.NET/mcp"
        ));
        for no in [
            "http://127.0.0.1:2583/MCP",
            "http://127.0.0.1:2583/mcp/",
            "http://127.0.0.1:2583/elsewhere",
            "http://127.0.0.1:2584/mcp",
            "https://127.0.0.1:2583/mcp",
            "http://127.0.0.1:2583",
            "",
        ] {
            assert!(!is_resource(iss, no), "{no}");
        }
    }

    /// Neither issuer's tokens are the other's.
    #[test]
    fn tokens_apart() {
        let oauth = super::super::OAuth::open(
            std::path::Path::new("/nonexistent/oauth-mcp-test"),
            "http://127.0.0.1:2583",
            None,
        )
        .unwrap();
        for mcp in [false, true] {
            let (access, refresh) = labels(mcp);
            let (other_access, other_refresh) = labels(!mcp);
            let a = oauth.token(access, "sid", "jti");
            let r = oauth.token(refresh, "sid", "jti");
            assert!(oauth.token_of(access, &a).is_some());
            for (label, t) in [
                (other_access, &a),
                (other_refresh, &a),
                (refresh, &a),
                (other_access, &r),
                (other_refresh, &r),
                (access, &r),
            ] {
                assert_eq!(oauth.token_of(label, t), None, "{label} {mcp}");
            }
        }
    }
}