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

OAuth: a PAR with no DPoP proof taken, as the reference takes it

Open chadtmiller.com wants to merge into main from chadtmiller.com/monolith:oauth/par-without-dpop
.changeset/par-without-dpop.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# OAuth sign-in works for clients that send no DPoP proof at PAR
A pushed authorization request (`/oauth/par`) with no `DPoP` header is now taken, as Bluesky's PDS takes it, and the session is bound to the key the client proves at the token request. Clients written against Bluesky's PDS that start DPoP only at the token request (trezy.pet among them) could not sign in before: their PAR was refused `401 invalid_dpop_proof`. atproto's OAuth profile says a client must send a proof at PAR, so this is a departure the server may drop again once such clients send one.
crates/pds-server/src/oauth/tests.rs+102−19
@@ -319,6 +319,19 @@ impl<'s> App<'s> {
/// Push a request with `extra` changed: the answer, and what the app keeps.
pub async fn par(&mut self, extra: &[(&'static str, Option<&str>)]) -> (Got, Pushed) {
self.push(extra, true).await
}
/// Push a request with `extra` changed and no DPoP proof (PAR's step 4).
pub async fn par_unproven(&mut self, extra: &[(&'static str, Option<&str>)]) -> (Got, Pushed) {
self.push(extra, false).await
}
async fn push(
&mut self,
extra: &[(&'static str, Option<&str>)],
proven: bool,
) -> (Got, Pushed) {
let verifier = b64(rand::random::<[u8; 32]>());
let state = hex::encode(rand::random::<[u8; 8]>());
let params = self.par_params(&verifier, &state, extra);
@@ -326,7 +339,11 @@ impl<'s> App<'s> {
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let g = self.call("/oauth/par", &pairs).await;
let g = if proven {
self.call("/oauth/par", &pairs).await
} else {
self.send("/oauth/par", &form(&pairs), &[]).await
};
let request_uri = g.json()["request_uri"]
.as_str()
.unwrap_or_default()
@@ -614,6 +631,12 @@ pub(crate) async fn approved(
name: &str,
) -> (Pushed, String) {
let (_, pushed) = app.par(&[]).await;
let code = approve(app, browser, name, &pushed).await;
(pushed, code)
}
/// A request pushed, approved: its code, not yet exchanged.
async fn approve(app: &App<'_>, browser: &mut Browser<'_>, name: &str, pushed: &Pushed) -> String {
browser.page(&app.client_id, &pushed.request_uri).await;
let signed = browser.api(&app.client_id, &pushed.request_uri, "sign-in", json!({ "locale": "en", "identifier": format!("{name}.test"), "password": format!("{name}-pw") }), None).await;
// Signed in on this device already, it stays so, with no ephemeral token.
@@ -628,12 +651,10 @@ pub(crate) async fn approved(
)
.await;
let url = url::Url::parse(consent.json()["url"].as_str().unwrap()).unwrap();
let code = url
.query_pairs()
url.query_pairs()
.find(|(k, _)| k == "code")
.map(|(_, v)| v.into_owned())
.expect("a code");
(pushed, code)
.expect("a code")
}
pub(crate) fn text(j: &Json, k: &str) -> String {
@@ -860,7 +881,7 @@ async fn par_checks_in_order() {
(&[("state", None)], 400, "invalid_request"),
(&[("state", Some(""))], 400, "invalid_request"),
];
for (extra, status, error) in cases {
for &(extra, status, error) in &cases {
let (g, _) = app.par(extra).await;
assert_eq!(
refused(&g),
@@ -877,19 +898,28 @@ async fn par_checks_in_order() {
);
}
}
// 4. No proof.
let body = form(&[
("client_id", &app.client_id),
("response_type", "code"),
("scope", "atproto"),
]);
let g = app.send("/oauth/par", &body, &[]).await;
// 4. No proof: checked as any other request, in the same order, and
// `dpop_jkt`, with no proof to match, kept as the request's key.
for &(extra, status, error) in &cases {
let (g, _) = app.par_unproven(extra).await;
let want = if status == 401 {
(201, String::new())
} else {
(status, error.to_string())
};
assert_eq!(refused(&g), want, "{extra:?} with no proof: {}", g.body);
}
let (g, keyless) = app.par_unproven(&[]).await;
assert_eq!(g.status, 201, "{}", g.body);
let (g, given) = app.par_unproven(&[("dpop_jkt", Some("AAAA"))]).await;
assert_eq!(g.status, 201, "{}", g.body);
let st = srv.svc.oauth.snapshot();
assert_eq!(st.requests[request_id_of(&keyless.request_uri)].jkt, None);
assert_eq!(
(refused(&g), g.www_error()),
(
(401, "invalid_dpop_proof".into()),
Some("invalid_dpop_proof".into())
)
st.requests[request_id_of(&given.request_uri)]
.jkt
.as_deref(),
Some("AAAA")
);
// One that passes, as JSON too, and one whose state the client used before.
let (g, pushed) = app
@@ -931,7 +961,7 @@ async fn par_checks_in_order() {
),
(Some("alice.test"), Some("consent"), "query")
);
assert_eq!(r.jkt, app.key.jkt());
assert_eq!(r.jkt.as_deref(), Some(app.key.jkt().as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -2497,6 +2527,59 @@ async fn codes() {
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn a_request_with_no_key_takes_the_token_requests() {
let (dir, srv, _) = setup("oauth-codes-keyless").await;
let mut app = App::new(&srv, "atproto");
let mut browser = Browser::new(&srv);
let grant = "invalid_grant";
// Pushed with no proof and no `dpop_jkt`, it takes the key its code is
// exchanged with, and its session is bound to it.
let (g, pushed) = app.par_unproven(&[]).await;
assert_eq!(g.status, 201, "{}", g.body);
let code = approve(&app, &mut browser, "alice", &pushed).await;
let t = app.exchange(&code, &pushed).await;
assert_eq!(t.status, 200, "{}", t.body);
let jkt = app.key.jkt();
let st = srv.svc.oauth.snapshot();
assert_eq!(
st.sessions
.values()
.filter(|s| s.code == code)
.map(|s| s.jkt.as_str())
.collect::<Vec<_>>(),
[jkt.as_str()]
);
let access = text(&t.json(), "access_token");
assert_eq!(app.get_session(&access).await.status, 200);
let r = app.refresh(&text(&t.json(), "refresh_token")).await;
assert_eq!(r.status, 200, "{}", r.body);
// A second key is then refused, as for any session, and ends it.
let key = std::mem::replace(&mut app.key, Key::new());
let refused = app.refresh(&text(&r.json(), "refresh_token")).await;
assert_eq!(refused.error(), grant);
app.key = key;
assert_eq!(
app.get_session(&text(&r.json(), "access_token"))
.await
.error(),
"invalid_token"
);
// Pushed with no proof but a `dpop_jkt`, its code is that key's alone.
let (g, pushed) = app.par_unproven(&[("dpop_jkt", Some(&jkt))]).await;
assert_eq!(g.status, 201, "{}", g.body);
let code = approve(&app, &mut browser, "alice", &pushed).await;
let key = std::mem::replace(&mut app.key, Key::new());
assert_eq!(app.exchange(&code, &pushed).await.error(), grant);
app.key = key;
assert_eq!(app.exchange(&code, &pushed).await.error(), grant, "spent");
let (_, pushed) = app.par_unproven(&[("dpop_jkt", Some(&jkt))]).await;
let code = approve(&app, &mut browser, "alice", &pushed).await;
let t = app.exchange(&code, &pushed).await;
assert_eq!(t.status, 200, "{}", t.body);
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn revocation() {
let (dir, srv, _) = setup("oauth-revoke").await;
crates/pds-server/src/oauth.rs+37−14
@@ -206,8 +206,11 @@ struct Request {
prompt: Option<String>,
response_mode: String,
ui_locales: Option<String>,
/// The thumbprint of the client's DPoP key.
jkt: String,
/// The thumbprint of the client's DPoP key: `dpop_jkt`, or else the
/// PAR's proof's; none for a PAR with neither, which the code grant then
/// binds to its token request's key (`spec/OAUTH.md`, PAR step 4). Empty
/// for an MCP issuer's request, which binds no key.
jkt: Option<String>,
expires: u64,
/// The device it was loaded on.
device: Option<String>,
@@ -500,7 +503,7 @@ impl State {
prompt: opt_text("prompt"),
response_mode: text("responseMode")?,
ui_locales: opt_text("uiLocales"),
jkt: text("jkt")?,
jkt: opt_text("jkt"),
expires: number("expires")?,
device: None,
approval: None,
@@ -1756,9 +1759,15 @@ async fn par(
if let Err(why) = par_forms(&p) {
return bad(&why);
}
// 4. The proof, if the request carries one. A request with none is
// taken, its key then bound at the token request (the code grant's step
// 2), as the reference takes it. This departs from `atproto/oauth.md`,
// which has clients send a proof at PAR; it is taken only because the
// reference takes it and clients written against it rely on it, and is
// a candidate to drop once they send proofs (`spec/OAUTH.md`, "Where
// the reference departs from the specs").
let proof = match dpop::check(svc, headers, "POST", "/oauth/par", None) {
Ok(Some(proof)) => proof,
Ok(None) => return refuse_dpop("invalid_dpop_proof", "DPoP proof required"),
Ok(proof) => proof,
Err(r) => return refused_proof(r),
};
let client = match clients::load(svc, client_id).await {
@@ -1771,9 +1780,15 @@ async fn par(
Err(r) => return r.out(),
};
let text = |k: &str| p.text(k).ok().flatten();
if text("dpop_jkt").is_some_and(|j| j != proof.jkt) {
// 6. `dpop_jkt` given with a proof is its key's; given without one, it
// is kept as the request's key.
let dpop_jkt = text("dpop_jkt");
if let (Some(j), Some(proof)) = (dpop_jkt, &proof)
&& j != proof.jkt
{
return refuse_dpop("invalid_token", "dpop_jkt does not match the DPoP proof");
}
let jkt = dpop_jkt.or(proof.as_ref().map(|p| p.jkt.as_str()));
if ["claims", "id_token_hint", "nonce"]
.iter()
.any(|k| p.get(k).is_some())
@@ -1859,9 +1874,14 @@ async fn par(
"state": state, "codeChallenge": challenge, "loginHint": login_hint,
"prompt": if confidential { text("prompt") } else if text("prompt") == Some("create") { Some("create") } else { Some("consent") },
"responseMode": text("response_mode").unwrap_or("query"), "uiLocales": text("ui_locales"),
"jkt": proof.jkt, "expires": now + REQUEST_LIFE, "clientKey": client_key, "addr": addr,
"jkt": jkt, "expires": now + REQUEST_LIFE, "clientKey": client_key, "addr": addr,
});
settle(svc, &proof, now, low, (vec![held, entry], ok(201, json!({ "request_uri": format!("{REQUEST_URI}{id}"), "expires_in": REQUEST_LIFE }))))
let kept = (vec![held, entry], ok(201, json!({ "request_uri": format!("{REQUEST_URI}{id}"), "expires_in": REQUEST_LIFE })));
match &proof {
Some(proof) => settle(svc, proof, now, low, kept),
// A request with no proof has none to keep.
None => kept,
}
})
}
@@ -1999,11 +2019,14 @@ 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; `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.
/// The code grant: entries to log, and the answer. `jkt` is the token
/// request's proof's key, which the session is bound to: the request's
/// key, where it kept one, must be it (`spec/OAUTH.md`, the code grant's
/// step 2). `key` is the client key 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,
@@ -2039,7 +2062,7 @@ fn exchange(
let spend = || vec![json!({ "t": "oauthSpendCode", "code": code })];
if now >= a.at + CODE_LIFE
|| r.client_id != client_id
|| r.jkt != jkt
|| r.jkt.as_deref().is_some_and(|k| k != jkt)
|| r.client_key.as_deref() != key
|| r.redirect_uri != redirect_uri
{
harness/checks/oauth.mjs+8−7
@@ -300,11 +300,16 @@ async function newRequest(acct, { client, extra = {}, kind = 'PAR', whole = fals
})
const json = chance(0.1)
const jkt = chance(0.1)
// A PAR with no DPoP proof, the key bound at the token request, as the
// reference takes it (spec/OAUTH.md, "Pushed authorization requests",
// step 4).
const noProof = chance(0.1)
const send = (side) => {
const body = { ...p(side), ...(jkt ? { dpop_jkt: key.jkt } : {}) }
return json ? dpop[side.name].send(`${issuer(side)}/oauth/par`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }) : par(side, dpop[side.name], body)
const opts = noProof ? { dpop: null } : {}
return json ? dpop[side.name].send(`${issuer(side)}/oauth/par`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), ...opts }) : par(side, dpop[side.name], body, opts)
}
const res = await compare(kind, { par: p(ref), json, dpop_jkt: jkt }, send, (side, a) => view(side, a, (b) => ({ request_uri: typeof b?.request_uri === 'string' && b.request_uri.startsWith(URN) ? '<request_uri>' : b?.request_uri, expires_in: '<expires_in>' })))
const res = await compare(kind, { par: p(ref), json, dpop_jkt: jkt, ...(noProof ? { dpop: 'none' } : {}) }, send, (side, a) => view(side, a, (b) => ({ request_uri: typeof b?.request_uri === 'string' && b.request_uri.startsWith(URN) ? '<request_uri>' : b?.request_uri, expires_in: '<expires_in>' })))
for (const side of sides()) {
const a = res[side.name]
if (a.status === 201 && !(a.body.expires_in >= 299 && a.body.expires_in <= 300)) await fail(side, 'PAR expires_in (spec/OAUTH.md)', { par: p(ref) }, '299 to 300', a.body.expires_in)
@@ -1182,7 +1187,7 @@ export async function oauthClientLibrary(acct) {
export async function oauthDepartures() {
const d = new Dpop(await newKey())
const p = basePar()
const which = pick(['no DPoP', 'no state', 'empty state', 'a state used before', 'a parameter twice', 'no PAR', ...Object.keys(PAR_CAPS)])
const which = pick(['no state', 'empty state', 'a state used before', 'a parameter twice', 'no PAR', ...Object.keys(PAR_CAPS)])
const want = { status: 400, error: 'invalid_request' }
let got
if (which in PAR_CAPS) {
@@ -1191,10 +1196,6 @@ export async function oauthDepartures() {
got = view(cand, await par(cand, d, q))
return void (await held(which, q, status === 201 ? { status: 201, error: null } : want, got))
}
if (which === 'no DPoP') {
got = view(cand, await par(cand, d, p, { dpop: null }))
return void (await held(which, p, { status: 401, error: 'invalid_dpop_proof' }, got))
}
if (which === 'no state' || which === 'empty state') got = view(cand, await par(cand, d, { ...p, state: which === 'no state' ? undefined : '' }))
else if (which === 'a state used before') {
const first = await par(cand, d, p)
spec/OAUTH.md+23−8
@@ -298,10 +298,20 @@ The request is checked in this order, and the first failure answers, all
`ui_locales`, `display`, `max_age` as above; `login_hint` non-empty;
`id_token_hint` and `claims`, if given, a JWT and a JSON object; else
`invalid_request`.
4. The DPoP proof, as above: required here (else `401 invalid_dpop_proof`).
4. The DPoP proof, as above, if the request carries a `DPoP` header. A
request with none is taken, its DPoP key then bound at the token request
(below, "The code grant", step 2), as the reference takes it.
*Note:* this departs from `atproto/oauth.md`, which says a client must
send a proof at PAR; refusing a PAR without one, `401
invalid_dpop_proof`, is the stricter answer, and the right one. The
server takes it only because the reference does, and clients written
against the reference rely on it. It is a candidate to drop once such
clients send proofs at PAR.
5. The client: its `client_id` as under "Clients".
6. `dpop_jkt`, if given, the proof's key's thumbprint: else `401
invalid_token`, with `WWW-Authenticate: DPoP … error="invalid_token"`.
6. `dpop_jkt`, if given with a proof, the proof's key's thumbprint: else
`401 invalid_token`, with `WWW-Authenticate: DPoP … error="invalid_token"`.
Given without a proof, it is kept as the request's key.
7. `claims`, `id_token_hint` or `nonce` given: `invalid_request`.
8. `response_type` not `code`: `unsupported_response_type`.
9. Every scope token one the client's metadata declares: else
@@ -365,7 +375,8 @@ What is kept of it:
- `login_hint`, lower-cased.
- `prompt`: `create` if given `create`, else `consent`, whatever was given:
a public client never skips consent.
- the DPoP key's thumbprint: `dpop_jkt`, or else the proof's.
- the DPoP key's thumbprint: `dpop_jkt`, or else the proof's; none for a
request with neither.
- the rest as given.
**Which permissions parse.** A permission scope is as
@@ -670,7 +681,9 @@ each failure `400` unless said:
`400` error page, and the API answers `400`), whatever follows. A code
whose request a change of its account's state ended is spent
(`LIFECYCLE.md`, "OAuth sessions").
2. Its request's client is this one; the proof's key is the request's.
2. Its request's client is this one; the proof's key is the request's,
where the request kept one. A request kept with no key (PAR, step 4)
takes this proof's key: the session is bound to it.
3. `redirect_uri` is the request's, as kept.
4. `code_verifier` present, and its SHA-256, base64url, is the request's
`code_challenge`.
@@ -803,11 +816,12 @@ The passkeys themselves are kept as `PASSKEYS.md` says ("Durability").
The reference PDS does these, which the specs this page rests on say
otherwise; the server follows the specs, and the harness does not compare
them, but holds the server to this page:
them, but holds the server to this page. The first alone the server does
as the reference does, against the spec, and the harness compares it:
| The reference | The spec | The server |
| --- | --- | --- |
| takes a PAR with no DPoP proof, binding the key at the token request | `atproto/oauth.md`: clients must start DPoP at PAR | `401 invalid_dpop_proof` |
| takes a PAR with no DPoP proof, binding the key at the token request | `atproto/oauth.md`: clients must start DPoP at PAR | takes it too, alone of these (PAR, step 4): compared, and a candidate to drop |
| takes a PAR without `state`, or with an empty one | `atproto/oauth.md`: `state` is required | `400 invalid_request` |
| takes a `state` the client used before | `atproto/oauth.md`: servers should reject duplicate states | `400 invalid_request` for the same client within 24 hours |
| takes a parameter twice, the last winning | RFC 6749 §3.1: parameters must not be repeated | `400 invalid_request` |
@@ -832,7 +846,8 @@ its steps, among the others of `compare.mjs`:
- **sign-in:** a full flow for an account, with a random client (loopback
`client_id`s with scopes and redirect URIs drawn from a list), scope,
`login_hint`, `prompt`, `response_mode`, identifier, `remember`, and a
`login_hint`, `prompt`, `response_mode`, identifier, `remember`, a PAR
sometimes with no DPoP proof (with or without `dpop_jkt`), and a
narrowed consent or a rejection; the session joins the account's.
- **PAR, page, API, redirect, token, revoke refused:** one request with one
thing wrong, from the lists above, on each side; PAR's among them a body