~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

MCP step-up: a scope that does not allow a call is a 403 naming all it needs

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:mcp/step-up
crates/pds-server/src/mcp.rs+61−10
@@ -9,7 +9,7 @@
use crate::oauth::mcp::Token as McpToken;
use crate::sessions::Bearer;
use crate::{Auth, Call, Resp, Shared, answer, authorization, limits, scopes};
use crate::{Auth, Call, Resp, Shared, XrpcError, answer, authorization, limits, scopes};
use axum::body::Body;
use axum::extract::{Extension, State};
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
@@ -37,14 +37,15 @@ const HEADER_MISMATCH: i64 = -32020;
const UNSUPPORTED_PROTOCOL_VERSION: i64 = -32022;
/// 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`).
/// `challenge`, an HTTP `401` or `403` with that `WWW-Authenticate: Bearer`
/// challenge and the OAuth error its body names, and `message` its
/// `error_description` (`spec/OAUTH-MCP.md`).
struct RpcError {
status: StatusCode,
code: i64,
message: String,
data: Option<Json>,
challenge: Option<String>,
challenge: Option<(String, &'static str)>,
}
fn rpc_err(status: StatusCode, code: i64, message: impl Into<String>) -> RpcError {
@@ -69,11 +70,44 @@ fn challenge(st: &Shared, error: Option<&str>, description: &str) -> RpcError {
}
};
RpcError {
challenge: Some(challenge),
challenge: Some((challenge, "invalid_token")),
..rpc_err(StatusCode::UNAUTHORIZED, INVALID_REQUEST, description)
}
}
/// The `403` that has a client ask for more (MCP's step-up), for an error a
/// token of scope `granted` was refused with, if it is a `ScopeMissingError`:
/// the scope it names, then `also`, the others the call needs that the token
/// lacks, after the token's own, so that one sign-in grants all of it
/// (`spec/OAUTH-MCP.md`, "Tokens at the MCP endpoint").
fn step_up(st: &Shared, granted: &[String], also: &[String], e: &XrpcError) -> Option<RpcError> {
if e.status != 403 || e.name != "ScopeMissingError" {
return None;
}
let missing = e
.message
.strip_prefix("Missing required scope \"")?
.strip_suffix('"')?;
let mut scope: Vec<&str> = granted.iter().map(String::as_str).collect();
for s in std::iter::once(missing).chain(also.iter().map(String::as_str)) {
if !scope.contains(&s) {
scope.push(s);
}
}
let metadata = crate::oauth::mcp::resource_metadata(st);
let description = e.message.replace('"', "'");
Some(RpcError {
challenge: Some((
format!(
"Bearer error=\"insufficient_scope\", scope=\"{}\", resource_metadata=\"{metadata}\", error_description=\"{description}\"",
scope.join(" ")
),
"insufficient_scope",
)),
..rpc_err(StatusCode::FORBIDDEN, INVALID_REQUEST, e.message.clone())
})
}
pub async fn endpoint(
State(st): State<Shared>,
method: Method,
@@ -233,10 +267,10 @@ 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 });
if let Some((c, error)) = e.challenge {
let body = json!({ "error": error, "error_description": e.message });
let mut r = (
StatusCode::UNAUTHORIZED,
e.status,
[(header::CONTENT_TYPE, "application/json")],
body.to_string(),
)
@@ -614,6 +648,8 @@ async fn call_tool(
},
_ => None,
};
// The token's scope, for a step-up if the call is refused for it.
let granted = mcp.as_ref().map(|(_, a)| a.scope.clone());
// 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.
let did = match &mcp {
@@ -628,6 +664,11 @@ async fn call_tool(
args.entry(a.name.clone()).or_insert_with(|| json!(did));
}
}
// What else a write needs that the token lacks, for a step-up to name.
let also = granted
.as_deref()
.map(|g| scopes::missing_for_records(&m.nsid, &args, g))
.unwrap_or_default();
let (method, mut params, mut body) = (
if m.kind == Kind::Query {
Method::GET
@@ -675,7 +716,12 @@ async fn call_tool(
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)),
Err(e) => {
if let Some(s) = granted.as_deref().and_then(|g| step_up(st, g, &also, &e)) {
return Err(s);
}
return Ok((json!({ "error": e.name, "message": e.message }), true));
}
}
}
if let Some(g) = &grant {
@@ -713,7 +759,12 @@ async fn call_tool(
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),
Err(e) => {
if let Some(s) = granted.as_deref().and_then(|g| step_up(st, g, &also, &e)) {
return Err(s);
}
(json!({ "error": e.name, "message": e.message }), true)
}
};
Ok((content, is_error))
}
crates/pds-server/src/scopes.rs+22−0
@@ -462,6 +462,28 @@ pub(crate) fn records(
.try_for_each(|n| g.scope.may(n))
}
/// The scopes a repository write's input needs that a session of `granted`
/// does not allow, each once, in the order `records` asks them: what a
/// step-up asks for all at once (`spec/OAUTH-MCP.md`).
pub(crate) fn missing_for_records(
nsid: &str,
input: &Map<String, Json>,
granted: &[String],
) -> Vec<String> {
let scope = Scope::of(granted);
let mut out: Vec<String> = Vec::new();
for n in record_needs(nsid, input)
.iter()
.filter(|n| !scope.allows(n))
{
let s = n.scope();
if !out.contains(&s) {
out.push(s);
}
}
out
}
/// What a procedure that takes a token needs of a scope once its input is
/// checked, as the reference asks it in the method: `registerPush` and
/// `unregisterPush`, `rpc` of the method to the notification service its
harness/checks/oauth-mcp.mjs+30−2
@@ -73,9 +73,9 @@ function request(clientId, redirect, 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) {
async function signIn(acct, clientId, redirect, scope = SCOPE) {
const { issuer } = names()
const { pk, params } = request(clientId, redirect)
const { pk, params } = request(clientId, redirect, { scope })
const b = new Browser()
const start = await authorize(b, params)
const page = start.headers.location ? new URL(start.headers.location, cand.url).href : null
@@ -234,6 +234,34 @@ export async function checkMcpOAuth() {
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)
// Step-up: a narrow token refused for its scope is a 403 naming all it
// needs; signed in again with that, the call works. A method no scope
// grants stays a tool error.
const NARROW = 'atproto repo:com.example.other'
const narrowAnswer = await exchange(HOSTED, await signIn(acct, HOSTED, HOSTED_REDIRECT, NARROW))
const narrow = narrowAnswer.body?.access_token
if (narrowAnswer.status !== 200 || narrowAnswer.body?.scope !== NARROW) await broke('token: code (a narrow scope)', { scope: NARROW }, { status: 200, scope: NARROW }, { status: narrowAnswer.status, scope: narrowAnswer.body?.scope ?? null })
const stepRkey = `mcp-${nextBatch()}`
const stepRecord = { $type: 'com.example.note', text: 'written after a step-up' }
const refused = await toolCall('repo_put_record', { collection: 'com.example.note', rkey: stepRkey, record: stepRecord }, `Bearer ${narrow}`)
const wantScope = `${NARROW} repo:com.example.note?action=create repo:com.example.note?action=update`
const sc = challenge(refused.challenge)
const wantChallenge = { error: 'insufficient_scope', scope: wantScope, resource_metadata: prm }
const gotChallenge = sc && { error: sc.error, scope: sc.scope, resource_metadata: sc.resource_metadata }
if (refused.http !== 403 || !isDeepStrictEqual(gotChallenge, wantChallenge) || refused.body?.error !== 'insufficient_scope') await broke('a call the scope refuses', { scope: NARROW, tool: 'repo_put_record' }, { http: 403, challenge: wantChallenge, body: { error: 'insufficient_scope' } }, { http: refused.http, challenge: refused.challenge, body: refused.body })
const appPassword = await toolCall('server_create_app_password', { name: `mcp-${nextBatch()}` }, `Bearer ${narrow}`)
if (appPassword.http !== 200 || appPassword.result?.isError !== true) await broke('a method no OAuth token may call', { tool: 'server_create_app_password' }, 'a tool error, not a challenge', { http: appPassword.http, challenge: appPassword.challenge, body: appPassword.body })
const wider = await exchange(HOSTED, await signIn(acct, HOSTED, HOSTED_REDIRECT, wantScope))
const stepped = await toolCall('repo_put_record', { collection: 'com.example.note', rkey: stepRkey, record: stepRecord }, `Bearer ${wider.body?.access_token}`)
if (stepped.result?.isError !== false) await broke('the call after a step-up', { scope: wantScope }, 'the record written', stepped)
else {
const a = await xrpc(ref, 'com.atproto.repo.putRecord', { body: { repo: acct.handle, collection: 'com.example.note', rkey: stepRkey, record: stepRecord }, token: acct })
noteWrite(acct, 'com.example.note', stepRkey, a)
noteCommit(ref, acct, a)
noteCommit(cand, acct, { body: stepped.result.structuredContent })
}
count('mcp oauth: step-up', true)
// What the MCP issuer refuses.
await refusedByRedirect('no resource', { resource: undefined }, 'invalid_target')
await refusedByRedirect('another resource', { resource: `${origin}/elsewhere` }, 'invalid_target')
spec/OAUTH-MCP.md+31−7
@@ -218,10 +218,29 @@ not a JSON-RPC answer, in two cases, so that a client signs in:
revoked, its session ended: `Bearer error="invalid_token",
resource_metadata="…"`, so that the client refreshes or signs in again.
The body is `{"error": "invalid_token", "error_description": "…"}`. Any
other call is answered as `COMMANDS.md` says: a tool that needs no account
works with no token, and a token the server did not give out, or a password
session's, is taken as XRPC takes it.
The body is `{"error": "invalid_token", "error_description": "…"}`.
With a token that works, a call its scope does not allow is HTTP `403`, so
that the client asks the account for more (MCP's step-up, "Scope Challenge
Handling"): where the method, called as an XRPC call with an OAuth token of
that scope, answers `403 ScopeMissingError` naming the scope that would
allow it (`OAUTH-SCOPES.md`, "The refusal"), the challenge is
`Bearer error="insufficient_scope", scope="<the token's scope, then what it
lacks>", resource_metadata="…", error_description="<the error's
message>"`: the token's scope as its token answer gave it, its tokens in
order; then each scope the call needs that it does not allow and that is
not already there: the one the error names, and, for a repository write,
the others its input needs, in the order `OAUTH-SCOPES.md` asks them
(`putRecord` both `create` and `update`); separated by single spaces, so
that one sign-in grants all the call needs. The body is `{"error":
"insufficient_scope", "error_description": "…"}`. A method that takes no
OAuth token at all, as the app password methods, is not refused for its
scope: no sign-in grants it, and its refusal is a tool error, as XRPC
answers it.
Any other call is answered as `COMMANDS.md` says: a tool that needs no
account works with no token, and a token the server did not give out, or a
password session's, is taken as XRPC takes it.
An MCP session's access token is for the MCP endpoint alone. On XRPC it is
not a token the server gave out as `Bearer`: `400 InvalidToken`, as
@@ -267,6 +286,13 @@ publishes a document of Claude's shape, a public client with no `scope`,
- A client whose `grant_types` is `authorization_code` alone: its code
grant answers no `refresh_token`, and a refresh grant from it, with any
`refresh_token`, `400 unauthorized_client`.
- Step-up: an account signed in with `atproto repo:com.example.other`
alone; `repo_put_record` to `com.example.note` with that token: `403`,
`Bearer error="insufficient_scope", scope="atproto repo:com.example.other
repo:com.example.note?action=create repo:com.example.note?action=update",
resource_metadata="…"`; signed in
again with that scope, the same call writes. `server_create_app_password`
with the narrow token is a tool error, not a challenge.
- Refusals: no `resource`, or another, `invalid_target`; no PKCE, or
`plain`, `invalid_request`; a scope without `atproto`, `invalid_scope`,
each a redirect with `iss`; a document whose `client_id` is another URL,
@@ -278,6 +304,4 @@ publishes a document of Claude's shape, a public client with no `scope`,
`authorization-server-metadata-endpoint` against the MCP issuer.
Not checked: Claude itself, which reaches only a server on the internet
(`README.md`, "Deploying"); step-up (`403 insufficient_scope`), which the
server does not send: a call its scope refuses is a tool error, as
`OAUTH-SCOPES.md`'s `ScopeMissingError`.
(`README.md`, "Deploying").
README.md+0−2
@@ -347,7 +347,5 @@ cd harness && node compare.mjs --upgrade-write -- ../../pds-release/target/relea
- No MCP tool uploads or reads blobs: `upload-blob` and `get-blob` are CLI
commands only.
- MCP serves only tools: no resources, prompts or `subscriptions/listen`.
An MCP client's sign-in (`spec/OAUTH-MCP.md`) has no step-up: a call its
scope refuses is a tool error, not a `403` challenge.
- Mail sent over SMTP (`EMAIL.md`) is no outbound request of
`OPERATIONS.md`: it has no span and no `pds_outbound_*` metrics.