chadtmiller.com/monolith
An atproto PDS
0
0
OAuth for MCP clients: Claude signs in, through an issuer of its own
crates/pds-server/src/oauth/clients/document.rs+2−2
| @@ -84,7 +84,7 @@ pub(super) fn client_id(id: &str) -> Result<Url, &'static str> { | ||
} | ||
| ||
/// A redirect URI's form. | ||
enum Form { | ||
pub(super) enum Form { | ||
Https(Url), | ||
Loopback(Url), | ||
/// Its scheme. | ||
| @@ -106,7 +106,7 @@ fn https_url(uri: &str) -> Option<Url> { | ||
ok.then_some(u) | ||
} | ||
| ||
fn form(uri: &str) -> Option<Form> { | ||
pub(super) fn form(uri: &str) -> Option<Form> { | ||
if let Some(u) = https_url(uri) { | ||
return Some(Form::Https(u)); | ||
} | ||
crates/pds-server/src/oauth/clients/mcp.rsnew+244−0
| @@ -0,0 +1,244 @@ | ||
//! 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 | ||
); | ||
} | ||
} | ||
crates/pds-server/src/oauth/clients.rs+52−2
| @@ -1,8 +1,9 @@ | ||
//! Discoverable clients, whose `client_id` is an `https://` URL, as | ||
//! `spec/OAUTH-CLIENTS.md` says: their documents and JWKS, fetched | ||
//! (`fetch`), checked (`document`) and kept 10 minutes; confidential | ||
//! clients' authentication with `private_key_jwt` (`assertion`); and silent | ||
//! sign-in (`silent`). | ||
//! clients' authentication with `private_key_jwt` (`assertion`); silent | ||
//! sign-in (`silent`); and MCP clients, whose documents are fetched and kept | ||
//! alike but held to MCP's rules (`mcp`, `spec/OAUTH-MCP.md`). | ||
//! | ||
//! Documents and JWKS are kept in memory only, each cache behind its own | ||
//! lock, never held across a fetch: a restart forgets them. What must | ||
| @@ -12,12 +13,14 @@ | ||
mod assertion; | ||
mod document; | ||
mod fetch; | ||
mod mcp; | ||
pub(super) mod silent; | ||
#[cfg(test)] | ||
mod tests; | ||
| ||
pub(super) use assertion::authenticate; | ||
pub(crate) use fetch::ClientFetch; | ||
pub(super) use mcp::redirect_uri as mcp_redirect_uri; | ||
| ||
use super::client::{self, Client}; | ||
use crate::Service; | ||
| @@ -100,6 +103,8 @@ pub(crate) struct Clients { | ||
fetcher: fetch::Fetcher, | ||
documents: Cache<Arc<document::Taken>>, | ||
jwks: Cache<Arc<Vec<Map<String, Json>>>>, | ||
/// MCP clients' documents, taken by MCP's rules. | ||
mcp_documents: Cache<Arc<mcp::Taken>>, | ||
} | ||
| ||
impl Clients { | ||
| @@ -108,6 +113,7 @@ impl Clients { | ||
fetcher: fetch::Fetcher::new(dev), | ||
documents: Cache::new(), | ||
jwks: Cache::new(), | ||
mcp_documents: Cache::new(), | ||
} | ||
} | ||
} | ||
| @@ -160,6 +166,50 @@ pub(super) async fn load_why(svc: &Service, id: &str) -> Result<Client, Failure> | ||
}) | ||
} | ||
| ||
/// An MCP client (`spec/OAUTH-MCP.md`, "Clients"): its document fetched or | ||
/// kept as any discoverable client's, then held to MCP's rules. A | ||
/// `client_id` that is not an https one as `spec/OAUTH-CLIENTS.md` has it | ||
/// is `invalid_client`. | ||
pub(super) async fn load_mcp(svc: &Service, id: &str) -> Result<Client, Failure> { | ||
const INVALID: Failure = Failure::Id("invalid_client"); | ||
if !discoverable(id) { | ||
return Err(INVALID); | ||
} | ||
let url = document::client_id(id).map_err(|_| INVALID)?; | ||
let clients = &svc.oauth.clients; | ||
let taken = match clients.mcp_documents.get(id, svc.sessions.now()) { | ||
Some(t) => t, | ||
None => { | ||
let doc = clients | ||
.fetcher | ||
.get(&svc.outbound, &url, fetch::Kind::Document) | ||
.await | ||
.map_err(|_| Failure::Unusable)?; | ||
let t = Arc::new(mcp::check(id, &doc)?); | ||
clients.mcp_documents.put(id, svc.sessions.now(), t.clone()); | ||
t | ||
} | ||
}; | ||
Ok(Client { | ||
id: id.to_string(), | ||
scope: String::new(), | ||
redirect_uris: taken.redirect_uris.clone(), | ||
refresh: taken.refresh, | ||
keys: None, | ||
document: Some(taken.shown.clone()), | ||
}) | ||
} | ||
| ||
/// The client of a request, loaded as its issuer loads it: the MCP | ||
/// issuer's (`mcp`) by `load_mcp`, the atproto one's by `load_why`. | ||
pub(super) async fn load_for(svc: &Service, id: &str, mcp: bool) -> Result<Client, Failure> { | ||
if mcp { | ||
load_mcp(svc, id).await | ||
} else { | ||
load_why(svc, id).await | ||
} | ||
} | ||
| ||
/// The client keys of the JWKS at `url`, fetched or kept. | ||
async fn jwks(svc: &Service, url: &url::Url) -> Result<Arc<Vec<Map<String, Json>>>, Failure> { | ||
let clients = &svc.oauth.clients; | ||
crates/pds-server/src/oauth/mcp.rsnew+504−0
504 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/page.rs+30−17
| @@ -185,7 +185,7 @@ fn page(status: u16, title: &'static str, data: &[(&str, &Json)]) -> Response { | ||
r | ||
} | ||
| ||
fn error_page(status: u16, error: &str, description: &str) -> Response { | ||
pub(super) fn error_page(status: u16, error: &str, description: &str) -> Response { | ||
page( | ||
status, | ||
"Something went wrong", | ||
| @@ -196,12 +196,12 @@ fn error_page(status: u16, error: &str, description: &str) -> Response { | ||
) | ||
} | ||
| ||
fn bad_page(description: &str) -> Response { | ||
pub(super) fn bad_page(description: &str) -> Response { | ||
error_page(400, "invalid_request", description) | ||
} | ||
| ||
/// Send the browser to a client's `redirect_uri` with `params`, as its response mode says. | ||
fn redirect_to(mode: &str, redirect_uri: &str, params: &[(&str, String)]) -> Response { | ||
pub(super) fn redirect_to(mode: &str, redirect_uri: &str, params: &[(&str, String)]) -> Response { | ||
let Ok(mut u) = url::Url::parse(redirect_uri) else { | ||
return bad_page("Invalid redirect_uri"); | ||
}; | ||
| @@ -253,6 +253,17 @@ fn redirect_to(mode: &str, redirect_uri: &str, params: &[(&str, String)]) -> Res | ||
} | ||
} | ||
| ||
/// The parameters a request's redirect back carries before its code or | ||
/// error: `iss`, its issuer's, and its `state`, if it has one (an MCP | ||
/// client's request may have none). | ||
fn back_params(svc: &Service, r: &Request) -> Vec<(&'static str, String)> { | ||
let mut params = vec![("iss", svc.oauth.issuer_of(r))]; | ||
if !r.state.is_empty() { | ||
params.push(("state", r.state.clone())); | ||
} | ||
params | ||
} | ||
| ||
/// The parameters of a request's error, as its redirect carries them. | ||
fn error_params( | ||
svc: &Service, | ||
| @@ -260,12 +271,10 @@ fn error_params( | ||
error: &str, | ||
description: &str, | ||
) -> Vec<(&'static str, String)> { | ||
vec![ | ||
("iss", svc.oauth.issuer.clone()), | ||
("state", r.state.clone()), | ||
("error", error.into()), | ||
("error_description", description.into()), | ||
] | ||
let mut params = back_params(svc, r); | ||
params.push(("error", error.into())); | ||
params.push(("error_description", description.into())); | ||
params | ||
} | ||
| ||
/// The id a `request_uri` names, if it is of the form the server gives. | ||
| @@ -275,8 +284,8 @@ fn request_id(request_uri: &str) -> Option<&str> { | ||
.filter(|id| !id.is_empty()) | ||
} | ||
| ||
/// A request's query parameters; the first of a name counts. | ||
fn query(uri: &Uri) -> Vec<(String, String)> { | ||
/// A request's query parameters, every one as given. | ||
pub(super) fn query(uri: &Uri) -> Vec<(String, String)> { | ||
url::form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) | ||
.into_owned() | ||
.collect() | ||
| @@ -360,9 +369,11 @@ pub(super) async fn authorize( | ||
return bad_page("client_id and request_uri are required: requests must be pushed (PAR)"); | ||
}; | ||
let Some(id) = request_id(request_uri) else { return bad_page("Invalid request_uri") }; | ||
let client = match clients::load(&svc, client_id).await { | ||
// An MCP issuer's request's client is loaded as that issuer loads it. | ||
let mcp = svc.oauth.lock().requests.get(id).is_some_and(Request::mcp); | ||
let client = match clients::load_for(&svc, client_id, mcp).await { | ||
Ok(c) => c, | ||
Err(e) => return error_page(400, e, "Invalid client_id"), | ||
Err(e) => return error_page(400, e.error(), "Invalid client_id"), | ||
}; | ||
let mut tx = Tx::new(&svc); | ||
let device = device(&svc, &mut tx, &headers); | ||
| @@ -1036,18 +1047,18 @@ async fn consent( | ||
let low = super::low(svc); | ||
let first = tx.change(|st: &State, now| { | ||
match consent_checks(svc, st, now, id, device, did, signed_by_token) { | ||
Ok(r) => (vec![], Ok(r.client_id.clone())), | ||
Ok(r) => (vec![], Ok((r.client_id.clone(), r.mcp()))), | ||
Err(unapproved) => { | ||
let (entries, answer) = unless_low(low, unapproved); | ||
(entries, Err(answer)) | ||
} | ||
} | ||
}); | ||
let client_id = match first { | ||
let (client_id, mcp) = match first { | ||
Ok(c) => c, | ||
Err(answer) => return answer, | ||
}; | ||
let loaded = clients::load_why(svc, &client_id).await; | ||
let loaded = clients::load_for(svc, &client_id, mcp).await; | ||
tx.change(changing(low, |st: &State, now| { | ||
let r = match consent_checks(svc, st, now, id, device, did, signed_by_token) { | ||
Ok(r) => r, | ||
| @@ -1074,7 +1085,9 @@ async fn consent( | ||
entries.push(json!({ "t": "oauthLoad", "id": id, "device": device, "expires": r.expires })); | ||
} | ||
entries.push(json!({ "t": "oauthApprove", "id": id, "code": code, "did": did, "scope": scope, "at": now })); | ||
let url = redirect_url(svc, r, &[("iss", svc.oauth.issuer.clone()), ("state", r.state.clone()), ("code", code)]); | ||
let mut back = back_params(svc, r); | ||
back.push(("code", code)); | ||
let url = redirect_url(svc, r, &back); | ||
(entries, Ok(json!({ "url": url }))) | ||
})) | ||
} | ||
crates/pds-server/src/mcp.rs+82−5
| @@ -7,8 +7,9 @@ | ||
//! method with a JSON answer, or none, is a tool, called through the same | ||
//! handling as XRPC. | ||
| ||
use crate::oauth::mcp::Token as McpToken; | ||
use crate::sessions::Bearer; | ||
use crate::{Auth, Call, Resp, Shared, answer, authorization, limits}; | ||
use crate::{Auth, Call, Resp, Shared, answer, authorization, limits, scopes}; | ||
use axum::body::Body; | ||
use axum::extract::{Extension, State}; | ||
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header}; | ||
| @@ -35,12 +36,15 @@ const INVALID_PARAMS: i64 = -32602; | ||
const HEADER_MISMATCH: i64 = -32020; | ||
const UNSUPPORTED_PROTOCOL_VERSION: i64 = -32022; | ||
| ||
/// A JSON-RPC error, with the HTTP status it is answered with. | ||
/// A JSON-RPC error, with the HTTP status it is answered with; or, with a | ||
/// `challenge`, an HTTP `401` with that `WWW-Authenticate: Bearer` | ||
/// challenge, and `message` its `error_description` (`spec/OAUTH-MCP.md`). | ||
struct RpcError { | ||
status: StatusCode, | ||
code: i64, | ||
message: String, | ||
data: Option<Json>, | ||
challenge: Option<String>, | ||
} | ||
| ||
fn rpc_err(status: StatusCode, code: i64, message: impl Into<String>) -> RpcError { | ||
| @@ -49,6 +53,24 @@ fn rpc_err(status: StatusCode, code: i64, message: impl Into<String>) -> RpcErro | ||
code, | ||
message: message.into(), | ||
data: None, | ||
challenge: None, | ||
} | ||
} | ||
| ||
/// The `401` that has a client sign in, or sign in again: `error`, if any, | ||
/// names what is wrong with the token it sent (`spec/OAUTH-MCP.md`, | ||
/// "Tokens at the MCP endpoint"). | ||
fn challenge(st: &Shared, error: Option<&str>, description: &str) -> RpcError { | ||
let metadata = crate::oauth::mcp::resource_metadata(st); | ||
let challenge = match error { | ||
Some(e) => format!("Bearer error=\"{e}\", resource_metadata=\"{metadata}\""), | ||
None => { | ||
format!("Bearer resource_metadata=\"{metadata}\", scope=\"atproto transition:generic\"") | ||
} | ||
}; | ||
RpcError { | ||
challenge: Some(challenge), | ||
..rpc_err(StatusCode::UNAUTHORIZED, INVALID_REQUEST, description) | ||
} | ||
} | ||
| ||
| @@ -211,6 +233,19 @@ fn reply(status: StatusCode, message: &Json, sse: bool) -> Response { | ||
} | ||
| ||
fn error_response(id: Option<Json>, e: RpcError, sse: bool) -> Response { | ||
if let Some(c) = e.challenge { | ||
let body = json!({ "error": "invalid_token", "error_description": e.message }); | ||
let mut r = ( | ||
StatusCode::UNAUTHORIZED, | ||
[(header::CONTENT_TYPE, "application/json")], | ||
body.to_string(), | ||
) | ||
.into_response(); | ||
if let Ok(v) = HeaderValue::from_str(&c) { | ||
r.headers_mut().insert(header::WWW_AUTHENTICATE, v); | ||
} | ||
return r; | ||
} | ||
let mut error = json!({ "code": e.code, "message": e.message }); | ||
if let Some(data) = e.data { | ||
error["data"] = data; | ||
| @@ -394,6 +429,7 @@ async fn modern( | ||
code: UNSUPPORTED_PROTOCOL_VERSION, | ||
message: "Unsupported protocol version".into(), | ||
data: Some(json!({ "supported": SUPPORTED, "requested": version })), | ||
challenge: None, | ||
}); | ||
} | ||
let header_method = required_header(headers, "mcp-method")?; | ||
| @@ -533,7 +569,11 @@ fn param_text(v: &Json) -> String { | ||
| ||
/// Call a tool's method, with its arguments as the query's parameters or the | ||
/// procedure's input, and the request's `Authorization` header, from `client`: | ||
/// its answer, and whether it is an error the method answered. | ||
/// its answer, and whether it is an error the method answered. An MCP | ||
/// session's access token makes the call its account's, with its scope, as | ||
/// an OAuth access token makes an XRPC call; one the MCP issuer gave that no | ||
/// longer works, or no token where the method needs one, is the challenge | ||
/// that has the client sign in (`spec/OAUTH-MCP.md`). | ||
async fn call_tool( | ||
st: &Shared, | ||
name: &str, | ||
| @@ -560,9 +600,30 @@ async fn call_tool( | ||
)); | ||
} | ||
}; | ||
let mcp = match bearer { | ||
Bearer::Token(t) => match crate::oauth::mcp::access(st, t) { | ||
McpToken::Not => None, | ||
McpToken::Gone => { | ||
return Err(challenge( | ||
st, | ||
Some("invalid_token"), | ||
"The access token is expired, replaced or revoked", | ||
)); | ||
} | ||
McpToken::Good(a) => Some((t, a)), | ||
}, | ||
_ => None, | ||
}; | ||
// A `repo` or `did` left out is the token's account's; with no token, or | ||
// one the server did not give out, it stays out, for the method to answer. | ||
if let Auth::Account(did) = st.auth(bearer) { | ||
let did = match &mcp { | ||
Some((_, a)) => Some(a.did.clone()), | ||
None => match st.auth(bearer) { | ||
Auth::Account(did) => Some(did), | ||
_ => None, | ||
}, | ||
}; | ||
if let Some(did) = did { | ||
for a in m.args.iter().filter(|a| a.names_account()) { | ||
args.entry(a.name.clone()).or_insert_with(|| json!(did)); | ||
} | ||
| @@ -597,7 +658,8 @@ async fn call_tool( | ||
{ | ||
headers.insert(header::AUTHORIZATION, v); | ||
} | ||
let call = Call { | ||
let mut grant = None; | ||
let mut call = Call { | ||
nsid: &m.nsid, | ||
method: &method, | ||
params: ¶ms, | ||
| @@ -608,6 +670,17 @@ async fn call_tool( | ||
charged: OnceLock::new(), | ||
http: None, | ||
}; | ||
if let Some((token, access)) = mcp { | ||
match scopes::look_mcp(st, &call, access) { | ||
Ok(Some(g)) => grant = Some(g), | ||
// A method that reads no OAuth token answers it as XRPC answers one sent so. | ||
Ok(None) => call.bearer = Bearer::DPoP(token), | ||
Err(e) => return Ok((json!({ "error": e.name, "message": e.message }), true)), | ||
} | ||
} | ||
if let Some(g) = &grant { | ||
call.bearer = Bearer::OAuth(g); | ||
} | ||
let (content, is_error) = match answer(st, &call).await { | ||
// A service's error is the method's, as it answered it. | ||
Ok(Resp::Upstream(u)) if u.status >= 400 => ( | ||
| @@ -636,6 +709,10 @@ async fn call_tool( | ||
json!({ "error": "InternalServerError", "message": "a tool's method answered no JSON" }), | ||
true, | ||
), | ||
// No token, where the method needs an account's: a sign-in. | ||
Err(e) if authorization.is_none() && e.status == 401 && e.name == "AuthMissing" => { | ||
return Err(challenge(st, None, &e.message)); | ||
} | ||
Err(e) => (json!({ "error": e.name, "message": e.message }), true), | ||
}; | ||
Ok((content, is_error)) | ||
crates/pds-server/src/oauth.rs+132−26
| @@ -27,6 +27,7 @@ mod assets; | ||
mod client; | ||
mod clients; | ||
mod dpop; | ||
pub(crate) mod mcp; | ||
mod page; | ||
mod scope; | ||
mod sets; | ||
| @@ -168,6 +169,17 @@ const OTHER_BODY_MAX: usize = 2 << 20; | ||
| ||
const REQUEST_URI: &str = "urn:ietf:params:oauth:request_uri:"; | ||
| ||
/// The labels a session's access and refresh tokens are sealed for: an MCP | ||
/// session's apart from an atproto one's, so that neither issuer, nor XRPC, | ||
/// takes the other's (`spec/OAUTH-MCP.md`). | ||
fn labels(mcp: bool) -> (&'static str, &'static str) { | ||
if mcp { | ||
("mcp access", "mcp refresh") | ||
} else { | ||
("access", "refresh") | ||
} | ||
} | ||
| ||
/// A pushed authorization request, as kept. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
struct Request { | ||
| @@ -194,6 +206,16 @@ struct Request { | ||
client_key: Option<String>, | ||
/// The client address it was pushed from (`pending_key`), if kept. | ||
addr: Option<String>, | ||
/// The resource an MCP issuer's request is for (`spec/OAUTH-MCP.md`): | ||
/// set, it is the MCP issuer's, and has no DPoP key. | ||
resource: Option<String>, | ||
} | ||
| ||
impl Request { | ||
/// Whether it is the MCP issuer's. | ||
fn mcp(&self) -> bool { | ||
self.resource.is_some() | ||
} | ||
} | ||
| ||
/// The requests kept and pending, not yet approved, ended or past their | ||
| @@ -331,6 +353,9 @@ struct Session { | ||
client_key: Option<String>, | ||
/// Its last token answer. | ||
refreshed: u64, | ||
/// Whether it is the MCP issuer's (`spec/OAUTH-MCP.md`): no DPoP key, | ||
/// and tokens for the MCP endpoint alone. | ||
mcp: bool, | ||
} | ||
| ||
impl Session { | ||
| @@ -419,6 +444,7 @@ impl State { | ||
approval: None, | ||
client_key: opt_text("clientKey"), | ||
addr: opt_text("addr"), | ||
resource: opt_text("resource"), | ||
}; | ||
// A request kept before addresses were is counted as of no address. | ||
self.pending | ||
| @@ -454,8 +480,9 @@ impl State { | ||
}); | ||
self.codes.insert(code, id.clone()); | ||
self.pending.remove(&id); | ||
// A discoverable client's approval is kept, for silent sign-in. | ||
if clients::discoverable(&r.client_id) { | ||
// A discoverable client's approval is kept, for silent sign-in; | ||
// an MCP client's signs it in to nothing. | ||
if clients::discoverable(&r.client_id) && !r.mcp() { | ||
let tokens = self | ||
.approved | ||
.entry(did) | ||
| @@ -503,6 +530,7 @@ impl State { | ||
refresh: text("refresh")?, | ||
client_key: opt_text("clientKey"), | ||
refreshed: number("started")?, | ||
mcp: e["mcp"].as_bool().unwrap_or(false), | ||
}; | ||
self.spend(&code)?; | ||
self.by_code.insert(code, sid.clone()); | ||
| @@ -821,6 +849,20 @@ impl OAuth { | ||
self.state.lock().unwrap_or_else(PoisonError::into_inner) | ||
} | ||
| ||
/// The MCP issuer (`spec/OAUTH-MCP.md`, "Names"). | ||
pub fn mcp_issuer(&self) -> String { | ||
format!("{}/oauth/mcp", self.issuer) | ||
} | ||
| ||
/// The issuer of a request: the MCP issuer, or the atproto one. | ||
fn issuer_of(&self, r: &Request) -> String { | ||
if r.mcp() { | ||
self.mcp_issuer() | ||
} else { | ||
self.issuer.clone() | ||
} | ||
} | ||
| ||
/// The scope a code was approved with, if it is a code to exchange: what | ||
/// the code grant resolves the sets of before it takes the lock. | ||
fn approved_scope(&self, code: &str) -> Vec<String> { | ||
| @@ -832,9 +874,10 @@ impl OAuth { | ||
.unwrap_or_default() | ||
} | ||
| ||
/// The scope, as consented, of the session a refresh token is of. | ||
fn session_scope(&self, token: &str) -> Vec<String> { | ||
let Some((sid, _)) = self.token_of("refresh", token) else { | ||
/// The scope, as consented, of the session a refresh token is of: one | ||
/// sealed for `label`. | ||
fn session_scope(&self, label: &str, token: &str) -> Vec<String> { | ||
let Some((sid, _)) = self.token_of(label, token) else { | ||
return vec![]; | ||
}; | ||
self.lock() | ||
| @@ -871,7 +914,7 @@ impl OAuth { | ||
serde_json::from_slice(&B64.decode(p).ok()?).ok() | ||
} | ||
| ||
/// A token of `kind`, `access` or `refresh`, for a session: its id and the token's. | ||
/// A token of `kind`, a label of `labels`, for a session: its id and the token's. | ||
fn token(&self, kind: &str, sid: &str, jti: &str) -> String { | ||
self.seal(kind, &json!({ "sid": sid, "jti": jti })) | ||
} | ||
| @@ -1036,6 +1079,23 @@ pub(crate) fn routes() -> Router<Shared> { | ||
.route("/oauth/assets/{name}", any(assets::asset)) | ||
.route("/oauth/authorize/redirect", any(page::redirect)) | ||
.route("/@atproto/oauth-provider/~api/{endpoint}", any(page::api)) | ||
.route( | ||
"/.well-known/oauth-protected-resource/mcp", | ||
get(mcp::protected_resource), | ||
) | ||
.route( | ||
"/.well-known/oauth-authorization-server/oauth/mcp", | ||
any(mcp::authorization_server), | ||
) | ||
.route("/oauth/mcp/authorize", any(mcp::authorize)) | ||
.route( | ||
"/oauth/mcp/token", | ||
any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::McpToken)), | ||
) | ||
.route( | ||
"/oauth/mcp/revoke", | ||
any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::McpRevoke)), | ||
) | ||
} | ||
| ||
fn set(r: &mut Response, name: &'static str, value: &str) { | ||
| @@ -1101,7 +1161,7 @@ async fn authorization_server(AxState(svc): AxState<Shared>, method: Method) -> | ||
"require_request_uri_registration": true, | ||
"request_uri_parameter_supported": true, | ||
"request_parameter_supported": false, | ||
"scopes_supported": ["atproto", "transition:email", "transition:generic", "transition:chat.bsky"], | ||
"scopes_supported": SCOPES_SUPPORTED, | ||
"subject_types_supported": ["public"], | ||
"response_types_supported": ["code"], | ||
"response_modes_supported": ["query", "fragment", "form_post"], | ||
| @@ -1120,6 +1180,14 @@ async fn authorization_server(AxState(svc): AxState<Shared>, method: Method) -> | ||
}) | ||
} | ||
| ||
/// The scopes both issuers' metadata names. | ||
const SCOPES_SUPPORTED: [&str; 4] = [ | ||
"atproto", | ||
"transition:email", | ||
"transition:generic", | ||
"transition:chat.bsky", | ||
]; | ||
| ||
async fn jwks(method: Method) -> Response { | ||
document(&method, || json!({ "keys": [] })) | ||
} | ||
| @@ -1244,9 +1312,13 @@ enum Endpoint { | ||
Par, | ||
Token, | ||
Revoke, | ||
/// The MCP issuer's (`spec/OAUTH-MCP.md`), which take no DPoP proof. | ||
McpToken, | ||
McpRevoke, | ||
} | ||
| ||
/// `/oauth/par`, `/oauth/token` and `/oauth/revoke`. | ||
/// `/oauth/par`, `/oauth/token` and `/oauth/revoke`, and the MCP issuer's | ||
/// token and revocation endpoints. | ||
async fn endpoint( | ||
AxState(svc): AxState<Shared>, | ||
method: Method, | ||
| @@ -1286,6 +1358,8 @@ async fn endpoint( | ||
Endpoint::Par => par(&svc, &mut tx, &headers, &body, &client).await, | ||
Endpoint::Token => token(&svc, &mut tx, &headers, &body).await, | ||
Endpoint::Revoke => revoke(&svc, &mut tx, &headers, &body).await, | ||
Endpoint::McpToken => mcp::token(&svc, &mut tx, &headers, &body).await, | ||
Endpoint::McpRevoke => mcp::revoke(&svc, &mut tx, &headers, &body), | ||
}; | ||
// Below the free-space floor nothing is kept, a client's assertion neither. | ||
if out.status == 507 { | ||
| @@ -1302,6 +1376,9 @@ async fn endpoint( | ||
let mut r = cors(json_response(out.status, &out.body)); | ||
set(&mut r, "cache-control", "no-store"); | ||
set(&mut r, "pragma", "no-cache"); | ||
if matches!(which, Endpoint::McpToken | Endpoint::McpRevoke) { | ||
return r; | ||
} | ||
set(&mut r, "dpop-nonce", &svc.oauth.nonce(svc.sessions.now())); | ||
let expose = match out.www { | ||
Some((error, d)) => { | ||
| @@ -1682,11 +1759,13 @@ fn verifier_form(v: &str) -> bool { | ||
.all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b)) | ||
} | ||
| ||
/// A new session's or refresh's tokens, as the token endpoint answers them. | ||
/// A new session's or refresh's tokens, as the token endpoint answers them: | ||
/// an MCP session's sealed apart, for the `Bearer` scheme. | ||
fn token_answer(svc: &Service, sid: &str, s: &Session, now: u64) -> Json { | ||
let (access, refresh) = labels(s.mcp); | ||
json!({ | ||
"access_token": svc.oauth.token("access", sid, &s.access), "token_type": "DPoP", | ||
"refresh_token": svc.oauth.token("refresh", sid, &s.refresh), "scope": s.granted.join(" "), | ||
"access_token": svc.oauth.token(access, sid, &s.access), "token_type": if s.mcp { "Bearer" } else { "DPoP" }, | ||
"refresh_token": svc.oauth.token(refresh, sid, &s.refresh), "scope": s.granted.join(" "), | ||
"expires_in": s.access_exp.saturating_sub(now), "sub": s.did, | ||
}) | ||
} | ||
| @@ -1759,6 +1838,7 @@ async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) | ||
now, | ||
low, | ||
client_id, | ||
false, | ||
&proof.jkt, | ||
key.as_deref(), | ||
code, | ||
| @@ -1779,7 +1859,7 @@ async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) | ||
Some("refresh_token") if client.refresh => { | ||
let token = p.filled("refresh_token").unwrap_or_default(); | ||
// The session's sets, resolved again, with no lock held. | ||
let consented = svc.oauth.session_scope(token); | ||
let consented = svc.oauth.session_scope("refresh", token); | ||
let sets = svc.oauth.sets.resolve_all(svc, &consented).await.ok(); | ||
tx.change(|st, now| { | ||
settle( | ||
| @@ -1792,6 +1872,7 @@ async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) | ||
st, | ||
now, | ||
client_id, | ||
false, | ||
&proof.jkt, | ||
key.as_deref(), | ||
token, | ||
| @@ -1805,9 +1886,10 @@ async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) | ||
} | ||
| ||
/// The code grant: entries to log, and the answer. `key` is the client key | ||
/// the request was authenticated with, if any. Below the free-space floor | ||
/// (`low`), a code that would be exchanged is refused before its challenge | ||
/// is spent. | ||
/// the request was authenticated with, if any; `mcp`, whether it is the | ||
/// MCP issuer's, which takes only its own codes, and binds no DPoP key | ||
/// (`jkt` empty). Below the free-space floor (`low`), a code that would be | ||
/// exchanged is refused before its challenge is spent. | ||
#[allow(clippy::too_many_arguments)] | ||
fn exchange( | ||
svc: &Service, | ||
| @@ -1815,6 +1897,7 @@ fn exchange( | ||
now: u64, | ||
low: bool, | ||
client_id: &str, | ||
mcp: bool, | ||
jkt: &str, | ||
key: Option<&str>, | ||
code: &str, | ||
| @@ -1823,16 +1906,19 @@ fn exchange( | ||
sets: Option<&HashMap<String, Arc<Json>>>, | ||
) -> (Vec<Json>, Out) { | ||
let refused = || refuse(400, "invalid_grant", "Invalid code"); | ||
// A code the other issuer gave is none of this one's. | ||
let Some((r, a)) = st | ||
.codes | ||
.get(code) | ||
.and_then(|id| st.requests.get(id)) | ||
.and_then(|r| Some((r, r.approval.as_ref()?))) | ||
.filter(|(r, _)| r.mcp() == mcp) | ||
else { | ||
// A code used twice ends what the first use made. | ||
let end = st | ||
.by_code | ||
.get(code) | ||
.filter(|sid| st.sessions.get(*sid).is_some_and(|s| s.mcp == mcp)) | ||
.map(|sid| json!({ "t": "oauthEndSession", "sid": sid })); | ||
return (end.into_iter().collect(), refused()); | ||
}; | ||
| @@ -1892,33 +1978,38 @@ fn exchange( | ||
refresh: new_id(12), | ||
client_key: r.client_key.clone(), | ||
refreshed: now, | ||
mcp, | ||
}; | ||
s.access_exp = (now + ACCESS_LIFE).min(s.end()); | ||
let entry = json!({ | ||
let mut entry = json!({ | ||
"t": "oauthSession", "sid": sid, "did": s.did, "client": s.client_id, "jkt": s.jkt, "scope": s.scope, "granted": s.granted, | ||
"started": s.started, "code": s.code, "access": s.access, "accessExp": s.access_exp, "refresh": s.refresh, | ||
"clientKey": s.client_key, | ||
}); | ||
if mcp { | ||
entry["mcp"] = json!(true); | ||
} | ||
(vec![held, entry], ok(200, token_answer(svc, &sid, &s, now))) | ||
} | ||
| ||
/// The refresh grant: entries to log, and the answer. | ||
/// The refresh grant: entries to log, and the answer. `mcp` as `exchange`'s. | ||
#[allow(clippy::too_many_arguments)] | ||
fn refresh( | ||
svc: &Service, | ||
st: &State, | ||
now: u64, | ||
client_id: &str, | ||
mcp: bool, | ||
jkt: &str, | ||
key: Option<&str>, | ||
token: &str, | ||
sets: Option<&HashMap<String, Arc<Json>>>, | ||
) -> (Vec<Json>, Out) { | ||
let refused = || refuse(400, "invalid_grant", "Invalid refresh token"); | ||
let Some((sid, jti)) = svc.oauth.token_of("refresh", token) else { | ||
let Some((sid, jti)) = svc.oauth.token_of(labels(mcp).1, token) else { | ||
return (vec![], refused()); | ||
}; | ||
let Some(s) = st.sessions.get(&sid) else { | ||
let Some(s) = st.sessions.get(&sid).filter(|s| s.mcp == mcp) else { | ||
return (vec![], refused()); | ||
}; | ||
if s.refresh != jti | ||
| @@ -1946,15 +2037,30 @@ fn refresh( | ||
} | ||
| ||
/// The session a token names, of any kind revocation takes: its current | ||
/// access token, its refresh tokens current and replaced, and its code. | ||
fn session_of<'s>(svc: &Service, st: &'s State, token: &str) -> Option<(String, &'s Session)> { | ||
let found = |sid: &str| st.sessions.get(sid).map(|s| (sid.to_string(), s)); | ||
if let Some((sid, jti)) = svc.oauth.token_of("access", token) { | ||
/// access token, its refresh tokens current and replaced, and, of an | ||
/// atproto session, its code; `mcp` as `exchange`'s. | ||
fn session_of<'s>( | ||
svc: &Service, | ||
st: &'s State, | ||
token: &str, | ||
mcp: bool, | ||
) -> Option<(String, &'s Session)> { | ||
let found = |sid: &str| { | ||
st.sessions | ||
.get(sid) | ||
.filter(|s| s.mcp == mcp) | ||
.map(|s| (sid.to_string(), s)) | ||
}; | ||
let (access, refresh) = labels(mcp); | ||
if let Some((sid, jti)) = svc.oauth.token_of(access, token) { | ||
return found(&sid).filter(|(_, s)| s.access == jti); | ||
} | ||
if let Some((sid, _)) = svc.oauth.token_of("refresh", token) { | ||
if let Some((sid, _)) = svc.oauth.token_of(refresh, token) { | ||
return found(&sid); | ||
} | ||
if mcp { | ||
return None; | ||
} | ||
found(st.by_code.get(token)?) | ||
} | ||
| ||
| @@ -1999,7 +2105,7 @@ async fn revoke(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8] | ||
tx.change(|st, now| { | ||
let mine = | ||
|s: &Session| s.client_id == client_id && s.jkt == proof.jkt && s.client_key == key; | ||
let end = session_of(svc, st, token) | ||
let end = session_of(svc, st, token, false) | ||
.filter(|(_, s)| mine(s)) | ||
.map(|(sid, _)| json!({ "t": "oauthEndSession", "sid": sid })); | ||
settle( | ||
| @@ -2071,7 +2177,7 @@ fn check_access( | ||
vec![], | ||
st.sessions | ||
.get(&sid) | ||
.filter(|s| s.jkt == proof.jkt && s.access == jti && now < s.access_exp) | ||
.filter(|s| !s.mcp && s.jkt == proof.jkt && s.access == jti && now < s.access_exp) | ||
.cloned(), | ||
) | ||
}); | ||
crates/pds-server/src/ops.rs+7−1
| @@ -380,7 +380,8 @@ pub(crate) async fn fsync<T>(f: impl Future<Output = T>) -> T { | ||
} | ||
| ||
/// The routes outside `/xrpc/` the server serves, each its own label: the | ||
/// MCP endpoint, `atproto-did`, and OAuth's metadata, endpoints and pages. | ||
/// MCP endpoint, `atproto-did`, OAuth's metadata, endpoints and pages, and | ||
/// the MCP issuer's (`spec/OAUTH-MCP.md`). | ||
const ROUTES: &[&str] = &[ | ||
"/mcp", | ||
"/.well-known/atproto-did", | ||
| @@ -396,6 +397,11 @@ const ROUTES: &[&str] = &[ | ||
"/@atproto/oauth-provider/~api/consent", | ||
"/@atproto/oauth-provider/~api/reject", | ||
"/@atproto/oauth-provider/~api/sign-out", | ||
"/.well-known/oauth-protected-resource/mcp", | ||
"/.well-known/oauth-authorization-server/oauth/mcp", | ||
"/oauth/mcp/authorize", | ||
"/oauth/mcp/token", | ||
"/oauth/mcp/revoke", | ||
]; | ||
| ||
/// The route of every path under `/oauth/assets/`, whatever its name, | ||
crates/pds-server/src/scopes.rs+50−26
| @@ -309,32 +309,11 @@ pub(crate) async fn look( | ||
s => s, | ||
}; | ||
match served { | ||
Ok(Some(nsid)) => { | ||
let Ok(m) = crate::method_named(nsid, call.method) else { | ||
return Ok(None); | ||
}; | ||
match takes(nsid) { | ||
Takes::Nothing | Takes::Refresh | Takes::Space => return Ok(None), | ||
Takes::CreateAccount => { | ||
return Err(Box::new(respond( | ||
err( | ||
401, | ||
"AuthenticationRequired", | ||
"OAuth credentials are not supported for this endpoint", | ||
), | ||
None, | ||
))); | ||
} | ||
Takes::Optionally | Takes::Needs(_) => { | ||
if m.kind == Kind::Query | ||
&& m.parse_params(call.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))) | ||
.is_err() | ||
{ | ||
return Ok(None); | ||
} | ||
} | ||
} | ||
} | ||
Ok(Some(nsid)) => match reads_token(nsid, call) { | ||
Ok(true) => {} | ||
Ok(false) => return Ok(None), | ||
Err(e) => return Err(Box::new(respond(Err(e), None))), | ||
}, | ||
// A path the server does not serve pays its point first, before | ||
// anything is fetched for it (its `atproto-proxy` target) and its | ||
// token is looked at (`spec/LIMITS.md`, "When"); `answer` then does | ||
| @@ -374,6 +353,51 @@ pub(crate) async fn look( | ||
} | ||
} | ||
| ||
/// Of a served method, whether a call with an OAuth access token has the | ||
/// token looked at: not for its HTTP method, a query's parameters that do | ||
/// not parse, or a method that reads no OAuth token, which answers it as it | ||
/// answers any; `createAccount` refuses it. | ||
fn reads_token(nsid: &str, call: &Call) -> Result<bool, XrpcError> { | ||
let Ok(m) = crate::method_named(nsid, call.method) else { | ||
return Ok(false); | ||
}; | ||
match takes(nsid) { | ||
Takes::Nothing | Takes::Refresh | Takes::Space => Ok(false), | ||
Takes::CreateAccount => err( | ||
401, | ||
"AuthenticationRequired", | ||
"OAuth credentials are not supported for this endpoint", | ||
), | ||
Takes::Optionally | Takes::Needs(_) => Ok(m.kind != Kind::Query | ||
|| m.parse_params(call.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))) | ||
.is_ok()), | ||
} | ||
} | ||
| ||
/// A tool call at the MCP endpoint with an MCP session's access token that | ||
/// works (`spec/OAUTH-MCP.md`, "Tokens at the MCP endpoint"), as `look` | ||
/// takes an OAuth access token over XRPC: `Ok(Some)`, the call is made with | ||
/// `Bearer::OAuth` of the grant; `Ok(None)`, its method reads no OAuth | ||
/// token, and is called as with one it has not looked at; `Err`, its | ||
/// method's refusal of one. | ||
pub(crate) fn look_mcp( | ||
svc: &Service, | ||
call: &Call<'_>, | ||
access: crate::oauth::Access, | ||
) -> Result<Option<Grant>, XrpcError> { | ||
let Ok(Some(nsid)) = crate::proxy::served(svc, call.nsid) else { | ||
return Ok(None); | ||
}; | ||
if !reads_token(nsid, call)? { | ||
return Ok(None); | ||
} | ||
crate::ops::verified(&access.did); | ||
Ok(Some(Grant { | ||
did: access.did, | ||
scope: Scope::of(&access.scope), | ||
})) | ||
} | ||
| ||
/// The answer to a call `look` passed, with its nonce. | ||
pub(crate) fn answered(svc: &Service, grant: Option<&Grant>, mut r: Response) -> Response { | ||
if grant.is_some() { | ||
harness/checks/oauth-mcp.mjsnew+246−0
| @@ -0,0 +1,246 @@ | ||
// OAuth for MCP clients (spec/OAUTH-MCP.md), on the server alone, as the | ||
// reference has no MCP endpoint: an account signed in as Claude does, from | ||
// the endpoint's 401 to tool calls with the bearer token it is given, its | ||
// refresh and revocation; where else that token is refused; and what the | ||
// MCP issuer refuses. The writes it makes are made on the reference too. | ||
| ||
import { isDeepStrictEqual } from 'node:util' | ||
import { cand, ref } from '../lib/processes.mjs' | ||
import { serve } from '../lib/clients.mjs' | ||
import { fail } from '../lib/plc.mjs' | ||
import { count } from '../lib/report.mjs' | ||
import { below } from '../lib/random.mjs' | ||
import { accounts, didOf, nextBatch, noteCommit, noteWrite } from '../lib/state.mjs' | ||
import { xrpc, xrpcHttp } from '../lib/xrpc.mjs' | ||
import { Browser, answer, form, fresh, pkce, target } from '../lib/oauth.mjs' | ||
import { mcpPost } from '../lib/via.mjs' | ||
import { approved } from './oauth.mjs' | ||
| ||
/// The legacy revision Claude speaks, and the scope it is given. | ||
const ERA = '2025-11-25' | ||
const SCOPE = 'atproto transition:generic' | ||
/// Claude's two documents, as Claude publishes them, on the client web's | ||
/// host for it: the hosted apps' and Claude Code's. | ||
const HOST = 'https://claude.pds-harness.net' | ||
const HOSTED = `${HOST}/oauth/claude-client-metadata` | ||
const HOSTED_REDIRECT = `${HOST}/api/mcp/auth_callback` | ||
const CODE = `${HOST}/oauth/claude-code-client-metadata` | ||
/// Documents with one thing wrong. | ||
const OTHER_ID = `${HOST}/oauth/other-client-id` | ||
const NO_AUTH_METHOD = `${HOST}/oauth/no-auth-method` | ||
/// A client without the refresh grant. | ||
const NO_REFRESH = `${HOST}/oauth/no-refresh` | ||
| ||
const names = () => { | ||
const origin = new URL(cand.publicUrl).origin | ||
return { origin, resource: `${origin}/mcp`, issuer: `${origin}/oauth/mcp`, prm: `${origin}/.well-known/oauth-protected-resource/mcp` } | ||
} | ||
const at = (path) => `${cand.url}${path}` | ||
const broke = (what, request, want, got) => fail(cand, `MCP OAuth: ${what}`, request, want, got) | ||
| ||
function publish() { | ||
const doc = (id, over = {}) => ({ client_id: id, client_name: 'Claude', client_uri: 'https://claude.ai', redirect_uris: [HOSTED_REDIRECT], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', ...over }) | ||
serve(HOSTED, doc(HOSTED)) | ||
serve(CODE, doc(CODE, { client_name: 'Claude Code', redirect_uris: ['http://localhost/callback', 'http://127.0.0.1/callback'] })) | ||
serve(OTHER_ID, doc(HOSTED)) | ||
const { token_endpoint_auth_method, ...noMethod } = doc(NO_AUTH_METHOD) | ||
serve(NO_AUTH_METHOD, noMethod) | ||
serve(NO_REFRESH, doc(NO_REFRESH, { grant_types: ['authorization_code'] })) | ||
} | ||
| ||
/// A `tools/call` at the MCP endpoint in Claude's revision: answers its HTTP | ||
/// status, `WWW-Authenticate`, and the JSON-RPC result or the body. | ||
async function toolCall(name, args, authorization) { | ||
const r = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, { 'mcp-protocol-version': ERA, ...(authorization ? { authorization } : {}) }) | ||
const m = r.messages?.[0] | ||
return { http: r.http, challenge: r.headers?.get('www-authenticate') ?? null, result: m?.result ?? null, body: m ?? r.failed ?? null } | ||
} | ||
| ||
/// A challenge's parameters, by name. | ||
function challenge(h) { | ||
if (!h || !/^Bearer\b/i.test(h)) return null | ||
return Object.fromEntries([...h.matchAll(/(\w+)="([^"]*)"/g)].map(([, k, v]) => [k, v])) | ||
} | ||
| ||
/// `/oauth/mcp/authorize` with `params` in a new browser: its answer. | ||
const authorize = (b, params) => b.navigate(at(`/oauth/mcp/authorize?${new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined))}`)) | ||
| ||
/// The parameters of a valid authorization request of `clientId`. | ||
function request(clientId, redirect, over = {}) { | ||
const pk = pkce() | ||
return { pk, params: { response_type: 'code', client_id: clientId, redirect_uri: redirect, code_challenge: pk.challenge, code_challenge_method: 'S256', resource: names().resource, state: fresh(12), scope: SCOPE, ...over } } | ||
} | ||
| ||
/// Sign `acct` in through `/oauth/mcp/authorize` and the page, as `clientId` | ||
/// to `redirect`: answers `{code, pk, redirect}`. | ||
async function signIn(acct, clientId, redirect) { | ||
const { issuer } = names() | ||
const { pk, params } = request(clientId, redirect) | ||
const b = new Browser() | ||
const start = await authorize(b, params) | ||
const page = start.headers.location ? new URL(start.headers.location, cand.url).href : null | ||
const p = page && new URL(page) | ||
if (start.status !== 303 || p?.pathname !== '/oauth/authorize' || p.searchParams.get('client_id') !== clientId || !p.searchParams.get('request_uri')) { | ||
return broke('authorize', { client_id: clientId, redirect_uri: redirect }, '303 to /oauth/authorize with the client_id and a request_uri', { status: start.status, location: start.headers.location ?? null, text: start.text.slice(0, 200) }) | ||
} | ||
const shown = await b.navigate(page) | ||
if (shown.status !== 200) return broke('the authorization page', { client_id: clientId }, 'the page', { status: shown.status, text: shown.text.slice(0, 200) }) | ||
const si = await b.api(page, '/sign-in', { locale: 'en', identifier: acct.handle, password: acct.password, remember: true }) | ||
if (si.status !== 200) return broke('sign-in', { client_id: clientId }, 'signed in', { status: si.status, body: si.json }) | ||
const c = await b.api(page, '/consent', { did: didOf(cand, acct) }) | ||
if (c.status !== 200 || !c.json?.url) return broke('consent', { client_id: clientId }, 'a url to the redirect', { status: c.status, body: c.json }) | ||
const back = await b.navigate(new URL(c.json.url, cand.url).href, { site: 'same-origin', referer: page }) | ||
const t = target(back.headers.location) | ||
const want = { to: redirect, state: params.state, iss: issuer, code: true } | ||
const got = { to: t?.to ?? null, state: t?.params?.state ?? null, iss: t?.params?.iss ?? null, code: Boolean(t?.params?.code) } | ||
if (!isDeepStrictEqual(got, want)) await broke('the redirect back', { client_id: clientId, redirect_uri: redirect }, want, { ...got, status: back.status }) | ||
return { code: t.params.code, pk, redirect } | ||
} | ||
| ||
/// A form POST to one of the MCP issuer's endpoints. | ||
async function post(path, params) { | ||
return answer(await fetch(at(path), { method: 'POST', ...form(params) })) | ||
} | ||
| ||
/// The code grant at `/oauth/mcp/token`. | ||
const exchange = (clientId, { code, pk, redirect }, over = {}) => post('/oauth/mcp/token', { grant_type: 'authorization_code', client_id: clientId, redirect_uri: redirect, code, code_verifier: pk.verifier, resource: names().resource, ...over }) | ||
| ||
/// A token answer held to the spec; answers its tokens. | ||
async function held(what, res, acct, withRefresh) { | ||
const b = res.body ?? {} | ||
const ok = res.status === 200 && b.token_type === 'Bearer' && typeof b.access_token === 'string' && b.expires_in >= 899 && b.expires_in <= 900 && b.sub === didOf(cand, acct) && b.scope?.split(' ').includes('atproto') && b.scope.split(' ').includes('transition:generic') && (typeof b.refresh_token === 'string') === withRefresh | ||
if (!ok) await broke(what, {}, { status: 200, token_type: 'Bearer', expires_in: 900, sub: '<the account>', scope: SCOPE, refresh_token: withRefresh }, { status: res.status, ...b, access_token: b.access_token ? '<token>' : undefined, refresh_token: b.refresh_token ? '<token>' : undefined }) | ||
return { access: b.access_token, refresh: b.refresh_token } | ||
} | ||
| ||
/// The access token no longer works at the MCP endpoint: the | ||
/// `invalid_token` challenge. | ||
async function challenged(what, access) { | ||
const r = await toolCall('server_get_session', {}, `Bearer ${access}`) | ||
const c = challenge(r.challenge) | ||
if (r.http !== 401 || c?.error !== 'invalid_token' || c?.resource_metadata !== names().prm) await broke(`/mcp with ${what}`, {}, { http: 401, challenge: { error: 'invalid_token', resource_metadata: names().prm } }, { http: r.http, challenge: r.challenge, body: r.body }) | ||
} | ||
| ||
/// The authorization request with one thing wrong after its client and | ||
/// redirect URI: a redirect with the error, `iss` and `state`. | ||
async function refusedByRedirect(name, over, error) { | ||
const { params } = request(HOSTED, HOSTED_REDIRECT, over) | ||
const res = await authorize(new Browser(), params) | ||
const t = target(res.headers.location) | ||
const want = { status: 303, to: HOSTED_REDIRECT, error, iss: names().issuer, state: params.state } | ||
const got = { status: res.status, to: t?.to ?? null, error: t?.params?.error ?? null, iss: t?.params?.iss ?? null, state: t?.params?.state ?? null } | ||
if (!isDeepStrictEqual(got, want)) await broke(`authorize: ${name}`, over, want, got) | ||
count(`mcp oauth: authorize refused, ${name}`, false) | ||
} | ||
| ||
/// The authorization request with its client or redirect URI wrong: a 400 | ||
/// page, no redirect. | ||
async function refusedByPage(name, clientId, redirect) { | ||
const { params } = request(clientId, redirect) | ||
const res = await authorize(new Browser(), params) | ||
if (res.status !== 400 || res.headers.location) await broke(`authorize: ${name}`, { client_id: clientId, redirect_uri: redirect }, 'a 400 error page, no redirect', { status: res.status, location: res.headers.location ?? null }) | ||
count(`mcp oauth: authorize refused, ${name}`, false) | ||
} | ||
| ||
export async function checkMcpOAuth() { | ||
const acct = accounts.find((a) => a.password) | ||
if (!acct) return | ||
publish() | ||
const { origin, resource, issuer, prm } = names() | ||
| ||
// The challenge, and a tool that needs no account. | ||
const anon = await toolCall('repo_create_record', { repo: didOf(cand, acct), collection: 'com.example.note', record: { $type: 'com.example.note', text: 'x' } }) | ||
const c = challenge(anon.challenge) | ||
if (anon.http !== 401 || !isDeepStrictEqual(c, { resource_metadata: prm, scope: SCOPE }) || anon.body?.error !== 'invalid_token') await broke('a tool needing an account, no token', {}, { http: 401, challenge: { resource_metadata: prm, scope: SCOPE }, body: { error: 'invalid_token' } }, anon) | ||
const open = await toolCall('server_describe_server', {}) | ||
if (open.http !== 200 || open.result?.isError) await broke('a tool needing no account, no token', {}, 'its answer', open) | ||
const garbage = await toolCall('server_get_session', {}, 'Bearer not-a-token') | ||
if (garbage.http !== 200 || garbage.result?.structuredContent?.error !== 'InvalidToken') await broke('a token the server did not give out', {}, 'a tool error, InvalidToken, as XRPC answers it', garbage) | ||
count('mcp oauth: challenge', true) | ||
| ||
// The metadata. | ||
const meta = await answer(await fetch(at('/.well-known/oauth-protected-resource/mcp'))) | ||
const wantMeta = { resource, authorization_servers: [issuer], scopes_supported: ['atproto', 'transition:generic'], bearer_methods_supported: ['header'], resource_documentation: 'https://atproto.com' } | ||
if (meta.status !== 200 || meta.headers['access-control-allow-origin'] !== '*' || !isDeepStrictEqual(meta.body, wantMeta)) await broke('protected resource metadata of /mcp', {}, wantMeta, { status: meta.status, cors: meta.headers['access-control-allow-origin'] ?? null, body: meta.body }) | ||
const as = await answer(await fetch(at('/.well-known/oauth-authorization-server/oauth/mcp'))) | ||
const atproto = await answer(await fetch(at('/.well-known/oauth-authorization-server'))) | ||
const wantAs = { | ||
issuer, authorization_endpoint: `${issuer}/authorize`, token_endpoint: `${issuer}/token`, revocation_endpoint: `${issuer}/revoke`, | ||
scopes_supported: atproto.body?.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], | ||
} | ||
if (as.status !== 200 || !isDeepStrictEqual(as.body, wantAs)) await broke('the MCP issuer\'s metadata', {}, wantAs, { status: as.status, body: as.body }) | ||
count('mcp oauth: metadata', true) | ||
| ||
// Signed in as the hosted apps; the token at the MCP endpoint. | ||
const hosted = await held('token: code (hosted)', await exchange(HOSTED, await signIn(acct, HOSTED, HOSTED_REDIRECT)), acct, true) | ||
const bearer = `Bearer ${hosted.access}` | ||
const me = await toolCall('server_get_session', {}, bearer) | ||
if (me.result?.isError !== false || me.result?.structuredContent?.did !== didOf(cand, acct)) await broke('/mcp with the token: server_get_session', {}, { did: '<the account>' }, me) | ||
const rkey = `mcp-${nextBatch()}` | ||
const record = { $type: 'com.example.note', text: 'written through MCP with an MCP token' } | ||
const put = await toolCall('repo_put_record', { collection: 'com.example.note', rkey, record }, bearer) | ||
if (put.result?.isError !== false) await broke('/mcp with the token: repo_put_record', { rkey }, 'the record written', put) | ||
else { | ||
const read = await xrpcHttp(cand, 'com.atproto.repo.getRecord', { params: { repo: didOf(cand, acct), collection: 'com.example.note', rkey } }) | ||
if (!isDeepStrictEqual(read.body?.value, record)) await broke('getRecord of what the MCP token wrote', { rkey }, record, read.body) | ||
// The same write on the reference, so the repositories still agree. | ||
const a = await xrpc(ref, 'com.atproto.repo.putRecord', { body: { repo: acct.handle, collection: 'com.example.note', rkey, record }, token: acct }) | ||
noteWrite(acct, 'com.example.note', rkey, a) | ||
noteCommit(ref, acct, a) | ||
noteCommit(cand, acct, { body: put.result.structuredContent }) | ||
} | ||
count('mcp oauth: tools with the token', true) | ||
| ||
// The token elsewhere. | ||
const asBearer = await xrpcHttp(cand, 'com.atproto.server.getSession', { token: hosted.access }) | ||
if (asBearer.status !== 400 || asBearer.body?.error !== 'InvalidToken') await broke('the token on XRPC, as Bearer', {}, '400 InvalidToken', asBearer) | ||
const asDpop = await answer(await fetch(at('/xrpc/com.atproto.server.getSession'), { headers: { authorization: `DPoP ${hosted.access}` } })) | ||
if (asDpop.status !== 401 || asDpop.body?.error !== 'invalid_token') await broke('the token on XRPC, as DPoP', {}, '401 invalid_token', { status: asDpop.status, body: asDpop.body }) | ||
const atAtproto = await post('/oauth/token', { grant_type: 'refresh_token', client_id: HOSTED, refresh_token: hosted.refresh }) | ||
if (atAtproto.status === 200) await broke('the refresh token at /oauth/token', {}, 'refused', atAtproto.status) | ||
const atproto2 = await approved(acct) | ||
if (atproto2) { | ||
const r = await post('/oauth/mcp/token', { grant_type: 'authorization_code', client_id: atproto2.req.clientId, redirect_uri: atproto2.req.redirect, code: atproto2.codes.server, code_verifier: atproto2.req.pk.verifier, resource }) | ||
if (r.status === 200) await broke('an atproto code at /oauth/mcp/token', {}, 'refused', r.status) | ||
} | ||
count('mcp oauth: the token refused elsewhere', true) | ||
| ||
// Refresh: new tokens, the old access token challenged; the old refresh | ||
// token refused, ending the session. | ||
const refreshed = await held('token: refresh', await post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: HOSTED, refresh_token: hosted.refresh }), acct, true) | ||
await challenged('an access token replaced', hosted.access) | ||
const works = await toolCall('server_get_session', {}, `Bearer ${refreshed.access}`) | ||
if (works.result?.isError !== false) await broke('/mcp with the refreshed token', {}, 'the session', works) | ||
const again = await post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: HOSTED, refresh_token: hosted.refresh }) | ||
if (again.status !== 400 || again.body?.error !== 'invalid_grant') await broke('a replaced refresh token', {}, '400 invalid_grant', { status: again.status, body: again.body }) | ||
await challenged('the token of a session ended', refreshed.access) | ||
count('mcp oauth: refresh', true) | ||
| ||
// Claude Code: a localhost redirect on a port the document does not name. | ||
const native = await signIn(acct, CODE, `http://localhost:${49152 + below(1000)}/callback`) | ||
const wrongVerifier = await exchange(CODE, native, { code_verifier: pkce().verifier }) | ||
if (wrongVerifier.status !== 400 || wrongVerifier.body?.error !== 'invalid_grant') await broke('token: a wrong code_verifier', {}, '400 invalid_grant', { status: wrongVerifier.status, body: wrongVerifier.body }) | ||
const code2 = await held('token: code (Claude Code)', await exchange(CODE, await signIn(acct, CODE, 'http://localhost:51234/callback')), acct, true) | ||
const revoked = await post('/oauth/mcp/revoke', { client_id: CODE, token: code2.refresh }) | ||
if (revoked.status !== 200) await broke('revoke', {}, 200, { status: revoked.status, body: revoked.body }) | ||
await challenged('the token of a session revoked', code2.access) | ||
count('mcp oauth: Claude Code, and revocation', true) | ||
| ||
// A client without the refresh grant: no refresh token, and no refresh. | ||
await held('token: code (no refresh grant)', await exchange(NO_REFRESH, await signIn(acct, NO_REFRESH, HOSTED_REDIRECT)), acct, false) | ||
const noRefresh = await post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: NO_REFRESH, refresh_token: 'any' }) | ||
if (noRefresh.status !== 400 || noRefresh.body?.error !== 'unauthorized_client') await broke('a refresh grant from a client without it', { client_id: NO_REFRESH }, '400 unauthorized_client', { status: noRefresh.status, body: noRefresh.body }) | ||
count('mcp oauth: a client without the refresh grant', true) | ||
| ||
// What the MCP issuer refuses. | ||
await refusedByRedirect('no resource', { resource: undefined }, 'invalid_target') | ||
await refusedByRedirect('another resource', { resource: `${origin}/elsewhere` }, 'invalid_target') | ||
await refusedByRedirect('no PKCE', { code_challenge: undefined, code_challenge_method: undefined }, 'invalid_request') | ||
await refusedByRedirect('PKCE plain', { code_challenge_method: 'plain' }, 'invalid_request') | ||
await refusedByRedirect('a scope without atproto', { scope: 'transition:generic' }, 'invalid_scope') | ||
await refusedByPage('a document naming another client_id', OTHER_ID, HOSTED_REDIRECT) | ||
await refusedByPage('a document with no token_endpoint_auth_method', NO_AUTH_METHOD, HOSTED_REDIRECT) | ||
await refusedByPage('a redirect URI the document does not name', HOSTED, `${HOST}/elsewhere`) | ||
} | ||
harness/lib/clients.mjs+3−1
| @@ -12,7 +12,9 @@ import http from 'node:http' | ||
| ||
/// The hosts of the clients the harness makes: under a public suffix, so | ||
/// that both sides take them as discoverable clients (spec/OAUTH-CLIENTS.md). | ||
export const HOSTS = ['app.pds-harness.net', 'other.pds-harness.net'] | ||
/// The last stands for Claude's, whose documents an MCP client signs in | ||
/// with (spec/OAUTH-MCP.md). | ||
export const HOSTS = ['app.pds-harness.net', 'other.pds-harness.net', 'claude.pds-harness.net'] | ||
export const ORIGINS = HOSTS.map((h) => `https://${h}`) | ||
| ||
/// What each path serves, by `host + path` (the query is not part of it): | ||
harness/lib/observe.mjs+5−0
harness/lib/via.mjs+4−1
harness/compare.mjs+5−1
harness/conformance.mjs+5−1
spec/mcp/legacy/2025-11-25/basic/authorization.mdnew+708−0
708 lines changed: not loaded until asked for.
spec/rfc/rfc8707.txtnew+547−0
547 lines changed: not loaded until asked for.