Skip to main content

hyprstream_core/services/oauth/
token.rs

1//! OAuth 2.1 Token Endpoint.
2//!
3//! POST /oauth/token — exchanges authorization code, device code, or refresh token
4//! for an access token.
5//!
6//! Supports:
7//! - `grant_type=authorization_code` — PKCE + PolicyClient delegation
8//! - `grant_type=urn:ietf:params:oauth:grant-type:device_code` — RFC 8628 device flow
9//! - `grant_type=refresh_token` — OAuth 2.1 token refresh with rotation
10
11use std::sync::Arc;
12use std::time::Instant;
13
14use axum::{
15    extract::RawForm,
16    extract::State,
17    http::{header, HeaderMap, StatusCode},
18    response::{IntoResponse, Response},
19    Json,
20};
21use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
22use serde::Deserialize;
23use sha2::{Digest, Sha256};
24use subtle::ConstantTimeEq;
25
26use super::state::{DeviceCodeStatus, DpopJtiAdmission, OAuthState, RefreshTokenEntry};
27use hyprstream_pds::repo_authority::is_path_form_did_web;
28use hyprstream_rpc::auth::{jwk_thumbprint, JwkThumbprintInput};
29use hyprstream_rpc_std::policy_client::{IssueToken, IssueTokenProfile};
30// #1425: the public browser client_id routes the sender-bound exchange.
31use hyprstream_rpc::wasm_token_exchange::BROWSER_PUBLIC_CLIENT_ID;
32
33/// Device code grant type URN (RFC 8628).
34const DEVICE_CODE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code";
35/// JWT bearer grant type URN (RFC 7523).
36const JWT_BEARER_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:jwt-bearer";
37/// Token exchange grant type URN (RFC 8693).
38const TOKEN_EXCHANGE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
39
40/// Token exchange request (application/x-www-form-urlencoded).
41///
42/// All fields are optional because different grant types use different subsets.
43#[derive(Debug, Deserialize)]
44pub struct TokenRequest {
45    pub grant_type: String,
46    pub client_id: String,
47    // authorization_code fields
48    #[serde(default)]
49    pub code: Option<String>,
50    #[serde(default)]
51    pub redirect_uri: Option<String>,
52    #[serde(default)]
53    pub code_verifier: Option<String>,
54    // device_code field
55    #[serde(default)]
56    pub device_code: Option<String>,
57    // refresh_token field
58    #[serde(default)]
59    pub refresh_token: Option<String>,
60    // jwt-bearer assertion (RFC 7523)
61    #[serde(default)]
62    pub assertion: Option<String>,
63    // private_key_jwt client auth (RFC 7521 §4.2, RFC 7523 §2.2)
64    #[serde(default)]
65    pub client_assertion: Option<String>,
66    #[serde(default)]
67    pub client_assertion_type: Option<String>,
68    // token-exchange fields (RFC 8693)
69    #[serde(default)]
70    pub subject_token: Option<String>,
71    #[serde(default)]
72    pub subject_token_type: Option<String>,
73    #[serde(default)]
74    pub requested_token_type: Option<String>,
75    #[serde(default)]
76    pub actor_token: Option<String>,
77    // RFC 8693 §2.1 actor-token type indicator (#1425 r2 P2). Modeled
78    // explicitly so it is never silently dropped by the form extractor —
79    // a request that names an actor_token_type but omits actor_token must
80    // still be recognized and rejected by the browser handler, not treated
81    // as if it had no actor field at all.
82    #[serde(default)]
83    pub actor_token_type: Option<String>,
84    #[serde(default)]
85    pub scope: Option<String>,
86    #[serde(default)]
87    pub audience: Option<String>,
88    #[serde(default)]
89    pub tenant: Option<String>,
90    // RFC 8707 resource indicator (token-exchange, #1425).
91    #[serde(default)]
92    pub resource: Option<String>,
93}
94
95/// `hs_profile` (either class's profile string) and the two reserved client
96/// ids always take the dedicated Federate exchange parser. A configured TUI
97/// client id is reserved even with the profile field stripped, so a TUI
98/// form can never fall through to the generic RFC 8693 dispatcher; an
99/// UNCONFIGURED client id is not reserved and the generic dispatcher
100/// denies it (default-deny, W1.1 invariant).
101fn reserved_federate_form(raw: &[u8], tui_client: Option<&str>) -> bool {
102    url::form_urlencoded::parse(raw).any(|(key, value)| {
103        key == "hs_profile"
104            || (key == "client_id"
105                && (value == super::federate_source::CLIENT
106                    || tui_client.is_some_and(|tui| value == tui)))
107    })
108}
109
110/// POST /oauth/token — token exchange
111pub async fn exchange_token(
112    State(state): State<Arc<OAuthState>>,
113    req_headers: HeaderMap,
114    RawForm(raw): RawForm,
115) -> Response {
116    // Reserve the exact Federate clients/profiles before the generic RFC 8693
117    // dispatcher. The dedicated parser rejects duplicate and unknown fields;
118    // removing hs_profile cannot fall through to generic ID-token exchange.
119    // The TUI class joins the reservation only when configured.
120    #[cfg(feature = "postgres")]
121    let reserved_tui_client = state
122        .federate_issuer
123        .as_ref()
124        .and_then(|issuer| issuer.tui_client_id());
125    // The Federate issuer exists only under the postgres feature; without it
126    // no TUI class can be configured (default-deny, W1.1 invariant).
127    #[cfg(not(feature = "postgres"))]
128    let reserved_tui_client: Option<&str> = None;
129    if reserved_federate_form(&raw, reserved_tui_client) {
130        return super::federate_host::exchange(&state, &req_headers, &raw).await;
131    }
132    let params: TokenRequest = match serde_urlencoded::from_bytes(&raw) {
133        Ok(params) => params,
134        Err(_) => {
135            return token_error(
136                StatusCode::BAD_REQUEST,
137                "invalid_request",
138                Some("invalid token request form"),
139            )
140        }
141    };
142    tracing::info!(
143        grant_type = %params.grant_type,
144        client_id = %params.client_id,
145        has_code = params.code.is_some(),
146        has_redirect_uri = params.redirect_uri.is_some(),
147        has_code_verifier = params.code_verifier.is_some(),
148        "Token exchange request received"
149    );
150    // Extract optional DPoP proof header (RFC 9449).
151    let dpop_header: Option<String> = req_headers
152        .get("DPoP")
153        .and_then(|v| v.to_str().ok())
154        .map(str::to_owned);
155
156    // Extract __Secure-VaultDevice cookie for silent device-user linking.
157    let vault_device_cookie: Option<String> = req_headers
158        .get(header::COOKIE)
159        .and_then(|v| v.to_str().ok())
160        .and_then(|cookies| {
161            cookies.split(';').find_map(|part| {
162                let part = part.trim();
163                part.strip_prefix("__Secure-VaultDevice=")
164                    .map(str::to_owned)
165            })
166        });
167
168    // Client authentication gate. For confidential clients (those that
169    // declared token_endpoint_auth_method=private_key_jwt at
170    // registration), verify the client_assertion JWT against the
171    // client's JWKS BEFORE dispatching the grant. Public clients
172    // (auth_method=none or unset) skip this — PKCE substitutes for
173    // client auth per OAuth 2.1.
174    //
175    // On success this yields the RFC 7638 thumbprint of the assertion
176    // key (#1146 T3.3) — the grant handlers persist it into the refresh
177    // entry so the session stays bound to that exact key.
178    let client_assertion_jkt = match enforce_client_authentication(&state, &params).await {
179        Ok(jkt) => jkt,
180        Err(resp) => return resp,
181    };
182
183    match params.grant_type.as_str() {
184        "authorization_code" => {
185            exchange_authorization_code(
186                state,
187                params,
188                dpop_header,
189                vault_device_cookie,
190                client_assertion_jkt,
191            )
192            .await
193        }
194        "refresh_token" => {
195            exchange_refresh_token(
196                state,
197                params,
198                dpop_header,
199                vault_device_cookie,
200                client_assertion_jkt,
201            )
202            .await
203        }
204        gt if gt == DEVICE_CODE_GRANT_TYPE => {
205            exchange_device_code(
206                state,
207                params,
208                dpop_header,
209                vault_device_cookie,
210                client_assertion_jkt,
211            )
212            .await
213        }
214        gt if gt == JWT_BEARER_GRANT_TYPE => {
215            let assertion = match params.assertion {
216                Some(a) => a,
217                None => {
218                    return token_error(
219                        StatusCode::BAD_REQUEST,
220                        "invalid_request",
221                        Some("assertion is required"),
222                    )
223                }
224            };
225            super::jwt_bearer::exchange_jwt_bearer(&state, &params.client_id, &assertion).await
226        }
227        gt if gt == TOKEN_EXCHANGE_GRANT_TYPE => {
228            let subject_token = match params.subject_token {
229                Some(t) => t,
230                None => {
231                    return token_error(
232                        StatusCode::BAD_REQUEST,
233                        "invalid_request",
234                        Some("subject_token is required"),
235                    )
236                }
237            };
238            let subject_token_type = match params.subject_token_type {
239                Some(t) => t,
240                None => {
241                    return token_error(
242                        StatusCode::BAD_REQUEST,
243                        "invalid_request",
244                        Some("subject_token_type is required"),
245                    )
246                }
247            };
248            // S6 (#572): the UCAN grant path. Routed on a dedicated
249            // `subject_token_type` so it cannot be confused with the OIDC/WIT
250            // exchange flows. Requires sender-binding (DPoP) — ZSP.
251            if subject_token_type == crate::mac::exchange::UCAN_GRANT_TOKEN_TYPE {
252                // #698 Decision D: resolves a delegated actor's clearance off the
253                // signed policy's enrollment table, floored at Classical
254                // assurance; falls back to DenyUnlabeledResolver (fail-closed) on
255                // a node that hasn't installed a compiled policy.
256                let resolver = crate::mac::exchange_enrollment_resolver();
257                return super::token_exchange::exchange_ucan_grant(
258                    &state,
259                    &subject_token,
260                    dpop_header.as_deref(),
261                    params.scope.as_deref(),
262                    params.audience.as_deref(),
263                    resolver.as_ref(),
264                )
265                .await;
266            }
267            // #1425: the browser RFC 8693 sender-bound exchange (DPoP +
268            // cnf.jkt). Routed on the public browser client_id so it cannot be
269            // confused with the generic OIDC/WIT bearer exchange or the UCAN
270            // grant path. DPoP is mandatory inside the handler.
271            if params.client_id == BROWSER_PUBLIC_CLIENT_ID {
272                return super::token_exchange::exchange_browser_token_exchange(
273                    &state,
274                    &subject_token,
275                    &subject_token_type,
276                    dpop_header.as_deref(),
277                    params.audience.as_deref(),
278                    params.resource.as_deref(),
279                    params.scope.as_deref(),
280                    params.requested_token_type.as_deref(),
281                    params.actor_token.as_deref(),
282                    params.actor_token_type.as_deref(),
283                    params.tenant.as_deref(),
284                    &params.client_id,
285                )
286                .await;
287            }
288            let output_dpop_proof = match dpop_header.as_deref() {
289                Some(proof) => {
290                    let endpoint =
291                        format!("{}/oauth/token", state.issuer_url.trim_end_matches('/'));
292                    match super::dpop::verify_dpop_proof(proof, "POST", &endpoint, None) {
293                        Ok(verified) => Some(verified),
294                        Err(error) => {
295                            tracing::warn!(%error, "token exchange rejected invalid DPoP proof");
296                            return token_error(
297                                StatusCode::BAD_REQUEST,
298                                "invalid_dpop_proof",
299                                Some("DPoP proof verification failed"),
300                            );
301                        }
302                    }
303                }
304                None => None,
305            };
306            super::token_exchange::exchange_token_exchange(
307                &state,
308                &subject_token,
309                &subject_token_type,
310                params.audience.as_deref(),
311                params.scope.as_deref(),
312                params.actor_token.as_deref(),
313                output_dpop_proof,
314                params.requested_token_type.as_deref(),
315                params.tenant.as_deref(),
316                &params.client_id,
317            )
318            .await
319        }
320        _ => token_error(
321            StatusCode::BAD_REQUEST,
322            "unsupported_grant_type",
323            Some("Supported: authorization_code, refresh_token, device_code, jwt-bearer"),
324        ),
325    }
326}
327
328/// The immutable scope set of the grant being redeemed, used to derive
329/// the profile-correct issuer for assertion-audience checking.
330async fn bound_grant_scopes(state: &OAuthState, params: &TokenRequest) -> Option<Vec<String>> {
331    match params.grant_type.as_str() {
332        "authorization_code" => {
333            let code = params.code.as_deref()?;
334            let pending = state.pending_codes.read().await;
335            let entry = pending.get(code)?;
336            (entry.client_id == params.client_id).then(|| entry.scopes.clone())
337        }
338        "refresh_token" => {
339            let refresh_token = params.refresh_token.as_deref()?;
340            let entry = state
341                .get_refresh_token(refresh_token)
342                .await
343                .ok()
344                .flatten()?;
345            (entry.client_id == params.client_id).then_some(entry.scopes)
346        }
347        gt if gt == DEVICE_CODE_GRANT_TYPE => {
348            let device_code = params.device_code.as_deref()?;
349            let pending = state.pending_device_codes.read().await;
350            let entry = pending.get(device_code)?;
351            (entry.client_id == params.client_id).then(|| entry.scopes.clone())
352        }
353        _ => None,
354    }
355}
356
357/// The client-assertion key thumbprint bound to the grant being redeemed
358/// (#1146 T3.3): PAR-bound for `authorization_code`, issuance-bound for
359/// `refresh_token`. `None` when the grant carries no binding.
360async fn bound_assertion_jkt(state: &OAuthState, params: &TokenRequest) -> Option<String> {
361    match params.grant_type.as_str() {
362        "authorization_code" => {
363            let code = params.code.as_deref()?;
364            let pending = state.pending_codes.read().await;
365            let entry = pending.get(code)?;
366            (entry.client_id == params.client_id)
367                .then(|| entry.client_assertion_jkt.clone())
368                .flatten()
369        }
370        "refresh_token" => {
371            let refresh_token = params.refresh_token.as_deref()?;
372            let entry = state
373                .get_refresh_token(refresh_token)
374                .await
375                .ok()
376                .flatten()?;
377            (entry.client_id == params.client_id)
378                .then_some(entry.client_assertion_jkt)
379                .flatten()
380        }
381        _ => None,
382    }
383}
384
385/// Enforce token endpoint client authentication.
386///
387/// Resolves the registered client (DCR or CIMD-cached), then:
388///   - If the client requires `private_key_jwt`: `client_assertion` and
389///     `client_assertion_type` MUST be present and verify successfully.
390///   - If the client does NOT require it but an assertion was sent
391///     anyway: we still verify it (best-effort, defense in depth).
392///   - Unknown client_ids return invalid_client.
393///
394/// Returns the assertion key's RFC 7638 thumbprint when an assertion was
395/// verified (`Ok(Some(jkt))`), `Ok(None)` when no assertion was presented;
396/// the caller proceeds with the grant. Returns Err(Response) with the
397/// appropriate token error response on failure.
398async fn enforce_client_authentication(
399    state: &OAuthState,
400    params: &TokenRequest,
401) -> Result<Option<String>, Response> {
402    // CIMD client_ids are HTTPS URLs; DCR client_ids are UUIDs.
403    //
404    // For CIMD: on cache miss (entry expired between PAR/authorize
405    // admission and now), we MUST re-resolve via resolve_cimd_client,
406    // not fall through. Otherwise a client that declared
407    // token_endpoint_auth_method=private_key_jwt could pass through
408    // without an assertion check just because its cache entry aged
409    // out — a security regression.
410    //
411    // resolve_cimd_client re-runs the federation:register policy check
412    // and re-fetches metadata, so a revocation that happened during
413    // the user's consent step is honored at token time.
414    let client = if params.client_id.starts_with("https://") {
415        match state.cimd_cache.get(&params.client_id).await {
416            Some(c) => Some(c),
417            None => super::registration::resolve_cimd_client(state, &params.client_id)
418                .await
419                .ok(),
420        }
421    } else {
422        state.clients.read().await.get(&params.client_id).cloned()
423    };
424
425    let Some(client) = client else {
426        // Genuinely unknown client_id. For grants that don't need a
427        // RegisteredClient (jwt-bearer, token_exchange) the downstream
428        // handler dispatches without it. For grants that DO need one
429        // (authorization_code, refresh_token, device_code), the
430        // downstream handler's own client_id check on the pending entry
431        // will reject — but only if the IDs don't match. Permitting
432        // pass-through here is safe because:
433        //   - CIMD path above already attempts re-resolve, so a real
434        //     CIMD client_id has had two chances to be found.
435        //   - DCR clients with UUID IDs are only "absent" if they were
436        //     never registered, in which case no pending entry exists.
437        return Ok(None);
438    };
439
440    let needs_auth = super::client_auth::requires_private_key_jwt(&client);
441    let has_assertion = params.client_assertion.is_some() && params.client_assertion_type.is_some();
442
443    if needs_auth && !has_assertion {
444        // Client-actionable: the client knows their own
445        // token_endpoint_auth_method registration; we can tell them
446        // what's missing from the request they sent.
447        return Err(token_error(
448            StatusCode::UNAUTHORIZED,
449            "invalid_client",
450            Some("client_assertion required"),
451        ));
452    }
453
454    if has_assertion {
455        let assertion = params
456            .client_assertion
457            .as_deref()
458            .unwrap_or_else(|| unreachable!());
459        let atype = params
460            .client_assertion_type
461            .as_deref()
462            .unwrap_or_else(|| unreachable!());
463        // Derive the assertion audience from the immutable grant, not from
464        // caller-supplied scopes. atproto grants use the origin-only issuer
465        // advertised in RFC 8414 metadata; generic grants preserve the
466        // configured path-bearing issuer.
467        //
468        // #1146 T1.2: the accepted audience is the AS ISSUER — alone. The
469        // atproto OAuth profile mandates the issuer; RFC 7523 §3 also
470        // permits the token endpoint URL, but atproto does not, and
471        // `private_key_jwt` client auth ships with this conformance chain,
472        // so no deployed legacy client needs the endpoint form. Accepting
473        // both would leave the endpoint URL valid as an assertion target
474        // (replayable at any endpoint applying the same broadened rule).
475        // PAR accepts the issuer only as well (`par.rs`).
476        let issuer = match bound_grant_scopes(state, params).await {
477            Some(scopes) => state.issuer_for_scopes(&scopes),
478            None => state.issuer_url.clone(),
479        };
480        let expected_audiences = [issuer];
481        match super::client_auth::verify_client_assertion(
482            state,
483            &client,
484            atype,
485            assertion,
486            &expected_audiences,
487        )
488        .await
489        {
490            Ok(verified) => {
491                // #1146 T3.3: when the grant was bound to a specific
492                // assertion key (at PAR for authorization_code, at
493                // issuance for refresh_token), the presented assertion
494                // MUST verify under the same key — refresh cannot switch
495                // to another registered key, and removing the bound key
496                // from the client's JWKS revokes the session.
497                if let Some(bound_jkt) = bound_assertion_jkt(state, params).await {
498                    if bound_jkt != verified.key_jkt {
499                        tracing::warn!(
500                            client_id = %params.client_id,
501                            "client_assertion key does not match the grant-bound key"
502                        );
503                        return Err(token_error(
504                            StatusCode::UNAUTHORIZED,
505                            "invalid_client",
506                            None,
507                        ));
508                    }
509                }
510                return Ok(Some(verified.key_jkt));
511            }
512            Err(e) => {
513                // Full reason goes to logs; the public response stays
514                // opaque so we don't leak the validation logic / order
515                // (iss/sub/aud/exp/signature) to probing attackers.
516                tracing::warn!(
517                    client_id = %params.client_id,
518                    error = %e,
519                    "client_assertion verification failed"
520                );
521                return Err(token_error(
522                    StatusCode::UNAUTHORIZED,
523                    "invalid_client",
524                    None,
525                ));
526            }
527        }
528    }
529
530    Ok(None)
531}
532
533/// Verify a DPoP proof for the token endpoint, check JTI replay, enforce
534/// server-side nonces per RFC 9449 §8.
535///
536/// Returns `None` when no DPoP header is present (DPoP is optional at the
537/// token endpoint).
538/// Returns `Some(Ok(jkt))` on success; `Some(Err(response))` on failure.
539///
540/// Nonce enforcement policy:
541/// - First proof from a given `jkt` (no prior nonce issuance recorded for
542///   this key) is accepted as a bootstrap and a fresh nonce is issued in
543///   the response `DPoP-Nonce` header.
544/// - Subsequent proofs from the same `jkt` MUST include a server-issued
545///   nonce; otherwise we reject with `error: "use_dpop_nonce"` and a fresh
546///   nonce in the response header.
547/// - Any presented nonce MUST be one we issued and not expired (5-min
548///   sliding window).
549async fn verify_dpop_at_token_endpoint(
550    state: &OAuthState,
551    dpop_header: Option<&str>,
552    issuer: &str,
553) -> Option<Result<String, Response>> {
554    let proof_str = dpop_header?;
555    let token_endpoint = format!("{}/oauth/token", issuer.trim_end_matches('/'));
556    let proof = match super::dpop::verify_dpop_proof(proof_str, "POST", &token_endpoint, None) {
557        Ok(p) => p,
558        Err(e) => {
559            // The DPoP module's error variants describe internal
560            // checks (signature, jkt match, htm/htu, alg). Keep them
561            // out of the public response; logs carry the detail.
562            tracing::warn!("DPoP proof verification failed: {e}");
563            return Some(Err(token_error(
564                StatusCode::BAD_REQUEST,
565                "invalid_dpop_proof",
566                None,
567            )));
568        }
569    };
570    // JTI replay check. A full barrier is already metered and warning-rate-
571    // limited at insertion; only a duplicate emits a generic debug event.
572    let admission = state.check_and_record_dpop_jti_admission(&proof.jti, proof.iat);
573    if !admission.is_inserted() {
574        if let Some(message) = dpop_jti_rejection_log_message(admission) {
575            tracing::debug!("{message}");
576        }
577        return Some(Err(token_error(
578            StatusCode::BAD_REQUEST,
579            "invalid_dpop_proof",
580            Some("DPoP proof rejected"),
581        )));
582    }
583
584    // RFC 9449 §8 nonce enforcement.
585    let client_needs_nonce = state.dpop_client_requires_nonce(&proof.jkt).await;
586    match (client_needs_nonce, proof.nonce.as_deref()) {
587        (true, None) => {
588            // Subsequent request without nonce — reject with fresh nonce.
589            let fresh = state.issue_dpop_nonce().await;
590            state.mark_dpop_client_nonced(&proof.jkt).await;
591            tracing::warn!(jkt = %proof.jkt, "DPoP nonce required but proof omitted it");
592            return Some(Err(use_dpop_nonce_error(
593                &fresh,
594                "DPoP proof must include a server-issued nonce",
595            )));
596        }
597        (_, Some(presented)) => {
598            // Whether bootstrap or subsequent: a presented nonce must be one
599            // we issued. If invalid/expired, reject and rotate.
600            if !state.verify_dpop_nonce(presented).await {
601                let fresh = state.issue_dpop_nonce().await;
602                state.mark_dpop_client_nonced(&proof.jkt).await;
603                tracing::warn!(jkt = %proof.jkt, "DPoP nonce invalid or expired");
604                return Some(Err(use_dpop_nonce_error(
605                    &fresh,
606                    "DPoP nonce invalid or expired",
607                )));
608            }
609        }
610        (false, None) => {
611            // Bootstrap: first request from this jkt with no nonce. Accept;
612            // a fresh nonce will be issued on the success path (see
613            // `issue_token_with_refresh`).
614        }
615    }
616
617    Some(Ok(proof.jkt))
618}
619
620/// A saturated barrier is logged only by its rate-limited insertion path.
621/// Duplicate proofs receive a generic diagnostic that never includes a JTI.
622fn dpop_jti_rejection_log_message(admission: DpopJtiAdmission) -> Option<&'static str> {
623    (admission == DpopJtiAdmission::Duplicate).then_some("DPoP JTI replay rejected")
624}
625
626/// Build a `400 use_dpop_nonce` response with the current nonce in the
627/// `DPoP-Nonce` header (RFC 9449 §8).
628///
629/// atproto contract (#1113): `@atproto/oauth-client-browser` retries a token
630/// request on `400` + `{"error":"use_dpop_nonce"}` + a fresh `DPoP-Nonce`
631/// header — the client re-signs the DPoP proof carrying the new nonce and
632/// replays the request. This is the 400 form (not the resource-server 401
633/// form used in `auth.rs`); both carry the same `DPoP-Nonce` header.
634fn use_dpop_nonce_error(nonce: &str, description: &str) -> Response {
635    // `description` here is always client-actionable ("nonce required",
636    // "nonce expired") — that's the whole point of RFC 9449 §8: tell
637    // the client to retry with the nonce we just issued in the header.
638    let mut resp = token_error(StatusCode::BAD_REQUEST, "use_dpop_nonce", Some(description));
639    if let Ok(val) = axum::http::HeaderValue::from_str(nonce) {
640        resp.headers_mut().insert("DPoP-Nonce", val);
641    }
642    resp
643}
644
645/// Handle authorization_code grant type.
646async fn exchange_authorization_code(
647    state: Arc<OAuthState>,
648    params: TokenRequest,
649    dpop_header: Option<String>,
650    vault_device_cookie: Option<String>,
651    client_assertion_jkt: Option<String>,
652) -> Response {
653    let code = match params.code {
654        Some(c) => c,
655        None => {
656            return token_error(
657                StatusCode::BAD_REQUEST,
658                "invalid_request",
659                Some("code is required"),
660            )
661        }
662    };
663    let redirect_uri = match params.redirect_uri {
664        Some(r) => r,
665        None => {
666            return token_error(
667                StatusCode::BAD_REQUEST,
668                "invalid_request",
669                Some("redirect_uri is required"),
670            )
671        }
672    };
673    let code_verifier = match params.code_verifier {
674        Some(v) => v,
675        None => {
676            return token_error(
677                StatusCode::BAD_REQUEST,
678                "invalid_request",
679                Some("code_verifier is required"),
680            )
681        }
682    };
683
684    // Look up and remove pending code (single-use)
685    let pending = {
686        let mut codes = state.pending_codes.write().await;
687        codes.remove(&code)
688    };
689
690    let pending = match pending {
691        Some(p) => p,
692        None => {
693            return token_error(
694                StatusCode::BAD_REQUEST,
695                "invalid_grant",
696                Some("Authorization code not found or already used"),
697            );
698        }
699    };
700
701    if pending.is_expired() {
702        return token_error(
703            StatusCode::BAD_REQUEST,
704            "invalid_grant",
705            Some("Authorization code has expired"),
706        );
707    }
708
709    if params.client_id != pending.client_id {
710        return token_error(
711            StatusCode::BAD_REQUEST,
712            "invalid_grant",
713            Some("client_id does not match"),
714        );
715    }
716
717    if redirect_uri != pending.redirect_uri {
718        return token_error(
719            StatusCode::BAD_REQUEST,
720            "invalid_grant",
721            Some("redirect_uri does not match"),
722        );
723    }
724
725    // PKCE verification
726    let computed_challenge = {
727        let digest = Sha256::digest(code_verifier.as_bytes());
728        URL_SAFE_NO_PAD.encode(digest)
729    };
730
731    if computed_challenge
732        .as_bytes()
733        .ct_eq(pending.code_challenge.as_bytes())
734        .unwrap_u8()
735        == 0
736    {
737        return token_error(
738            StatusCode::BAD_REQUEST,
739            "invalid_grant",
740            Some("PKCE code_verifier verification failed"),
741        );
742    }
743
744    // Verify DPoP if present.
745    let token_issuer = state.issuer_for_scopes(&pending.scopes);
746    let dpop_jkt =
747        match verify_dpop_at_token_endpoint(&state, dpop_header.as_deref(), &token_issuer).await {
748            None => None,
749            Some(Ok(jkt)) => Some(jkt),
750            Some(Err(resp)) => return resp,
751        };
752
753    // #1113 rev2 finding 3 + 6: the atproto profile (granted scope set
754    // includes `atproto`) is a STRICT path — DPoP is mandatory and the proof
755    // key MUST match the `jkt` bound at PAR (stored on the auth code). Non-
756    // atproto flows keep DPoP optional and their existing behavior.
757    if super::state::atproto_profile_active(&pending.scopes) {
758        match (dpop_jkt.as_ref(), pending.dpop_jkt.as_ref()) {
759            (Some(proof_jkt), Some(bound_jkt)) if proof_jkt == bound_jkt => {
760                // DPoP key matches the PAR binding — proceed.
761            }
762            _ => {
763                tracing::warn!(
764                    client_id = %params.client_id,
765                    proof_jkt = ?dpop_jkt,
766                    bound_jkt = ?pending.dpop_jkt,
767                    "atproto profile requires a DPoP proof matching the PAR-bound key"
768                );
769                return token_error(
770                    StatusCode::BAD_REQUEST,
771                    "invalid_dpop_proof",
772                    Some("atproto profile requires a DPoP proof from the key bound at PAR"),
773                );
774            }
775        }
776    }
777
778    tracing::info!(client_id = %params.client_id, username = %pending.username, "PKCE verified, issuing token");
779    let sub = pending.username.clone();
780    let vk_ref = pending.verifying_key.as_ref();
781    issue_token_with_refresh(
782        &state,
783        &params.client_id,
784        pending.scopes,
785        pending.resource,
786        &sub,
787        pending.oidc_nonce,
788        true,
789        None,
790        vk_ref,
791        dpop_jkt,
792        client_assertion_jkt,
793        vault_device_cookie,
794    )
795    .await
796}
797
798/// Handle refresh_token grant type (OAuth 2.1 with rotation).
799async fn exchange_refresh_token(
800    state: Arc<OAuthState>,
801    params: TokenRequest,
802    dpop_header: Option<String>,
803    vault_device_cookie: Option<String>,
804    client_assertion_jkt: Option<String>,
805) -> Response {
806    let refresh_token = match params.refresh_token {
807        Some(rt) => rt,
808        None => {
809            return token_error(
810                StatusCode::BAD_REQUEST,
811                "invalid_request",
812                Some("refresh_token is required"),
813            )
814        }
815    };
816
817    let entry = match state.get_refresh_token(&refresh_token).await {
818        Ok(Some(e)) => e,
819        Ok(None) => {
820            return token_error(
821                StatusCode::BAD_REQUEST,
822                "invalid_grant",
823                Some("Refresh token not found or already used"),
824            );
825        }
826        Err(e) => {
827            tracing::error!(error = %e, "Refresh token store read failed");
828            return token_error(StatusCode::INTERNAL_SERVER_ERROR, "server_error", None);
829        }
830    };
831
832    // #1113 rev2 F3: validate client_id and DPoP BEFORE consuming the
833    // single-use refresh token. Consuming first and failing second strands
834    // the legitimate session on a missing/invalid proof.
835    if params.client_id != entry.client_id {
836        return token_error(
837            StatusCode::BAD_REQUEST,
838            "invalid_grant",
839            Some("client_id does not match"),
840        );
841    }
842
843    // MAC #547 / B1 (#673): a UCAN-grant refresh is re-evaluated through the S6
844    // gate chain with a MANDATORY fresh DPoP proof — never this generic OAuth
845    // rotation path (which treats DPoP as optional and does not re-check the
846    // ceiling). Preserve its existing fail-closed, single-use behavior.
847    if entry.ucan_grant.is_some() {
848        let claimed = match state.take_refresh_token(&refresh_token).await {
849            Ok(Some(claimed)) => claimed,
850            Ok(None) => {
851                return token_error(
852                    StatusCode::BAD_REQUEST,
853                    "invalid_grant",
854                    Some("Refresh token not found or already used"),
855                );
856            }
857            Err(e) => {
858                tracing::error!(error = %e, "Refresh token store take failed");
859                return token_error(StatusCode::INTERNAL_SERVER_ERROR, "server_error", None);
860            }
861        };
862        // UCAN refresh bypasses `issue_token_with_refresh` after this atomic
863        // claim, so apply the freeze before handing the grant to the direct
864        // UCAN re-mint path. The credential remains single-use and cannot
865        // produce another access or refresh token for a path-form subject.
866        if is_path_form_did_web(&claimed.username) {
867            return token_error(
868                StatusCode::BAD_REQUEST,
869                "invalid_grant",
870                Some(
871                    "token subject is a frozen path-form did:web account identifier; \
872                     host-form account minting is not available yet (#1159)",
873                ),
874            );
875        }
876        let Some(claimed_grant) = claimed.ucan_grant.as_ref() else {
877            tracing::error!("UCAN refresh token changed before atomic claim");
878            return token_error(StatusCode::INTERNAL_SERVER_ERROR, "server_error", None);
879        };
880        return super::token_exchange::exchange_ucan_grant_refresh(
881            &state,
882            claimed_grant,
883            dpop_header.as_deref(),
884        )
885        .await;
886    }
887
888    // Verify DPoP before consuming the refresh token. A use_dpop_nonce
889    // response must leave the credential available for the RFC 9449 retry.
890    let token_issuer = state.issuer_for_scopes(&entry.scopes);
891    let dpop_jkt =
892        match verify_dpop_at_token_endpoint(&state, dpop_header.as_deref(), &token_issuer).await {
893            None => None,
894            Some(Ok(jkt)) => Some(jkt),
895            Some(Err(resp)) => return resp,
896        };
897
898    // A sender-constrained token cannot be refreshed by another key or without
899    // a proof.
900    if !refresh_dpop_matches(entry.dpop_jkt.as_deref(), dpop_jkt.as_deref()) {
901        return token_error(
902            StatusCode::BAD_REQUEST,
903            "invalid_dpop_proof",
904            Some("DPoP proof must use the key bound to this refresh token"),
905        );
906    }
907
908    // The atproto profile is always DPoP-mandatory and sender-bound, even if
909    // a malformed legacy refresh entry somehow lacks a stored thumbprint.
910    if super::state::atproto_profile_active(&entry.scopes) {
911        match (&dpop_jkt, &entry.dpop_jkt) {
912            (Some(proof_jkt), Some(bound_jkt)) if proof_jkt == bound_jkt => {}
913            _ => {
914                return token_error(
915                    StatusCode::BAD_REQUEST,
916                    "invalid_dpop_proof",
917                    Some("atproto profile requires a DPoP proof from the key bound at issuance"),
918                );
919            }
920        }
921    }
922
923    // Validate the authority-controlled binding before atomically consuming
924    // the single-use credential. An operator-repairable mapping failure must
925    // fail closed without destroying the existing session.
926    if !is_path_form_did_web(&entry.username) {
927        if let Err(error) = resolve_hosted_account_binding(&state, &entry.username).await {
928            tracing::warn!(
929                username = %entry.username,
930                %error,
931                "refresh rejected before claim: hosted account binding unavailable"
932            );
933            return token_error(
934                StatusCode::BAD_REQUEST,
935                "invalid_grant",
936                Some("account has no valid hosted DID tenant binding"),
937            );
938        }
939    }
940
941    // Refresh prevention (v16 §3.3): a revoked or unknown session cannot
942    // refresh. Checked BEFORE the single-use claim so a rejected or
943    // unavailable check never consumes the credential (mirrors the DPoP
944    // ordering above).
945    if let Some(ref session_id) = entry.session_id {
946        let session_key =
947            hyprstream_rpc::auth::SessionKey::oidc(token_issuer.clone(), session_id.clone());
948        match hyprstream_rpc::auth::global_session_registry() {
949            Some(registry) => {
950                if registry.is_revoked(&session_key).await {
951                    tracing::warn!(username = %entry.username, "refresh rejected: session is revoked");
952                    return token_error(
953                        StatusCode::BAD_REQUEST,
954                        "invalid_grant",
955                        Some("session has been revoked"),
956                    );
957                }
958            }
959            None => {
960                tracing::error!("refresh rejected: session registry is not available");
961                return token_error(
962                    StatusCode::INTERNAL_SERVER_ERROR,
963                    "server_error",
964                    Some("session authority is unavailable"),
965                );
966            }
967        }
968    }
969
970    // Atomically claim only after all retryable DPoP validation succeeds.
971    // A successful claim prevents every other OAuth replica from minting with
972    // this single-use refresh credential.
973    let claimed = match state.take_refresh_token(&refresh_token).await {
974        Ok(Some(claimed)) => claimed,
975        Ok(None) => {
976            return token_error(
977                StatusCode::BAD_REQUEST,
978                "invalid_grant",
979                Some("Refresh token not found or already used"),
980            );
981        }
982        Err(e) => {
983            tracing::error!(error = %e, "Refresh token store take failed");
984            return token_error(StatusCode::INTERNAL_SERVER_ERROR, "server_error", None);
985        }
986    };
987
988    // Reconstruct verifying key from the atomically claimed record (cnf continuity across refreshes).
989    let stored_vk: Option<ed25519_dalek::VerifyingKey> = claimed
990        .verifying_key_bytes
991        .and_then(|b| ed25519_dalek::VerifyingKey::from_bytes(&b).ok());
992
993    // #1146 T3.3: carry the assertion-key binding forward across rotation.
994    // enforce_client_authentication already verified the presented
995    // assertion against this binding; for a legacy entry without one,
996    // ratchet onto the key that just verified.
997    let carried_assertion_jkt = claimed
998        .client_assertion_jkt
999        .clone()
1000        .or(client_assertion_jkt);
1001
1002    // Issue new access token + rotated refresh token. No id_token on refresh (OIDC Core § 12.2).
1003    issue_token_with_refresh(
1004        &state,
1005        &claimed.client_id,
1006        claimed.scopes,
1007        claimed.resource,
1008        &claimed.username,
1009        None,
1010        false,
1011        claimed.session_id.clone(),
1012        stored_vk.as_ref(),
1013        dpop_jkt,
1014        carried_assertion_jkt,
1015        vault_device_cookie,
1016    )
1017    .await
1018}
1019
1020/// Handle urn:ietf:params:oauth:grant-type:device_code grant type (RFC 8628 Section 3.4).
1021async fn exchange_device_code(
1022    state: Arc<OAuthState>,
1023    params: TokenRequest,
1024    dpop_header: Option<String>,
1025    vault_device_cookie: Option<String>,
1026    client_assertion_jkt: Option<String>,
1027) -> Response {
1028    let device_code = match params.device_code {
1029        Some(dc) => dc,
1030        None => {
1031            return token_error(
1032                StatusCode::BAD_REQUEST,
1033                "invalid_request",
1034                Some("device_code is required"),
1035            )
1036        }
1037    };
1038
1039    let mut device_codes = state.pending_device_codes.write().await;
1040
1041    let pending = match device_codes.get_mut(&device_code) {
1042        Some(p) => p,
1043        None => {
1044            return token_error(
1045                StatusCode::BAD_REQUEST,
1046                "invalid_grant",
1047                Some("Device code not found or already used"),
1048            );
1049        }
1050    };
1051
1052    // Check expiration
1053    if pending.is_expired() {
1054        let user_code = pending.user_code.clone();
1055        device_codes.remove(&device_code);
1056        let mut user_code_map = state.device_code_by_user_code.write().await;
1057        user_code_map.remove(&user_code);
1058        return token_error(
1059            StatusCode::BAD_REQUEST,
1060            "expired_token",
1061            Some("The device code has expired"),
1062        );
1063    }
1064
1065    // Validate client_id
1066    if params.client_id != pending.client_id {
1067        return token_error(
1068            StatusCode::BAD_REQUEST,
1069            "invalid_grant",
1070            Some("client_id does not match"),
1071        );
1072    }
1073
1074    // Rate limiting: check poll interval
1075    let now = Instant::now();
1076    if let Some(last) = pending.last_polled {
1077        if now.duration_since(last).as_secs() < pending.interval {
1078            return token_error(
1079                StatusCode::BAD_REQUEST,
1080                "slow_down",
1081                Some("Polling too frequently"),
1082            );
1083        }
1084    }
1085    match pending.status {
1086        DeviceCodeStatus::Pending => {
1087            pending.last_polled = Some(now);
1088            token_error(
1089                StatusCode::BAD_REQUEST,
1090                "authorization_pending",
1091                Some("The authorization request is still pending"),
1092            )
1093        }
1094        DeviceCodeStatus::Denied => {
1095            let user_code = pending.user_code.clone();
1096            device_codes.remove(&device_code);
1097            let mut user_code_map = state.device_code_by_user_code.write().await;
1098            user_code_map.remove(&user_code);
1099            token_error(
1100                StatusCode::BAD_REQUEST,
1101                "access_denied",
1102                Some("The user denied the authorization request"),
1103            )
1104        }
1105        DeviceCodeStatus::Approved => {
1106            let client_id = pending.client_id.clone();
1107            let scopes = pending.scopes.clone();
1108            let resource = pending.resource.clone();
1109            // Use the approving user's username as the JWT subject.
1110            // approved_by must be set when status is Approved; error defensively if missing.
1111            let approved_by = match pending.approved_by.clone() {
1112                Some(u) => u,
1113                None => {
1114                    // Internal invariant violation; do not surface
1115                    // server state shape to the polling client.
1116                    tracing::error!(
1117                        device_code_prefix = %&device_code[..8.min(device_code.len())],
1118                        "Device code approved but no approver identity recorded"
1119                    );
1120                    return token_error(StatusCode::INTERNAL_SERVER_ERROR, "server_error", None);
1121                }
1122            };
1123            let device_vk = pending.verifying_key;
1124            drop(device_codes);
1125
1126            // Verify DPoP before consuming the device code. A
1127            // `use_dpop_nonce` response must leave it available for retry.
1128            let token_issuer = state.issuer_for_scopes(&scopes);
1129            let dpop_jkt =
1130                match verify_dpop_at_token_endpoint(&state, dpop_header.as_deref(), &token_issuer)
1131                    .await
1132                {
1133                    None => None,
1134                    Some(Ok(jkt)) => Some(jkt),
1135                    Some(Err(resp)) => return resp,
1136                };
1137
1138            // A PDS attachment client records the host's iroh did:key at
1139            // registration. Its token request must demonstrate possession of
1140            // exactly that Ed25519 key via DPoP before a credential is minted.
1141            let registered_node_did = {
1142                let clients = state.clients.read().await;
1143                clients
1144                    .get(&client_id)
1145                    .and_then(|client| client.hyprstream_node_did.clone())
1146            };
1147            if !registered_host_dpop_matches(registered_node_did.as_deref(), dpop_jkt.as_deref()) {
1148                tracing::warn!(%client_id, "PDS host DID and DPoP key do not match");
1149                return token_error(
1150                    StatusCode::BAD_REQUEST,
1151                    "invalid_dpop_proof",
1152                    Some("DPoP proof must use the registered host key"),
1153                );
1154            }
1155
1156            // Atomically claim the approved code only after validation. A
1157            // concurrent poller cannot mint a second token after this point.
1158            let user_code = {
1159                let mut device_codes = state.pending_device_codes.write().await;
1160                let Some(current) = device_codes.get(&device_code) else {
1161                    return token_error(
1162                        StatusCode::BAD_REQUEST,
1163                        "invalid_grant",
1164                        Some("Device code not found or already used"),
1165                    );
1166                };
1167                if current.is_expired() {
1168                    let user_code = current.user_code.clone();
1169                    device_codes.remove(&device_code);
1170                    drop(device_codes);
1171                    let mut user_code_map = state.device_code_by_user_code.write().await;
1172                    user_code_map.remove(&user_code);
1173                    return token_error(
1174                        StatusCode::BAD_REQUEST,
1175                        "expired_token",
1176                        Some("The device code has expired"),
1177                    );
1178                }
1179                if current.status != DeviceCodeStatus::Approved {
1180                    return token_error(
1181                        StatusCode::BAD_REQUEST,
1182                        "invalid_grant",
1183                        Some("Device code not found or already used"),
1184                    );
1185                }
1186                let user_code = current.user_code.clone();
1187                device_codes.remove(&device_code);
1188                user_code
1189            };
1190            let mut user_code_map = state.device_code_by_user_code.write().await;
1191            user_code_map.remove(&user_code);
1192            drop(user_code_map);
1193
1194            // Device flow: no OIDC nonce and not initial OIDC auth.
1195            issue_token_with_refresh(
1196                &state,
1197                &client_id,
1198                scopes,
1199                resource,
1200                &approved_by,
1201                None,
1202                false,
1203                None,
1204                device_vk.as_ref(),
1205                dpop_jkt,
1206                client_assertion_jkt,
1207                vault_device_cookie,
1208            )
1209            .await
1210        }
1211    }
1212}
1213
1214fn registered_host_dpop_matches(registered_node_did: Option<&str>, dpop_jkt: Option<&str>) -> bool {
1215    let Some(node_did) = registered_node_did else {
1216        return true;
1217    };
1218    let Ok(node_key) = hyprstream_crypto::did_key::did_key_to_ed25519(node_did) else {
1219        return false;
1220    };
1221    let expected_jkt = jwk_thumbprint(&JwkThumbprintInput::Ed25519 { x: &node_key });
1222    dpop_jkt == Some(expected_jkt.as_str())
1223}
1224
1225fn refresh_dpop_matches(expected_jkt: Option<&str>, presented_jkt: Option<&str>) -> bool {
1226    expected_jkt.is_none() || expected_jkt == presented_jkt
1227}
1228
1229/// Generate a cryptographically random refresh token string.
1230fn generate_refresh_token() -> String {
1231    use rand::RngCore;
1232    let mut bytes = [0u8; 32];
1233    rand::rngs::OsRng.fill_bytes(&mut bytes);
1234    URL_SAFE_NO_PAD.encode(bytes)
1235}
1236
1237/// Issue a JWT access token via PolicyService, plus a rotated refresh token.
1238///
1239/// `sub` is the internal account username used for server-side bookkeeping
1240/// (refresh-token entry, profile lookup, device link). The emitted JWT's
1241/// `sub` claim is the atproto-conformant DID derived from it via
1242/// [`OAuthState::subject_did`] (#1113). Must be non-empty:
1243/// - authorization_code flow: pass `pending.username` (the Ed25519-authenticated user from the consent page)
1244/// - refresh_token flow: pass the original sub from the RefreshTokenEntry
1245/// - device_code flow: pass the approving user's username (from challenge-response)
1246///
1247/// `initial_auth`: true for authorization_code exchange (may issue id_token),
1248/// false for refresh_token and device_code (never issues id_token per OIDC Core § 12.2).
1249/// Resolve the PDS/Casbin tenant bound into a hosted account DID.
1250///
1251/// Hosted accounts are permanent host-form `did:web` identities:
1252/// `did:web:{account-label}.{account-zone}`. The account label selects the
1253/// record below `/pds/{tenant}/accounts`; the validated zone suffix is the
1254/// tenant. PLC and path-form DIDs have no hosted-zone binding and fail closed.
1255pub(super) fn hosted_account_tenant_from_did(
1256    did: &str,
1257    configured_zone: Option<&crate::account::AccountZone>,
1258) -> anyhow::Result<String> {
1259    let host = did
1260        .strip_prefix("did:web:")
1261        .ok_or_else(|| anyhow::anyhow!("hosted account DID must use did:web"))?;
1262    anyhow::ensure!(
1263        !host.contains(':'),
1264        "hosted account DID must be host-form, not path-form"
1265    );
1266    let (label, zone) = host
1267        .split_once('.')
1268        .ok_or_else(|| anyhow::anyhow!("hosted account DID has no account-zone suffix"))?;
1269    anyhow::ensure!(!label.is_empty(), "hosted account DID has an empty label");
1270    let tenant = crate::account::AccountZone::new(zone)?;
1271    let configured_zone = configured_zone
1272        .ok_or_else(|| anyhow::anyhow!("deployment account zone is not configured"))?;
1273    anyhow::ensure!(
1274        tenant == *configured_zone,
1275        "hosted account DID zone is not owned by this deployment"
1276    );
1277    Ok(tenant.apex().to_owned())
1278}
1279
1280pub(super) async fn resolve_hosted_account_binding(
1281    state: &OAuthState,
1282    sub: &str,
1283) -> anyhow::Result<(String, String)> {
1284    let did = state
1285        .check_atproto_account_eligibility(sub)
1286        .await
1287        .map_err(|error| anyhow::anyhow!("{error}"))?;
1288    // The DID's host form must be owned by this deployment, but the Casbin/PDS
1289    // tenant is the signed account-record binding, not a caller-supplied value
1290    // and not an inference from the DID text.
1291    hosted_account_tenant_from_did(&did, state.hosted_account_zone.as_ref())?;
1292    let tenant = state
1293        .hosted_account_tenant(&did)
1294        .await
1295        .map_err(anyhow::Error::msg)?
1296        .ok_or_else(|| anyhow::anyhow!("hosted DID has no signed local account binding"))?;
1297    Ok((did, tenant))
1298}
1299
1300async fn issue_token_with_refresh(
1301    state: &OAuthState,
1302    client_id: &str,
1303    scopes: Vec<String>,
1304    resource: Option<String>,
1305    sub: &str,
1306    oidc_nonce: Option<String>,
1307    initial_auth: bool,
1308    session_id: Option<String>,
1309    user_verifying_key: Option<&ed25519_dalek::VerifyingKey>,
1310    dpop_jkt: Option<String>,
1311    client_assertion_jkt: Option<String>,
1312    vault_device_cookie: Option<String>,
1313) -> Response {
1314    // ── #1159 freeze: path-form account subject guard ───────────────────────
1315    // This is the OAuth helper boundary: the authorization_code, refresh_token,
1316    // and device_code flows all funnel through here for both the access-token
1317    // `subject` and the persisted rotated `RefreshTokenEntry.username`. Blocking
1318    // `UserMappingStrategy::DidWeb` at config time stops NEW OIDC callbacks from
1319    // constructing a path-form subject, but it does not touch subjects already
1320    // durably persisted in refresh-token (and Valkey user-profile) stores. A
1321    // pre-upgrade refresh token carries `did:web:{authority}:users:{name}` as its
1322    // `username`; without this guard, refresh would mint a fresh access token for
1323    // that subject AND persist a newly rotated ~30-day refresh token carrying it,
1324    // keeping the path-form chain alive indefinitely.
1325    //
1326    // Fail-closed here bounds the OAuth refresh hole before it reaches the
1327    // PolicyService signing boundary: a stored path-form subject can no longer
1328    // be minted or rotated, so each pre-upgrade refresh token dies at its next
1329    // refresh attempt or at natural expiry — it cannot extend the lifetime. The
1330    // accounts themselves are reminted to host-form by E4 (#1176), not by this
1331    // freeze; this PR does NOT scan or revoke stored records at startup, because
1332    // that durable scan is exactly the out-of-band work #1176 owns and a partial
1333    // scan here would risk the data migration the freeze deliberately defers.
1334    // The predicate is the shared `is_path_form_did_web` so host-form
1335    // `did:web:alice.example.com`, plain usernames, and every non-did:web subject
1336    // pass through unchanged.
1337    if is_path_form_did_web(sub) {
1338        return token_error(
1339            StatusCode::BAD_REQUEST,
1340            "invalid_grant",
1341            Some(
1342                "token subject is a frozen path-form did:web account identifier; \
1343                 host-form account minting is not available yet (#1159)",
1344            ),
1345        );
1346    }
1347
1348    let scope_str = scopes.join(" ");
1349    let atproto_profile = super::state::atproto_profile_active(&scopes);
1350
1351    // The consent signature authenticates the user at the authorization
1352    // server; it is not a proof the client can present at a resource server.
1353    // A non-DPoP standard grant is a true Bearer token without cnf.jwk.
1354    // DPoP-bound grants retain their independently verified cnf.jkt below.
1355
1356    // #1113 rev2 finding 6 / r4 finding 1: the DID subject / account-
1357    // eligibility check is CONDITIONAL on the atproto profile. Non-atproto
1358    // flows (device, WIT, generic authorization-code) keep their existing
1359    // username subject byte-for-byte — the atproto strict path only activates
1360    // when the granted scope set includes `atproto`.
1361    //
1362    // atproto profile: the access token's `sub` MUST be the account's real
1363    // atproto DID. The eligibility check inspects the ACCOUNT/KEY MAPPING
1364    // (not the subject string): at9p-backed accounts are rejected; an account
1365    // with a mapped atproto DID gets that DID as `sub`; an account without a
1366    // mapped DID fails closed (#1124). The returned DID is already form-
1367    // validated by evaluate_atproto_eligibility → subject_did_for.
1368    // The mapped host-form DID is the binding authority for every user token,
1369    // regardless of whether the client requested the atproto profile. Its
1370    // account-zone suffix is the PDS/Casbin tenant; the full DID is an account
1371    // identity and is not a valid `/pds/{tenant}` path component.
1372    let (hosted_account_did, hosted_account_tenant) = match resolve_hosted_account_binding(
1373        state, sub,
1374    )
1375    .await
1376    {
1377        Ok(binding) => binding,
1378        Err(e) => {
1379            tracing::warn!(local_subject = %sub, error = %e, "rejecting token issuance: account has no hosted DID tenant binding");
1380            return token_error(
1381                StatusCode::BAD_REQUEST,
1382                "invalid_request",
1383                Some("account has no hosted DID tenant binding"),
1384            );
1385        }
1386    };
1387    let jwt_sub = if atproto_profile {
1388        hosted_account_did
1389    } else {
1390        sub.to_owned()
1391    };
1392    let token_issuer = state.issuer_for_scopes(&scopes);
1393    // Session binding (v16 §3.3): interactive/user session credentials MUST
1394    // carry a `sid`. A fresh issuance (`None` — authorization_code, device
1395    // code, or a pre-session legacy refresh) registers a new session with the
1396    // canonical authority; a refresh passes the persisted session through so
1397    // rotation keeps one stable sid across distinct credential IDs.
1398    // Registration is fail-closed: no unregistered session is ever minted.
1399    let session_id = match session_id {
1400        Some(sid) => Some(sid),
1401        None => {
1402            use rand::RngCore;
1403            let mut sid_bytes = [0u8; 32];
1404            rand::rngs::OsRng.fill_bytes(&mut sid_bytes);
1405            let sid = URL_SAFE_NO_PAD.encode(sid_bytes);
1406            let Some(registry) = hyprstream_rpc::auth::global_session_registry() else {
1407                tracing::error!("rejecting token issuance: session registry is not available");
1408                return token_error(
1409                    StatusCode::INTERNAL_SERVER_ERROR,
1410                    "server_error",
1411                    Some("session authority is unavailable"),
1412                );
1413            };
1414            let now = chrono::Utc::now().timestamp();
1415            let session_key =
1416                hyprstream_rpc::auth::SessionKey::oidc(token_issuer.clone(), sid.clone());
1417            let session_state = hyprstream_rpc::auth::SessionState {
1418                subject: jwt_sub.clone(),
1419                tenant: hosted_account_tenant.clone(),
1420                kind: hyprstream_rpc::auth::SessionKind::Interactive,
1421                created_at: now,
1422                expires_at: now + state.refresh_token_ttl as i64,
1423                status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
1424                clearance_epoch: 0,
1425            };
1426            if let Err(e) = registry.register_session(session_key, session_state).await {
1427                tracing::error!(error = %e, "rejecting token issuance: session registration failed");
1428                return token_error(
1429                    StatusCode::INTERNAL_SERVER_ERROR,
1430                    "server_error",
1431                    Some("session authority rejected the registration"),
1432                );
1433            }
1434            Some(sid)
1435        }
1436    };
1437    let issue_oidc_id_token =
1438        scopes.iter().any(|scope| scope == "openid") && initial_auth && state.signing_key.is_some();
1439    // Resolve the durable OIDC subject before issuing or persisting any token.
1440    // A database outage must not change `sub` from the stable UUID to the local
1441    // username, and a successful access token must not escape after a failed
1442    // profile read.
1443    let oidc_profile = if issue_oidc_id_token {
1444        let Some(user_store) = state.user_store_reader() else {
1445            tracing::error!(local_subject = %sub, "rejecting OIDC token issuance: relational user store is not configured");
1446            return token_error(
1447                StatusCode::INTERNAL_SERVER_ERROR,
1448                "server_error",
1449                Some("credential store is unavailable"),
1450            );
1451        };
1452        let profile = match user_store.get_profile(sub).await {
1453            Ok(Some(profile)) => profile,
1454            Ok(None) => {
1455                tracing::error!(local_subject = %sub, "rejecting OIDC token issuance: credential profile is missing");
1456                return token_error(
1457                    StatusCode::INTERNAL_SERVER_ERROR,
1458                    "server_error",
1459                    Some("credential profile is missing"),
1460                );
1461            }
1462            Err(error) => {
1463                tracing::error!(local_subject = %sub, %error, "rejecting OIDC token issuance: credential lookup failed");
1464                return token_error(
1465                    StatusCode::INTERNAL_SERVER_ERROR,
1466                    "server_error",
1467                    Some("credential store is unavailable"),
1468                );
1469            }
1470        };
1471        if profile.sub.as_deref().is_none_or(str::is_empty) {
1472            tracing::error!(local_subject = %sub, "rejecting OIDC token issuance: stable subject is missing");
1473            return token_error(
1474                StatusCode::INTERNAL_SERVER_ERROR,
1475                "server_error",
1476                Some("credential profile has no stable subject"),
1477            );
1478        }
1479        Some(profile)
1480    } else {
1481        None
1482    };
1483
1484    let result = state
1485        .policy_client
1486        .issue_token(&IssueToken {
1487            requested_scopes: Some(scopes.clone()),
1488            ttl: Some(state.token_ttl),
1489            audience: resource.clone(),
1490            subject: Some(jwt_sub.clone()),
1491            user_pub_key: None,
1492            dpop_jkt: dpop_jkt.clone(),
1493            issuer: Some(token_issuer.clone()),
1494            tenant: Some(hosted_account_tenant.clone()),
1495            require_clearance: false,
1496            session_id: session_id.clone(),
1497            issuance_profile: IssueTokenProfile::InteractiveSession,
1498            // RFC 9068 §2.2.1: the OAuth client this access token is issued to.
1499            client_id: Some(client_id.to_owned()),
1500        })
1501        .await;
1502
1503    match result {
1504        Ok(token_info) => {
1505            tracing::info!(client_id = %client_id, "Token issued successfully");
1506
1507            // Silently link device → user when __Secure-VaultDevice cookie accompanies the request.
1508            if let (Some(cookie_val), Some(ref ds), Some(ref sk)) = (
1509                &vault_device_cookie,
1510                &state.device_store,
1511                &state.signing_key,
1512            ) {
1513                let sk_bytes = sk.to_bytes();
1514                if let Some(pubkey) =
1515                    crate::auth::device_challenge::verify_vault_device_cookie(&sk_bytes, cookie_val)
1516                {
1517                    let fingerprint = bs58::encode(&pubkey).into_string();
1518                    let ds = ds.clone();
1519                    let sub_owned = sub.to_owned();
1520                    tokio::spawn(async move {
1521                        if let Err(e) = ds.link_device_user(&fingerprint, &sub_owned).await {
1522                            tracing::warn!(fingerprint = %fingerprint, error = %e, "device-user link failed");
1523                        } else {
1524                            tracing::debug!(fingerprint = %fingerprint, sub = %sub_owned, "device linked to user");
1525                        }
1526                    });
1527                }
1528            }
1529
1530            let now = chrono::Utc::now().timestamp();
1531            let expires_in = (token_info.expires_at - now).max(0);
1532            // Issue a fresh DPoP nonce when the client used DPoP (RFC 9449 §8).
1533            // Also record that this jkt has now been issued a nonce so future
1534            // proofs are required to carry one.
1535            let dpop_nonce = if let Some(ref jkt) = dpop_jkt {
1536                let n = state.issue_dpop_nonce().await;
1537                state.mark_dpop_client_nonced(jkt).await;
1538                Some(n)
1539            } else {
1540                None
1541            };
1542
1543            // Generate and persist a refresh token (RocksDB).
1544            let refresh_token = generate_refresh_token();
1545            {
1546                let entry = RefreshTokenEntry {
1547                    client_id: client_id.to_owned(),
1548                    username: sub.to_owned(),
1549                    scopes: scopes.clone(),
1550                    resource,
1551                    expires_at_unix: now + state.refresh_token_ttl as i64,
1552                    verifying_key_bytes: user_verifying_key.map(|vk| *vk.as_bytes()),
1553                    dpop_jkt: dpop_jkt.clone(),
1554                    client_assertion_jkt: client_assertion_jkt.clone(),
1555                    ucan_grant: None, // generic OAuth refresh; not a UCAN grant (MAC #547 B1)
1556                    session_id: session_id.clone(),
1557                };
1558                if let Err(e) = state
1559                    .put_refresh_token(&refresh_token, &entry, state.refresh_token_ttl as u64)
1560                    .await
1561                {
1562                    tracing::error!(error = %e, "Failed to persist refresh token");
1563                }
1564            }
1565
1566            // Build OIDC id_token when: scope includes "openid", signing key is available,
1567            // and this is an initial authorization (not refresh/device per OIDC Core § 12.2).
1568            let id_token = if issue_oidc_id_token {
1569                let id_exp = now + 300; // 5-minute id_token lifetime
1570                let mut id_claims = hyprstream_rpc::auth::IdTokenClaims::new(
1571                    token_issuer,
1572                    sub.to_owned(),
1573                    client_id.to_owned(),
1574                    now,
1575                    id_exp,
1576                )
1577                .with_nonce(oidc_nonce)
1578                .with_auth_time(now)
1579                .with_tenant(hosted_account_tenant.clone());
1580
1581                // Add profile claims based on requested scopes.
1582                let Some(profile) = oidc_profile else {
1583                    unreachable!("OIDC profile was loaded before token issuance")
1584                };
1585                if scopes.iter().any(|s| s == "profile") {
1586                    id_claims.preferred_username = Some(sub.to_owned());
1587                    id_claims.name = profile.name;
1588                }
1589                if scopes.iter().any(|s| s == "email") {
1590                    id_claims.email = profile.email;
1591                    id_claims.email_verified = profile.email_verified;
1592                }
1593                let Some(stable_sub) = profile.sub else {
1594                    unreachable!("stable OIDC subject was validated before token issuance")
1595                };
1596                id_claims.sub = stable_sub;
1597
1598                // SAFETY: signing_key.is_some() checked in the outer condition.
1599                let Some(ref sk) = state.signing_key else {
1600                    unreachable!()
1601                };
1602                let jwt_key =
1603                    hyprstream_rpc::node_identity::derive_purpose_key(sk, "hyprstream-jwt-v1");
1604                let id_token_jwt = hyprstream_rpc::auth::jwt::encode_id_token(&id_claims, &jwt_key);
1605                Some(id_token_jwt)
1606            } else {
1607                None
1608            };
1609
1610            let mut response_json = build_token_response_json(
1611                atproto_profile,
1612                dpop_jkt.is_some(),
1613                &token_info.token,
1614                &jwt_sub,
1615                &scope_str,
1616                expires_in,
1617                &refresh_token,
1618            );
1619            if let Some(id_token) = id_token {
1620                response_json["id_token"] = serde_json::Value::String(id_token);
1621            }
1622
1623            let mut resp = (
1624                StatusCode::OK,
1625                [
1626                    (header::CACHE_CONTROL, "no-store"),
1627                    (header::PRAGMA, "no-cache"),
1628                ],
1629                Json(response_json),
1630            )
1631                .into_response();
1632            if let Some(nonce) = dpop_nonce {
1633                if let Ok(val) = axum::http::HeaderValue::from_str(&nonce) {
1634                    resp.headers_mut().insert("DPoP-Nonce", val);
1635                }
1636            }
1637            resp
1638        }
1639        Err(e) => {
1640            tracing::error!(client_id = %client_id, error = %e, "Token issuance failed");
1641            token_error(StatusCode::INTERNAL_SERVER_ERROR, "server_error", None)
1642        }
1643    }
1644}
1645
1646/// Build the token-endpoint success response JSON (#1113 rev2 finding 1).
1647///
1648/// Factored pure so the atproto `atprotoOAuthTokenResponseSchema` shape and the
1649/// generic OAuth shapes are unit-testable without an `OAuthState` +
1650/// PolicyClient. A DPoP-bound token must advertise the DPoP token type;
1651/// the atproto profile additionally requires a top-level account DID.
1652pub(crate) fn build_token_response_json(
1653    atproto_profile: bool,
1654    dpop_bound: bool,
1655    access_token: &str,
1656    sub: &str,
1657    scope_str: &str,
1658    expires_in: i64,
1659    refresh_token: &str,
1660) -> serde_json::Value {
1661    let mut response = serde_json::json!({
1662            "access_token": access_token,
1663            "token_type": access_token_type(dpop_bound),
1664            "expires_in": expires_in,
1665            "scope": scope_str,
1666            "refresh_token": refresh_token,
1667    });
1668    if atproto_profile {
1669        response["sub"] = serde_json::Value::String(sub.to_owned());
1670    }
1671    response
1672}
1673
1674pub(crate) fn access_token_type(dpop_bound: bool) -> &'static str {
1675    if dpop_bound {
1676        "DPoP"
1677    } else {
1678        "Bearer"
1679    }
1680}
1681
1682/// Build an OAuth 2.1 §5.3 token-endpoint error response.
1683///
1684/// `description` is `Some(...)` only when the message is **client-
1685/// actionable** (refers to something the client themselves can fix in
1686/// their request — missing field, wrong assertion type, redirect_uri
1687/// mismatch). For server-internal failures (policy denials, dependency
1688/// outages, claim mismatches, signature failures) pass `None`: the
1689/// public response carries only the OAuth error code, and the caller
1690/// logs the full reason via tracing for operators.
1691///
1692/// Rationale: returning details like "PolicyService unreachable" or
1693/// "iss does not match client_id" leaks internal IAM topology and
1694/// validation order to unauthenticated callers. OAuth 2.1 §5.3
1695/// permits `error_description` to be omitted; standard practice
1696/// among hardened IdPs is to omit it for security-sensitive failures.
1697fn token_error(status: StatusCode, error: &str, description: Option<&str>) -> Response {
1698    (
1699        status,
1700        [
1701            (header::CACHE_CONTROL, "no-store"),
1702            (header::PRAGMA, "no-cache"),
1703        ],
1704        Json(token_error_body(error, description)),
1705    )
1706        .into_response()
1707}
1708
1709/// Pure JSON-body construction for `token_error`. Split out so unit
1710/// tests can assert on the body shape (notably: `error_description`
1711/// is omitted entirely when `description` is `None`, not serialized
1712/// as `null`).
1713fn token_error_body(error: &str, description: Option<&str>) -> serde_json::Value {
1714    let mut body = serde_json::Map::new();
1715    body.insert(
1716        "error".to_owned(),
1717        serde_json::Value::String(error.to_owned()),
1718    );
1719    if let Some(d) = description {
1720        body.insert(
1721            "error_description".to_owned(),
1722            serde_json::Value::String(d.to_owned()),
1723        );
1724    }
1725    serde_json::Value::Object(body)
1726}
1727
1728#[cfg(test)]
1729#[allow(clippy::unwrap_used, clippy::expect_used)]
1730mod tests {
1731    use super::*;
1732
1733    const TUI_CLIENT: &str = "hyprstream-tui-staging";
1734
1735    #[test]
1736    fn federate_form_cannot_downgrade_to_generic_exchange() {
1737        assert!(super::reserved_federate_form(
1738            b"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&hs_profile=federate-session-v1",
1739            None
1740        ));
1741        assert!(super::reserved_federate_form(
1742            format!(
1743            "client_id={}&subject_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aid_token",
1744            super::super::federate_source::CLIENT
1745        )
1746            .as_bytes(),
1747            None
1748        ));
1749        assert!(super::reserved_federate_form(
1750            format!(
1751                "client_id=ordinary&client_id={}",
1752                super::super::federate_source::CLIENT
1753            )
1754            .as_bytes(),
1755            None
1756        ));
1757        // The TUI class joins the reservation only when configured, by exact
1758        // client id, with or without the profile field present.
1759        assert!(super::reserved_federate_form(
1760            format!("client_id={TUI_CLIENT}").as_bytes(),
1761            Some(TUI_CLIENT)
1762        ));
1763        assert!(super::reserved_federate_form(
1764            format!("client_id={TUI_CLIENT}&hs_profile=federate-tui-v1").as_bytes(),
1765            Some(TUI_CLIENT)
1766        ));
1767        assert!(!super::reserved_federate_form(
1768            format!("client_id={TUI_CLIENT}").as_bytes(),
1769            None
1770        ));
1771        assert!(!super::reserved_federate_form(
1772            b"grant_type=authorization_code&client_id=ordinary",
1773            None
1774        ));
1775        assert!(!super::reserved_federate_form(
1776            b"client_id=ordinary&grant_type=refresh_token",
1777            Some(TUI_CLIENT)
1778        ));
1779    }
1780
1781    #[test]
1782    fn dpop_replay_logging_is_generic_and_never_bypasses_full_rate_limit() {
1783        assert_eq!(
1784            dpop_jti_rejection_log_message(DpopJtiAdmission::Duplicate),
1785            Some("DPoP JTI replay rejected")
1786        );
1787        assert_eq!(dpop_jti_rejection_log_message(DpopJtiAdmission::Full), None);
1788        assert_eq!(
1789            dpop_jti_rejection_log_message(DpopJtiAdmission::InvalidLifetime),
1790            None
1791        );
1792    }
1793
1794    #[test]
1795    fn hosted_account_tenant_is_zone_bound_into_host_form_did() {
1796        let zone = crate::account::AccountZone::new("acct.example.com").unwrap();
1797        assert_eq!(
1798            hosted_account_tenant_from_did("did:web:alice.acct.example.com", Some(&zone)).unwrap(),
1799            "acct.example.com"
1800        );
1801        for unbound in [
1802            "did:plc:abcdefghijklmnqrstuvwx2p",
1803            "did:web:example.com:users:alice",
1804            "did:web:alice",
1805        ] {
1806            assert!(hosted_account_tenant_from_did(unbound, Some(&zone)).is_err());
1807        }
1808        assert!(
1809            hosted_account_tenant_from_did("did:web:alice.other.example.com", Some(&zone)).is_err()
1810        );
1811        assert!(hosted_account_tenant_from_did("did:web:alice.acct.example.com", None).is_err());
1812    }
1813
1814    #[test]
1815    fn token_error_body_omits_description_when_none() {
1816        let body = token_error_body("invalid_client", None);
1817        let obj = body.as_object().unwrap();
1818        assert_eq!(
1819            obj.get("error").and_then(|v| v.as_str()),
1820            Some("invalid_client")
1821        );
1822        assert!(
1823            !obj.contains_key("error_description"),
1824            "description field MUST be absent when None — leaks happen via null/empty too"
1825        );
1826        assert_eq!(obj.len(), 1, "no extra fields");
1827    }
1828
1829    #[test]
1830    fn token_error_body_includes_description_when_some() {
1831        let body = token_error_body("invalid_request", Some("code is required"));
1832        let obj = body.as_object().unwrap();
1833        assert_eq!(
1834            obj.get("error_description").and_then(|v| v.as_str()),
1835            Some("code is required")
1836        );
1837    }
1838
1839    #[test]
1840    fn registered_pds_host_requires_its_dpop_key() {
1841        let key = ed25519_dalek::SigningKey::generate(&mut rand::rngs::OsRng);
1842        let did = hyprstream_crypto::did_key::ed25519_to_did_key(key.verifying_key().as_bytes());
1843        let matching_jkt = jwk_thumbprint(&JwkThumbprintInput::Ed25519 {
1844            x: key.verifying_key().as_bytes(),
1845        });
1846
1847        assert!(registered_host_dpop_matches(
1848            Some(&did),
1849            Some(&matching_jkt),
1850        ));
1851        assert!(!registered_host_dpop_matches(Some(&did), None));
1852        assert!(!registered_host_dpop_matches(Some(&did), Some("other-key")));
1853        assert!(!registered_host_dpop_matches(
1854            Some("did:key:zinvalid"),
1855            Some(&matching_jkt)
1856        ));
1857        assert!(registered_host_dpop_matches(None, None));
1858    }
1859
1860    #[test]
1861    fn dpop_bound_refresh_requires_the_original_key() {
1862        assert!(refresh_dpop_matches(None, None));
1863        assert!(refresh_dpop_matches(None, Some("new-key")));
1864        assert!(refresh_dpop_matches(Some("bound-key"), Some("bound-key")));
1865        assert!(!refresh_dpop_matches(Some("bound-key"), None));
1866        assert!(!refresh_dpop_matches(Some("bound-key"), Some("other-key")));
1867    }
1868
1869    #[test]
1870    fn token_error_body_never_carries_internal_substrings() {
1871        // Regression guard: no caller in token.rs should ever pass a
1872        // description containing these internal-state markers. The
1873        // sweep in 2026-05-26 stripped them all to None. If a future
1874        // change adds one back, this test won't catch it directly —
1875        // but the documented rule for token_error makes it a code-
1876        // review item. The test here pins the API: `None` yields an
1877        // empty object, so any leak would have to be explicit in a
1878        // caller's `Some(...)`.
1879        let body = token_error_body("invalid_client", None);
1880        let serialized = body.to_string();
1881        for forbidden in &[
1882            "PolicyService",
1883            "federation:register",
1884            "Failed to fetch",
1885            "iss does not match",
1886            "Token store error",
1887        ] {
1888            assert!(
1889                !serialized.contains(forbidden),
1890                "opaque response unexpectedly leaks `{forbidden}`: {serialized}"
1891            );
1892        }
1893    }
1894
1895    /// #1113: the DPoP nonce-retry contract that
1896    /// `@atproto/oauth-client-browser` relies on — HTTP 400 with
1897    /// `error: use_dpop_nonce` AND a `DPoP-Nonce` response header so the
1898    /// client can re-sign and replay the proof.
1899    #[test]
1900    fn use_dpop_nonce_error_carries_atproto_retry_contract() {
1901        // Draw the test nonce from OsRng exactly as production
1902        // (`OAuthState::issue_dpop_nonce`) does. A hard-coded literal here
1903        // tripped CodeQL `rust/hard-coded-cryptographic-value` (#1121) — a
1904        // false positive (test-only value, never a crypto sink), but the
1905        // literal-free form is also a more faithful test of the real shape.
1906        use rand::Rng;
1907        let nonce = URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 16]>());
1908        let resp = use_dpop_nonce_error(&nonce, "DPoP proof must include a server-issued nonce");
1909        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1910        assert_eq!(
1911            resp.headers()
1912                .get("DPoP-Nonce")
1913                .and_then(|v| v.to_str().ok()),
1914            Some(nonce.as_str()),
1915            "DPoP-Nonce header MUST carry the fresh nonce for client retry"
1916        );
1917    }
1918
1919    /// #1113: a nonce value that is not a valid HTTP header token still
1920    /// yields a 400 `use_dpop_nonce` body — the nonce header is omitted
1921    /// (graceful) but the error contract the client keys on is preserved.
1922    #[test]
1923    fn use_dpop_nonce_error_keeps_400_on_unheaderable_nonce() {
1924        // Map OsRng bytes into the C0 control range (0x00–0x1F): every byte
1925        // is then invalid in an HTTP header value, so
1926        // `HeaderValue::from_str` MUST reject it and the header is omitted.
1927        // (The previous "not valid token" literal contained only spaces,
1928        // which ARE valid header bytes — the header was silently inserted
1929        // and the graceful-omission branch went untested. The literal also
1930        // tripped CodeQL `rust/hard-coded-cryptographic-value`, #1121.)
1931        use rand::Rng;
1932        let bytes: Vec<u8> = rand::rngs::OsRng
1933            .gen::<[u8; 8]>()
1934            .into_iter()
1935            .map(|b| b % 0x20)
1936            .collect();
1937        let nonce = String::from_utf8(bytes).expect("C0 control bytes are valid UTF-8");
1938        let resp = use_dpop_nonce_error(&nonce, "expired");
1939        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1940        assert!(
1941            resp.headers().get("DPoP-Nonce").is_none(),
1942            "unheaderable nonce MUST be omitted from the response"
1943        );
1944    }
1945
1946    /// #1113 rev2 finding 1: the atproto token response matches
1947    /// atprotoOAuthTokenResponseSchema — `token_type: "DPoP"`, a top-level
1948    /// `sub` that is a valid atproto DID (did:plc or host-form did:web), and
1949    /// a scope containing `atproto`. Uses a valid `did:plc` subject (the
1950    /// spec-valid form; path-form did:web is rejected by @atproto/did — #1124).
1951    #[test]
1952    fn atproto_token_response_matches_schema_shape() {
1953        let json = build_token_response_json(
1954            true,
1955            true,
1956            "access-jwt",
1957            "did:plc:abcdefghijklmnqrstuvwx2p",
1958            "atproto transition:generic",
1959            3600,
1960            "rt",
1961        );
1962        assert_eq!(json["token_type"].as_str(), Some("DPoP"));
1963        let sub = json["sub"].as_str().expect("top-level sub required");
1964        // Valid atproto DID: did:plc (or host-form did:web with NO path).
1965        assert!(
1966            sub.starts_with("did:plc:") || {
1967                if let Some(rest) = sub.strip_prefix("did:web:") {
1968                    rest.split(':').count() <= 2 && !rest.contains('/')
1969                } else {
1970                    false
1971                }
1972            },
1973            "atproto sub must be did:plc or host-form did:web (no path), got {sub}"
1974        );
1975        let scope = json["scope"].as_str().expect("scope required");
1976        assert!(
1977            scope.split_whitespace().any(|s| s == "atproto"),
1978            "scope missing atproto"
1979        );
1980        assert_eq!(json["access_token"].as_str(), Some("access-jwt"));
1981        assert_eq!(json["refresh_token"].as_str(), Some("rt"));
1982    }
1983
1984    /// #1113 rev2 finding 6 (regression): a non-atproto grant (e.g. device
1985    /// flow, scopes without `atproto`) keeps the legacy Bearer shape with NO
1986    /// top-level `sub` — existing principals are byte-for-byte unchanged.
1987    #[test]
1988    fn non_atproto_token_response_is_bearer_without_sub() {
1989        let json =
1990            build_token_response_json(false, false, "access-jwt", "alice", "read:*:*", 3600, "rt");
1991        assert_eq!(json["token_type"].as_str(), Some("Bearer"));
1992        assert!(
1993            json.get("sub").is_none(),
1994            "non-atproto response MUST NOT carry a top-level sub"
1995        );
1996    }
1997
1998    #[test]
1999    fn non_atproto_dpop_token_response_advertises_binding_without_sub() {
2000        let json =
2001            build_token_response_json(false, true, "access-jwt", "alice", "read:*:*", 3600, "rt");
2002        assert_eq!(json["token_type"].as_str(), Some("DPoP"));
2003        assert!(json.get("sub").is_none());
2004    }
2005
2006    /// #1113 rev2 finding 3: PAR↔token DPoP binding — a proof whose `jkt`
2007    /// does not match the PAR-bound thumbprint must be rejected. The binding
2008    /// check is a plain equality compare; pin the comparator semantics.
2009    #[test]
2010    fn dpop_jkt_binding_rejects_mismatched_key() {
2011        let bound: Option<String> = Some("jkt-A".into());
2012        let proof: Option<String> = Some("jkt-B".into());
2013        // The token endpoint accepts only when both are present AND equal.
2014        let matches = matches!(
2015            (proof.as_ref(), bound.as_ref()),
2016            (Some(a), Some(b)) if a == b
2017        );
2018        assert!(!matches, "mismatched jkt must not bind");
2019        let bound2: Option<String> = Some("jkt-A".into());
2020        let matches2 = matches!(
2021            (proof.as_ref(), bound2.as_ref()),
2022            (Some(a), Some(b)) if a == b
2023        );
2024        assert!(!matches2);
2025        let proof_same: Option<String> = Some("jkt-A".into());
2026        let matches3 = matches!(
2027            (proof_same.as_ref(), bound.as_ref()),
2028            (Some(a), Some(b)) if a == b
2029        );
2030        assert!(matches3, "equal jkt must bind");
2031    }
2032
2033    // ── #1159 freeze: pre-upgrade path-form refresh token must not rotate ──
2034
2035    /// A `TokenStore` that counts `put` calls (rotation writes) and otherwise
2036    /// behaves like a small in-memory map. Used to prove a path-form refresh
2037    /// fails *without* persisting a rotated token.
2038    struct RecordingTokenStore {
2039        inner: parking_lot::Mutex<std::collections::HashMap<String, RefreshTokenEntry>>,
2040        puts: std::sync::atomic::AtomicUsize,
2041    }
2042
2043    impl RecordingTokenStore {
2044        fn new() -> Arc<Self> {
2045            Arc::new(Self {
2046                inner: parking_lot::Mutex::new(std::collections::HashMap::new()),
2047                puts: std::sync::atomic::AtomicUsize::new(0),
2048            })
2049        }
2050        fn put_count(&self) -> usize {
2051            self.puts.load(std::sync::atomic::Ordering::SeqCst)
2052        }
2053    }
2054
2055    #[async_trait::async_trait]
2056    impl crate::services::oauth::token_store::TokenStore for RecordingTokenStore {
2057        async fn put(
2058            &self,
2059            token: &str,
2060            entry: &RefreshTokenEntry,
2061            _ttl: u64,
2062        ) -> anyhow::Result<()> {
2063            self.puts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2064            self.inner.lock().insert(token.to_owned(), entry.clone());
2065            Ok(())
2066        }
2067        async fn get(&self, token: &str) -> anyhow::Result<Option<RefreshTokenEntry>> {
2068            Ok(self.inner.lock().get(token).cloned())
2069        }
2070        async fn take(&self, token: &str) -> anyhow::Result<Option<RefreshTokenEntry>> {
2071            Ok(self.inner.lock().remove(token))
2072        }
2073        async fn delete(&self, token: &str) -> anyhow::Result<()> {
2074            self.inner.lock().remove(token);
2075            Ok(())
2076        }
2077    }
2078
2079    /// Build a minimal `OAuthState` over dummy RPC clients (LazyUdsTransport at
2080    /// /dev/null — never opened) and a recording refresh-token store.
2081    async fn freeze_test_state(store: Arc<RecordingTokenStore>) -> Arc<OAuthState> {
2082        use crate::config::OAuthConfig;
2083        use hyprstream_rpc::rpc_client::RpcClientImpl;
2084        use hyprstream_rpc::signer::LocalSigner;
2085        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
2086        use hyprstream_rpc_std::discovery_client::DiscoveryClient;
2087        use hyprstream_rpc_std::policy_client::PolicyClient;
2088
2089        let key = ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]);
2090        let vk = ed25519_dalek::SigningKey::from_bytes(&[0x73; 32]).verifying_key();
2091        let dummy = std::path::PathBuf::from("/dev/null/freeze-test.sock");
2092        let mk_client = || {
2093            Arc::new(
2094                RpcClientImpl::new(
2095                    LocalSigner::new(key.clone()),
2096                    LazyUdsTransport::new(dummy.clone()),
2097                    Some(vk),
2098                )
2099                .with_response_verify_policy(hyprstream_rpc::crypto::CryptoPolicy::Classical),
2100            )
2101        };
2102        let mut state = OAuthState::new(
2103            &OAuthConfig::default(),
2104            PolicyClient::new(mk_client()),
2105            DiscoveryClient::new(mk_client()),
2106            [0x76; 32],
2107        );
2108        state.with_token_store_impl(
2109            store as Arc<dyn crate::services::oauth::token_store::TokenStore>,
2110        );
2111        Arc::new(state)
2112    }
2113
2114    /// The central mint guard: a path-form subject is rejected with
2115    /// `invalid_grant` and no rotated refresh token is persisted.
2116    #[tokio::test]
2117    async fn path_form_subject_rejected_at_mint_boundary_without_rotation() {
2118        let store = RecordingTokenStore::new();
2119        let state = freeze_test_state(Arc::clone(&store)).await;
2120
2121        let resp = issue_token_with_refresh(
2122            &state,
2123            "client-1",
2124            vec!["openid".to_owned()],
2125            None,
2126            "did:web:accounts.example:users:alice", // path-form — frozen under #1159
2127            None,
2128            false,
2129            None,
2130            None,
2131            None,
2132            None,
2133            None,
2134        )
2135        .await;
2136
2137        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2138        let body = axum::body::to_bytes(resp.into_body(), 4096).await.unwrap();
2139        let v: serde_json::Value = serde_json::from_slice(&body).unwrap();
2140        assert_eq!(v["error"].as_str(), Some("invalid_grant"));
2141        assert!(
2142            v["error_description"]
2143                .as_str()
2144                .unwrap()
2145                .contains("frozen path-form did:web"),
2146            "body was: {v}",
2147        );
2148        assert_eq!(
2149            store.put_count(),
2150            0,
2151            "guard must return before persisting a rotated refresh token",
2152        );
2153    }
2154
2155    /// End-to-end refresh regression: a pre-upgrade refresh token whose stored
2156    /// subject is path-form is consumed (taken) on refresh but NOT rotated —
2157    /// no access token is minted and no replacement refresh token is written,
2158    /// so the chain dies here rather than rotating indefinitely.
2159    #[tokio::test]
2160    async fn pre_upgrade_path_form_refresh_token_is_consumed_not_rotated() {
2161        let store = RecordingTokenStore::new();
2162        let state = freeze_test_state(Arc::clone(&store)).await;
2163
2164        // Seed a pre-upgrade refresh token carrying a path-form subject, exactly
2165        // as a `didweb`-configured deployment would have persisted before #1159.
2166        let path_form_entry = RefreshTokenEntry {
2167            client_id: "client-1".to_owned(),
2168            username: "did:web:accounts.example:users:alice".to_owned(),
2169            scopes: vec!["openid".to_owned()],
2170            resource: None,
2171            expires_at_unix: chrono::Utc::now().timestamp() + 3600,
2172            verifying_key_bytes: None,
2173            dpop_jkt: None,
2174            client_assertion_jkt: None,
2175            ucan_grant: None,
2176            session_id: None,
2177        };
2178        state
2179            .put_refresh_token("legacy-refresh", &path_form_entry, 3600)
2180            .await
2181            .unwrap();
2182        assert_eq!(store.put_count(), 1, "seeding writes one entry");
2183
2184        let params = TokenRequest {
2185            grant_type: "refresh_token".to_owned(),
2186            refresh_token: Some("legacy-refresh".to_owned()),
2187            client_id: "client-1".to_owned(),
2188            code: None,
2189            redirect_uri: None,
2190            code_verifier: None,
2191            device_code: None,
2192            assertion: None,
2193            client_assertion: None,
2194            client_assertion_type: None,
2195            subject_token: None,
2196            subject_token_type: None,
2197            requested_token_type: None,
2198            actor_token: None,
2199            actor_token_type: None,
2200            scope: None,
2201            audience: None,
2202            tenant: None,
2203            resource: None,
2204        };
2205        let resp = exchange_refresh_token(Arc::clone(&state), params, None, None, None).await;
2206
2207        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2208        let body = axum::body::to_bytes(resp.into_body(), 4096).await.unwrap();
2209        let v: serde_json::Value = serde_json::from_slice(&body).unwrap();
2210        assert_eq!(v["error"].as_str(), Some("invalid_grant"));
2211        assert!(v["error_description"].as_str().unwrap().contains("frozen"));
2212
2213        // No rotated refresh token was persisted (put_count still equals the
2214        // single seed write), and the legacy token is gone (taken on refresh) —
2215        // the chain is dead, not extended.
2216        assert_eq!(
2217            store.put_count(),
2218            1,
2219            "refresh must not persist a rotated refresh token for a path-form subject",
2220        );
2221        assert!(
2222            state
2223                .get_refresh_token("legacy-refresh")
2224                .await
2225                .unwrap()
2226                .is_none(),
2227            "the path-form refresh token must be consumed (taken), not left reusable",
2228        );
2229    }
2230
2231    #[tokio::test]
2232    async fn missing_hosted_binding_does_not_consume_refresh_token() {
2233        let store = RecordingTokenStore::new();
2234        let state = freeze_test_state(Arc::clone(&store)).await;
2235        let entry = RefreshTokenEntry {
2236            client_id: "client-1".to_owned(),
2237            username: "alice".to_owned(),
2238            scopes: vec!["openid".to_owned()],
2239            resource: None,
2240            expires_at_unix: chrono::Utc::now().timestamp() + 3600,
2241            verifying_key_bytes: None,
2242            dpop_jkt: None,
2243            client_assertion_jkt: None,
2244            ucan_grant: None,
2245            session_id: None,
2246        };
2247        state
2248            .put_refresh_token("repairable-refresh", &entry, 3600)
2249            .await
2250            .unwrap();
2251
2252        let params = TokenRequest {
2253            grant_type: "refresh_token".to_owned(),
2254            refresh_token: Some("repairable-refresh".to_owned()),
2255            client_id: entry.client_id,
2256            code: None,
2257            redirect_uri: None,
2258            code_verifier: None,
2259            device_code: None,
2260            assertion: None,
2261            client_assertion: None,
2262            client_assertion_type: None,
2263            subject_token: None,
2264            subject_token_type: None,
2265            requested_token_type: None,
2266            actor_token: None,
2267            actor_token_type: None,
2268            scope: None,
2269            audience: None,
2270            tenant: None,
2271            resource: None,
2272        };
2273        let response = exchange_refresh_token(Arc::clone(&state), params, None, None, None).await;
2274
2275        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
2276        assert!(
2277            state
2278                .get_refresh_token("repairable-refresh")
2279                .await
2280                .unwrap()
2281                .is_some(),
2282            "an operator-repairable hosted binding failure must not consume the session"
2283        );
2284    }
2285
2286    #[tokio::test]
2287    async fn pre_upgrade_path_form_ucan_refresh_is_consumed_not_reminted() {
2288        let store = RecordingTokenStore::new();
2289        let state = freeze_test_state(Arc::clone(&store)).await;
2290        let path_form_entry = RefreshTokenEntry {
2291            client_id: "ucan-grant:did:web:accounts.example:users:alice".to_owned(),
2292            username: "did:web:accounts.example:users:alice".to_owned(),
2293            scopes: vec!["urn:hyprstream:grant-type:ucan".to_owned()],
2294            resource: None,
2295            expires_at_unix: chrono::Utc::now().timestamp() + 3600,
2296            verifying_key_bytes: None,
2297            dpop_jkt: None,
2298            client_assertion_jkt: None,
2299            ucan_grant: Some(crate::services::oauth::state::UcanGrantRefresh {
2300                grant_cbor_b64: "not-reached".to_owned(),
2301                grant_cid: "not-reached".to_owned(),
2302                requested_scope: Some("read:model:demo".to_owned()),
2303                audience: None,
2304            }),
2305            session_id: None,
2306        };
2307        state
2308            .put_refresh_token("legacy-ucan-refresh", &path_form_entry, 3600)
2309            .await
2310            .unwrap();
2311
2312        let params = TokenRequest {
2313            grant_type: "refresh_token".to_owned(),
2314            refresh_token: Some("legacy-ucan-refresh".to_owned()),
2315            client_id: path_form_entry.client_id.clone(),
2316            code: None,
2317            redirect_uri: None,
2318            code_verifier: None,
2319            device_code: None,
2320            assertion: None,
2321            client_assertion: None,
2322            client_assertion_type: None,
2323            subject_token: None,
2324            subject_token_type: None,
2325            requested_token_type: None,
2326            actor_token: None,
2327            actor_token_type: None,
2328            scope: None,
2329            audience: None,
2330            tenant: None,
2331            resource: None,
2332        };
2333        let resp = exchange_refresh_token(state.clone(), params, None, None, None).await;
2334
2335        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2336        let body = axum::body::to_bytes(resp.into_body(), 4096).await.unwrap();
2337        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2338        assert_eq!(value["error"].as_str(), Some("invalid_grant"));
2339        assert!(value["error_description"]
2340            .as_str()
2341            .unwrap()
2342            .contains("frozen"));
2343        assert_eq!(
2344            store.put_count(),
2345            1,
2346            "UCAN refresh must not persist a replacement"
2347        );
2348        assert!(
2349            state
2350                .get_refresh_token("legacy-ucan-refresh")
2351                .await
2352                .unwrap()
2353                .is_none(),
2354            "the legacy UCAN refresh must be consumed, not left reusable",
2355        );
2356    }
2357}