Skip to main content

hyprstream_core/services/oauth/
token_exchange.rs

1//! RFC 8693 OAuth Token Exchange grant handler.
2//!
3//! Grant type: `urn:ietf:params:oauth:grant-type:token-exchange`
4//!
5//! Exchanges an existing credential (OIDC ID token, at+jwt, or WIT) for a
6//! hyprstream at+jwt. Serves as the HTTP-layer complement to ExchangeWit (ZMQ)
7//! and enables the MCP SDK's CrossAppAccessProvider enterprise flow.
8
9use std::sync::Arc;
10
11use axum::{
12    extract::State,
13    http::{header, HeaderMap, StatusCode},
14    response::{IntoResponse, Response},
15    Json,
16};
17use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
18use serde::Deserialize;
19use sha2::{Digest, Sha256};
20use subtle::ConstantTimeEq as _;
21
22use super::state::{DpopJtiAdmission, OAuthState};
23use crate::mac::exchange::{GrantDecision, GrantError, GrantRequest, GrantedAccess};
24use hyprstream_pds::repo_authority::is_path_form_did_web;
25use hyprstream_rpc_std::policy_client::{IssueToken, IssueTokenProfile};
26// #1425: the browser RFC 8693 sender-bound contract. The public client_id is
27// the single source of truth shared with the WASM client (`hyprstream-rpc`),
28// so the wire contract cannot drift between client and server.
29use hyprstream_rpc::wasm_token_exchange::BROWSER_PUBLIC_CLIENT_ID;
30
31const TOKEN_TYPE_ID_TOKEN: &str = "urn:ietf:params:oauth:token-type:id_token";
32const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token";
33const TOKEN_TYPE_JWT: &str = "urn:ietf:params:oauth:token-type:jwt";
34const ISSUED_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
35pub const ATPROTO_EXCHANGE_NSID: &str = "ai.hyprstream.identity.exchangeUcan";
36pub const ATPROTO_SESSION_EXCHANGE_NSID: &str = "ai.hyprstream.identity.exchangeSession";
37pub(super) const MAX_ATPROTO_SERVICE_TOKEN_LIFETIME: i64 = 3600;
38pub(super) const MAX_ATPROTO_EXCHANGE_TOKEN_TTL: u32 = 300;
39
40pub(super) struct VerifiedSubject {
41    pub(super) sub: String,
42    cnf_key_bytes: Option<[u8; 32]>,
43    /// RFC 9449 `cnf.jkt` sender-binding thumbprint on the subject token, when
44    /// present. A DPoP-bound access-token subject MUST be exchanged under a
45    /// token-endpoint proof from the **same** key (#1425 P1: the subject
46    /// token's sender constraint must be preserved, not re-bound to an
47    /// attacker's key).
48    cnf_jkt: Option<String>,
49    iat: i64,
50    /// Authority from a locally validated OAuth access-token grant. Identity
51    /// tokens and generic JWTs do not carry a server-authorized OAuth grant.
52    granted_scopes: Option<Vec<String>>,
53    pub(super) verified_tenant: Option<String>,
54    pub(super) atproto_replay: Option<(String, String, i64)>,
55    require_clearance: bool,
56    ttl_ceiling: Option<u32>,
57}
58
59/// POST /oauth/token — token-exchange grant (RFC 8693).
60pub async fn exchange_token_exchange(
61    state: &Arc<OAuthState>,
62    subject_token: &str,
63    subject_token_type: &str,
64    audience: Option<&str>,
65    scope: Option<&str>,
66    actor_token: Option<&str>,
67    output_dpop_proof: Option<super::dpop::DpopProof>,
68    requested_token_type: Option<&str>,
69    tenant: Option<&str>,
70    client_id: &str,
71) -> Response {
72    // Actor token (delegation) is deferred — RFC 8693 §4.
73    if actor_token.is_some() {
74        return tx_error(
75            StatusCode::BAD_REQUEST,
76            "invalid_request",
77            "actor_token is not supported",
78        );
79    }
80
81    // Only access_token is supported as the requested output type.
82    if let Some(rt) = requested_token_type {
83        if rt != ISSUED_TOKEN_TYPE {
84            return tx_error(
85                StatusCode::BAD_REQUEST,
86                "invalid_target",
87                "only urn:ietf:params:oauth:token-type:access_token is supported as requested_token_type",
88            );
89        }
90    }
91
92    let verified = match subject_token_type {
93        TOKEN_TYPE_ID_TOKEN => verify_id_token(state, subject_token).await,
94        TOKEN_TYPE_ACCESS_TOKEN => verify_access_token(state, subject_token).await,
95        TOKEN_TYPE_JWT => verify_jwt(state, subject_token).await,
96        _ => return tx_error(
97            StatusCode::BAD_REQUEST,
98            "invalid_request",
99            &format!("unsupported subject_token_type: {subject_token_type}; supported: id_token, access_token, jwt"),
100        ),
101    };
102
103    let verified = match verified {
104        Ok(v) => v,
105        Err(e) => return tx_error(StatusCode::UNAUTHORIZED, "invalid_grant", &e),
106    };
107
108    let requested_scopes = match attenuate_exchange_scopes(&verified, scope) {
109        Ok(scopes) => scopes,
110        Err(description) => {
111            return tx_error(StatusCode::BAD_REQUEST, "invalid_scope", description);
112        }
113    };
114
115    let tenant = match exchange_tenant(&verified, tenant) {
116        Ok(tenant) => tenant,
117        Err(description) => {
118            return tx_error(StatusCode::BAD_REQUEST, "invalid_target", description);
119        }
120    };
121
122    // The PolicyService check remains the shared signing boundary for every
123    // RPC issuer; this gives RFC 8693 callers a concrete OAuth error before a
124    // legacy subject can reach that RPC boundary.
125    if is_path_form_did_web(&verified.sub) {
126        return tx_error(
127            StatusCode::BAD_REQUEST,
128            "invalid_grant",
129            "path-form did:web account subjects are frozen; host-form account minting is not available yet (#1159)",
130        );
131    }
132    let subject_identity = crate::server::middleware::AuthenticatedUser {
133        user: verified.sub.clone(),
134        verified_tenant: tenant.clone(),
135        token: None,
136        exp: None,
137    };
138    if subject_identity.authorization_domain().is_err() {
139        return tx_error(
140            StatusCode::UNAUTHORIZED,
141            "invalid_grant",
142            "subject token has no valid verified hosted-account tenant binding",
143        );
144    }
145
146    // A sender-constrained subject cannot be exchanged for a bearer token or
147    // rebound to a different DPoP key. Check before consuming the subject's
148    // replay entry so an invalid attempt cannot burn a legitimate exchange.
149    if let Some(subject_jkt) = verified.cnf_jkt.as_deref() {
150        let matches = output_dpop_proof.as_ref().is_some_and(|presented| {
151            subject_jkt
152                .as_bytes()
153                .ct_eq(presented.jkt.as_bytes())
154                .into()
155        });
156        if !matches {
157            return tx_error(
158                StatusCode::BAD_REQUEST,
159                "invalid_dpop_proof",
160                "DPoP proof key must match the subject token's sender binding",
161            );
162        }
163    }
164
165    // Both the generic token endpoint and XRPC verify the endpoint-specific
166    // proof before reaching this shared handler. Admit its JTI only after the
167    // request and subject binding are valid, and before consuming the subject.
168    if let Some(proof) = output_dpop_proof.as_ref() {
169        if !state
170            .check_and_record_dpop_jti_admission(&proof.jti, proof.iat)
171            .is_inserted()
172        {
173            return tx_error(
174                StatusCode::BAD_REQUEST,
175                "invalid_dpop_proof",
176                "DPoP proof rejected",
177            );
178        }
179    }
180
181    let fresh = if let Some((issuer, jti, exp)) = verified.atproto_replay.as_ref() {
182        state.check_and_record_atproto_service_jti(issuer, jti, *exp)
183    } else {
184        let token_hash = URL_SAFE_NO_PAD.encode(Sha256::digest(subject_token.as_bytes()));
185        state.check_and_record_dpop_jti(&token_hash, verified.iat)
186    };
187    if !fresh {
188        return tx_error(
189            StatusCode::BAD_REQUEST,
190            "invalid_grant",
191            "subject_token already used (replay)",
192        );
193    }
194
195    // Service assertions carry the exact key which verified their signature.
196    let user_pub_key = verified.cnf_key_bytes.map(|b| URL_SAFE_NO_PAD.encode(b));
197    let output_issuer = state.issuer_for_scopes(requested_scopes.as_deref().unwrap_or_default());
198    let output_dpop_bound = output_dpop_proof.is_some();
199    let output_dpop_jkt = output_dpop_proof.map(|proof| proof.jkt);
200
201    let result = state
202        .policy_client
203        .issue_token(&IssueToken {
204            requested_scopes,
205            ttl: Some(
206                state
207                    .token_ttl
208                    .min(verified.ttl_ceiling.unwrap_or(state.token_ttl)),
209            ),
210            audience: audience.map(str::to_owned),
211            subject: Some(verified.sub.clone()),
212            user_pub_key,
213            dpop_jkt: output_dpop_jkt,
214            // RFC 8693/XRPC credentials cross a network boundary. They must
215            // never inherit the PolicyService's empty-issuer local-IPC profile.
216            issuer: Some(output_issuer),
217            tenant,
218            require_clearance: verified.require_clearance,
219            session_id: None,
220            issuance_profile: if verified.sub.starts_with("service:") {
221                IssueTokenProfile::Service
222            } else {
223                IssueTokenProfile::Rfc8693
224            },
225            // RFC 9068 §2.2.1: the exchanging OAuth client on the user
226            // `at+jwt`; the service (`wit+jwt`) form carries none.
227            client_id: (!verified.sub.starts_with("service:")).then(|| client_id.to_owned()),
228        })
229        .await;
230
231    match result {
232        Ok(token_info) => {
233            let now = chrono::Utc::now().timestamp();
234            let expires_in = (token_info.expires_at - now).max(0);
235            tracing::info!(sub = %verified.sub, "Token exchange issued at+jwt");
236            (
237                StatusCode::OK,
238                [
239                    (header::CACHE_CONTROL, "no-store"),
240                    (header::PRAGMA, "no-cache"),
241                ],
242                Json(serde_json::json!({
243                    "access_token": token_info.token,
244                    "issued_token_type": ISSUED_TOKEN_TYPE,
245                    "token_type": super::token::access_token_type(output_dpop_bound),
246                    "expires_in": expires_in,
247                })),
248            )
249                .into_response()
250        }
251        Err(e) => {
252            tracing::error!(sub = %verified.sub, error = %e, "Token exchange issuance failed");
253            tx_error(
254                StatusCode::INTERNAL_SERVER_ERROR,
255                "server_error",
256                "Failed to issue token",
257            )
258        }
259    }
260}
261
262/// The canonical Hyprstream RPC service resource/audience the browser
263/// sender-bound exchange mints for: the AS origin (`issuer` without path).
264/// The browser presents the exchanged token back to RPC services on this
265/// origin, so the mint is restricted to exactly it (#1425 audience/resource
266/// restriction). Any caller-supplied `audience` MUST match this value —
267/// substitution is rejected as `invalid_target`.
268fn browser_exchange_audience(state: &OAuthState) -> String {
269    state.atproto_issuer_url()
270}
271
272/// POST /oauth/token — the **browser** RFC 8693 token-exchange grant composed
273/// with RFC 9449 DPoP (#1425).
274///
275/// This is the sender-bound contract the WASM `VfsShell` uses: it exchanges an
276/// atproto/external subject token for a short-lived at+jwt access token that is
277/// **bound to the browser's DPoP key** (`cnf.jkt`) and **audience-restricted**
278/// to the Hyprstream RPC service. It is distinct from the generic
279/// [`exchange_token_exchange`] (bearer, optional DPoP) and the UCAN grant path.
280///
281/// **Public client rule (RFC 9700):** `client_id` is the well-known public
282/// browser client ([`BROWSER_PUBLIC_CLIENT_ID`]) — it identifies the browser
283/// client and is **not a client secret and not a proof of identity**. There is
284/// no secret; the sender binding comes entirely from the verified DPoP proof.
285///
286/// **Sender binding (RFC 9449):** a fresh DPoP proof is **mandatory** at the
287/// token endpoint. The proof's method (`POST`), URI (`{issuer}/oauth/token`),
288/// `iat`, `jti` (single-use, replay-rejected), and server-issued nonce are all
289/// verified here; the proof key's `jkt` becomes the minted token's `cnf.jkt`,
290/// and the response carries `token_type: DPoP`. The resource layer
291/// (`auth.rs`) then refuses to accept the token as a plain Bearer and requires
292/// a matching proof + `ath` on every use, so the binding is enforced end to
293/// end — a stolen DPoP-bound token is unusable without the key.
294///
295/// **Audience/resource restriction:** the issued token targets
296/// [`browser_exchange_audience`] (the AS origin / RPC service resource). A
297/// caller-supplied `audience` that differs is rejected (`invalid_target`).
298///
299/// **Access-token only:** no refresh token is issued (RFC 8693 browser/public
300/// client rotation is a separately reviewed, metadata-advertised policy).
301///
302/// **Assurance boundary:** this composes Classical browser authentication
303/// (Ed25519/ES256 DPoP) with RFC 8693/9449. It does **not** claim `PqHybrid`
304/// identity assurance; hybrid RPC transport signing is independent of this
305/// Classical sender binding.
306pub(super) async fn exchange_browser_token_exchange(
307    state: &Arc<OAuthState>,
308    subject_token: &str,
309    subject_token_type: &str,
310    dpop_header: Option<&str>,
311    audience: Option<&str>,
312    resource: Option<&str>,
313    scope: Option<&str>,
314    requested_token_type: Option<&str>,
315    actor_token: Option<&str>,
316    actor_token_type: Option<&str>,
317    tenant: Option<&str>,
318    client_id: &str,
319) -> Response {
320    // Public client rule: the browser client_id is a public identifier. It is
321    // not authenticated here — there is no secret. The routing in `token.rs`
322    // only reaches this handler for the well-known browser client, so a
323    // mismatch is a contract violation, not an auth failure.
324    if client_id != BROWSER_PUBLIC_CLIENT_ID {
325        return tx_error(
326            StatusCode::BAD_REQUEST,
327            "invalid_request",
328            "browser token-exchange requires the public browser client_id",
329        );
330    }
331
332    // ── P2: Explicitly reject RFC 8693 fields this contract does not support ──
333    // The browser exchange is a leaf path, not a general-purpose delegation
334    // flow. Fields that are silently ignored in the generic handler MUST be
335    // explicitly rejected here so there is no second, ambiguous interpretation.
336    if actor_token.is_some() {
337        return tx_error(
338            StatusCode::BAD_REQUEST,
339            "invalid_request",
340            "actor_token (delegation) is not supported for browser token-exchange",
341        );
342    }
343    // #1425 r2 P2: `actor_token_type` is rejected independently of
344    // `actor_token` — a request naming the type but omitting the token (or
345    // sending only the type) must not be treated as if it carried no actor
346    // field at all. Checked here, before proof admission or subject-token
347    // consumption, so neither the DPoP replay registry nor the subject-token
348    // single-use registry is ever touched by a request this contract refuses.
349    if actor_token_type.is_some() {
350        return tx_error(
351            StatusCode::BAD_REQUEST,
352            "invalid_request",
353            "actor_token_type is not supported for browser token-exchange",
354        );
355    }
356    if let Some(rtt) = requested_token_type {
357        if rtt != ISSUED_TOKEN_TYPE {
358            return tx_error(
359                StatusCode::BAD_REQUEST,
360                "invalid_target",
361                "browser token-exchange issues access_token only",
362            );
363        }
364    }
365    if tenant.is_some() {
366        return tx_error(
367            StatusCode::BAD_REQUEST,
368            "invalid_request",
369            "tenant is not a browser token-exchange parameter (authority is resolved from the subject token)",
370        );
371    }
372
373    // ── P2: Audience/resource restriction (#1425) ────────────────────────────
374    // Checked before DPoP verification and subject-token consumption so a
375    // malformed request fails fast. The browser token targets the Hyprstream
376    // RPC service resource (the canonical AS origin the metadata advertises).
377    // RFC 8707 `resource` and RFC 8693 `audience` both scope the issued token;
378    // for this contract they MUST both equal (or be omitted, defaulting to)
379    // the RPC service origin.
380    let rpc_resource = browser_exchange_audience(state);
381    for requested in [audience, resource].into_iter().flatten() {
382        if requested != rpc_resource {
383            return tx_error(
384                StatusCode::BAD_REQUEST,
385                "invalid_target",
386                "browser exchange audience/resource must be the Hyprstream RPC service resource",
387            );
388        }
389    }
390
391    // ── 1. Mandatory DPoP proof (RFC 9449 sender binding) ───────────────────
392    let Some(proof_str) = dpop_header else {
393        return tx_error(
394            StatusCode::BAD_REQUEST,
395            "invalid_request",
396            "browser token-exchange requires a DPoP proof (sender-binding)",
397        );
398    };
399    // The DPoP htu is the canonical token endpoint the AS advertises
400    // (`{origin}/oauth/token`), matching the browser's absolute request URI
401    // and the RFC 8414 `token_endpoint` value — not the possibly path-bearing
402    // configured `issuer_url`.
403    let token_endpoint = format!("{}/oauth/token", state.atproto_issuer_url());
404    let proof = match super::dpop::verify_dpop_proof(proof_str, "POST", &token_endpoint, None) {
405        Ok(p) => p,
406        Err(error) => {
407            tracing::warn!(%error, "browser exchange rejected invalid DPoP proof");
408            return tx_error(
409                StatusCode::BAD_REQUEST,
410                "invalid_dpop_proof",
411                "DPoP proof verification failed",
412            );
413        }
414    };
415    // Single-use jti: a replayed proof is rejected (RFC 9449 §6.1).
416    let admission = state.check_and_record_dpop_jti_admission(&proof.jti, proof.iat);
417    if !admission.is_inserted() {
418        if admission == DpopJtiAdmission::Duplicate {
419            tracing::debug!("browser exchange: DPoP JTI replay rejected");
420        }
421        return tx_error(
422            StatusCode::BAD_REQUEST,
423            "invalid_dpop_proof",
424            "DPoP proof rejected",
425        );
426    }
427    // Server-nonce policy (RFC 9449 §8): once a key has been issued a nonce,
428    // every subsequent proof MUST carry a valid server nonce. A bootstrap
429    // (first proof from this jkt) is accepted and a fresh nonce is issued in
430    // the success response.
431    let client_needs_nonce = state.dpop_client_requires_nonce(&proof.jkt).await;
432    let nonce_to_return: Option<String> = match (client_needs_nonce, proof.nonce.as_deref()) {
433        (true, None) => {
434            let fresh = state.issue_dpop_nonce().await;
435            state.mark_dpop_client_nonced(&proof.jkt).await;
436            tracing::warn!(jkt = %proof.jkt, "browser exchange: DPoP nonce required but omitted");
437            return dpop_nonce_tx_error(
438                &fresh,
439                "use_dpop_nonce",
440                "DPoP proof must include a server-issued nonce",
441            );
442        }
443        (_, Some(presented)) => {
444            if !state.verify_dpop_nonce(presented).await {
445                let fresh = state.issue_dpop_nonce().await;
446                state.mark_dpop_client_nonced(&proof.jkt).await;
447                tracing::warn!(jkt = %proof.jkt, "browser exchange: DPoP nonce invalid/expired");
448                return dpop_nonce_tx_error(
449                    &fresh,
450                    "use_dpop_nonce",
451                    "DPoP nonce invalid or expired",
452                );
453            }
454            None
455        }
456        (false, None) => {
457            // Bootstrap: accept; issue a fresh nonce on the success path.
458            Some(state.issue_dpop_nonce().await)
459        }
460    };
461
462    // ── 3. Verify the subject token ──────────────────────────────────────────
463    // P2: ID tokens are NOT accepted for the browser contract. `verify_id_token`
464    // validates no audience/client binding, so trusting an issuer alone is not
465    // sufficient to establish the token was minted for this browser client.
466    // The browser exchanges a `jwt` (atproto/external service assertion) or an
467    // `access_token` (subject to same-key cnf.jkt confirmation below).
468    let verified = match subject_token_type {
469        TOKEN_TYPE_ACCESS_TOKEN => verify_access_token(state, subject_token).await,
470        TOKEN_TYPE_JWT => verify_jwt(state, subject_token).await,
471        TOKEN_TYPE_ID_TOKEN => Err("id_token is not supported for browser token-exchange \
472             (no audience/client binding)"
473            .to_owned()),
474        _ => Err("unsupported subject_token_type for browser exchange; \
475             supported: access_token, jwt"
476            .to_owned()),
477    };
478    let verified = match verified {
479        Ok(v) => v,
480        Err(e) => return tx_error(StatusCode::UNAUTHORIZED, "invalid_grant", &e),
481    };
482
483    // ── 4. Scope + tenant + subject invariants (shared with the generic path) ──
484    let requested_scopes = match attenuate_exchange_scopes(&verified, scope) {
485        Ok(s) => s,
486        Err(description) => return tx_error(StatusCode::BAD_REQUEST, "invalid_scope", description),
487    };
488    let tenant = match exchange_tenant(&verified, None) {
489        Ok(t) => t,
490        Err(description) => {
491            return tx_error(StatusCode::BAD_REQUEST, "invalid_target", description)
492        }
493    };
494    // ── Subject-token sender-constraint preservation (#1425 P1) ──────────────
495    // A DPoP-bound subject access token (cnf.jkt present) MUST be exchanged
496    // under a token-endpoint proof from the **same** key. Without this check,
497    // a stolen sender-constrained token string can be re-bound to an
498    // attacker-owned key — defeating the source token's sender constraint.
499    // The one-use subject-token hash only makes this a race, not proof of
500    // possession. The check fires BEFORE the replay registry consumes the
501    // subject token so a mismatched key is rejected without burning it.
502    if let Some(ref subject_jkt) = verified.cnf_jkt {
503        if subject_jkt
504            .as_bytes()
505            .ct_eq(proof.jkt.as_bytes())
506            .unwrap_u8()
507            == 0
508        {
509            tracing::warn!(
510                sub = %verified.sub,
511                subject_cnf_jkt = %subject_jkt,
512                proof_jkt = %proof.jkt,
513                "browser exchange: DPoP proof key does not match the subject token's cnf.jkt"
514            );
515            return tx_error(
516                StatusCode::BAD_REQUEST,
517                "invalid_dpop_proof",
518                "DPoP proof key must match the subject token's sender binding (cnf.jkt)",
519            );
520        }
521    }
522    if is_path_form_did_web(&verified.sub) {
523        return tx_error(
524            StatusCode::BAD_REQUEST,
525            "invalid_grant",
526            "path-form did:web account subjects are frozen; \
527             host-form account minting is not available yet (#1159)",
528        );
529    }
530    let subject_identity = crate::server::middleware::AuthenticatedUser {
531        user: verified.sub.clone(),
532        verified_tenant: tenant.clone(),
533        token: None,
534        exp: None,
535    };
536    if subject_identity.authorization_domain().is_err() {
537        return tx_error(
538            StatusCode::UNAUTHORIZED,
539            "invalid_grant",
540            "subject token has no valid verified hosted-account tenant binding",
541        );
542    }
543    // Replay-protect the subject token exactly as the generic path does.
544    let fresh = if let Some((issuer, jti, exp)) = verified.atproto_replay.as_ref() {
545        state.check_and_record_atproto_service_jti(issuer, jti, *exp)
546    } else {
547        let token_hash = URL_SAFE_NO_PAD.encode(Sha256::digest(subject_token.as_bytes()));
548        state.check_and_record_dpop_jti(&token_hash, verified.iat)
549    };
550    if !fresh {
551        return tx_error(
552            StatusCode::BAD_REQUEST,
553            "invalid_grant",
554            "subject_token already used (replay)",
555        );
556    }
557
558    let requested_scopes_ref = requested_scopes.as_deref().unwrap_or_default();
559    let output_issuer = state.issuer_for_scopes(requested_scopes_ref);
560
561    // ── 5. Mint the sender-bound (cnf.jkt) access token via PolicyService ────
562    // `dpop_jkt = proof.jkt` is the cnf.jkt binding. No refresh token is
563    // issued (access-token only; rotation is a separately reviewed policy).
564    let result = state
565        .policy_client
566        .issue_token(&IssueToken {
567            requested_scopes,
568            ttl: Some(
569                state
570                    .token_ttl
571                    .min(verified.ttl_ceiling.unwrap_or(state.token_ttl)),
572            ),
573            audience: Some(rpc_resource),
574            subject: Some(verified.sub.clone()),
575            user_pub_key: None,
576            dpop_jkt: Some(proof.jkt.clone()),
577            // RFC 8693 credentials cross a network boundary; never inherit the
578            // PolicyService's empty-issuer local-IPC profile.
579            issuer: Some(output_issuer),
580            tenant,
581            require_clearance: verified.require_clearance,
582            session_id: None,
583            issuance_profile: if verified.sub.starts_with("service:") {
584                IssueTokenProfile::Service
585            } else {
586                IssueTokenProfile::Rfc8693
587            },
588            // RFC 9068 §2.2.1: the exchanging OAuth client on the user
589            // `at+jwt`; the service (`wit+jwt`) form carries none.
590            client_id: (!verified.sub.starts_with("service:")).then(|| client_id.to_owned()),
591        })
592        .await;
593
594    let token_info = match result {
595        Ok(ti) => ti,
596        Err(e) => {
597            tracing::error!(sub = %verified.sub, error = %e, "browser exchange issuance failed");
598            return tx_error(
599                StatusCode::INTERNAL_SERVER_ERROR,
600                "server_error",
601                "Failed to issue token",
602            );
603        }
604    };
605
606    // ── 6. DPoP response (access-token only) + fresh nonce for the next proof ─
607    let now = chrono::Utc::now().timestamp();
608    let expires_in = (token_info.expires_at - now).max(0);
609    // Mark this jkt as nonce-eligible so the next exchange/refresh proof from
610    // it is required to carry a server nonce.
611    state.mark_dpop_client_nonced(&proof.jkt).await;
612    let nonce = match nonce_to_return {
613        Some(n) => n,
614        None => state.issue_dpop_nonce().await,
615    };
616    tracing::info!(sub = %verified.sub, "Browser sender-bound token exchanged (cnf.jkt, DPoP)");
617    let mut resp = (
618        StatusCode::OK,
619        [
620            (header::CACHE_CONTROL, "no-store"),
621            (header::PRAGMA, "no-cache"),
622        ],
623        Json(serde_json::json!({
624            "access_token": token_info.token,
625            "issued_token_type": ISSUED_TOKEN_TYPE,
626            "token_type": "DPoP",
627            "expires_in": expires_in,
628        })),
629    )
630        .into_response();
631    if let Ok(val) = axum::http::HeaderValue::from_str(&nonce) {
632        resp.headers_mut().insert("DPoP-Nonce", val);
633    }
634    resp
635}
636
637/// Build a `400` OAuth error response that also carries a fresh `DPoP-Nonce`
638/// header (RFC 9449 §8 retry contract) for the browser exchange path.
639fn dpop_nonce_tx_error(nonce: &str, error: &str, description: &str) -> Response {
640    let mut resp = tx_error(StatusCode::BAD_REQUEST, error, description);
641    if let Ok(val) = axum::http::HeaderValue::from_str(nonce) {
642        resp.headers_mut().insert("DPoP-Nonce", val);
643    }
644    resp
645}
646
647/// Verify an OIDC ID token from a trusted issuer (CrossAppAccessProvider path).
648///
649/// `aud` is not strictly enforced — ID tokens target the OIDC client_id, not our
650/// token endpoint. Trust is established by the `iss` being in `trusted_issuers`.
651async fn verify_id_token(state: &Arc<OAuthState>, token: &str) -> Result<VerifiedSubject, String> {
652    let unverified = hyprstream_rpc::auth::decode_unverified(token)
653        .map_err(|e| format!("Cannot parse id_token: {e}"))?;
654
655    let iss = if unverified.iss.is_empty() {
656        return Err("id_token missing 'iss' claim".to_owned());
657    } else {
658        unverified.iss.clone()
659    };
660
661    let issuer_cfg = state
662        .trusted_issuers
663        .get(&iss)
664        .ok_or_else(|| format!("Issuer not in trusted_issuers allow-list: {iss}"))?
665        .clone();
666
667    check_nbf(token)?;
668
669    let vk = super::jwt_bearer::resolve_federated_key(state, &iss, token, issuer_cfg.allow_http)
670        .await
671        .map_err(|e| format!("JWKS key resolution failed for {iss}: {e}"))?;
672
673    // No audience check: ID token aud = OIDC client_id, not our token endpoint.
674    let claims = hyprstream_rpc::auth::decode_with_key(token, &vk, None)
675        .map_err(|e| format!("id_token signature verification failed: {e}"))?;
676
677    if claims.sub.is_empty() {
678        return Err("id_token missing 'sub' claim".to_owned());
679    }
680
681    Ok(VerifiedSubject {
682        sub: hyprstream_rpc::Subject::federated(&iss, &claims.sub)
683            .name()
684            .ok_or_else(|| "id_token subject is empty".to_owned())?
685            .to_owned(),
686        cnf_key_bytes: None, // ID tokens carry no key binding
687        cnf_jkt: None,
688        iat: claims.iat,
689        granted_scopes: None,
690        verified_tenant: None,
691        atproto_replay: None,
692        require_clearance: false,
693        ttl_ceiling: None,
694    })
695}
696
697/// The Federate TUI class is never a generic exchange subject (W1.3): the
698/// generic IssueToken path drops the class markers and the session binding
699/// and substitutes the request's client_id, laundering the class away. Deny
700/// the class by marker set OR the deployment's class pin at the local
701/// issuer.
702fn reject_federate_tui_exchange_subject(
703    claims: &hyprstream_rpc::auth::Claims,
704    local_issuer: &str,
705) -> Result<(), String> {
706    if claims.is_federate_tui_class(&[local_issuer]) {
707        return Err("federate TUI credentials are not exchangeable".to_owned());
708    }
709    Ok(())
710}
711
712/// Verify an existing hyprstream at+jwt through the same algorithm, audience,
713/// issuer, and revocation checks used by protected OAuth routes.
714async fn verify_access_token(state: &OAuthState, token: &str) -> Result<VerifiedSubject, String> {
715    let claims = super::auth::validate_oauth_access_token(state, token)
716        .await
717        .map_err(|e| format!("access_token verification failed: {e}"))?;
718
719    // The Federate TUI class is never a generic exchange subject (W1.3): the
720    // generic IssueToken path drops the class markers and the session
721    // binding and substitutes the request's client_id, which would launder
722    // the credential's class away. Deny the class here — by marker set or
723    // the deployment's class pin — so its only exchange surface remains the
724    // dedicated federate rail.
725    reject_federate_tui_exchange_subject(&claims, &state.issuer_url)?;
726
727    let granted_scopes = claims
728        .scope
729        .as_ref()
730        .map(|_| claims.granted_scopes().map(str::to_owned).collect());
731    let cnf_key_bytes = claims.cnf_key_bytes();
732    let cnf_jkt = claims.cnf_jkt().map(str::to_owned);
733    Ok(VerifiedSubject {
734        sub: claims.sub,
735        cnf_key_bytes,
736        cnf_jkt,
737        iat: claims.iat,
738        granted_scopes,
739        verified_tenant: claims.tenant,
740        atproto_replay: None,
741        require_clearance: false,
742        ttl_ceiling: None,
743    })
744}
745
746/// Verify a generic JWT — WIT from local trust store or federated OIDC issuer.
747///
748/// For `sub: service:*`: global trust store (CA-signed WIT).
749/// For other subjects: issuer must be in `trusted_issuers`.
750/// Audience must equal the token endpoint URL (same constraint as RFC 7523).
751async fn verify_jwt(state: &Arc<OAuthState>, token: &str) -> Result<VerifiedSubject, String> {
752    let issuer_hint = token
753        .split('.')
754        .nth(1)
755        .and_then(|payload| URL_SAFE_NO_PAD.decode(payload).ok())
756        .and_then(|payload| serde_json::from_slice::<serde_json::Value>(&payload).ok())
757        .and_then(|payload| {
758            payload
759                .get("iss")
760                .and_then(serde_json::Value::as_str)
761                .map(str::to_owned)
762        });
763    if issuer_hint
764        .as_deref()
765        .is_some_and(|issuer| issuer.starts_with("did:plc:") || issuer.starts_with("did:web:"))
766    {
767        return verify_atproto_service_jwt(state, token, ATPROTO_EXCHANGE_NSID).await;
768    }
769
770    let unverified = hyprstream_rpc::auth::decode_unverified(token)
771        .map_err(|e| format!("Cannot parse jwt: {e}"))?;
772
773    let iss = if unverified.iss.is_empty() {
774        return Err("jwt missing 'iss' claim".to_owned());
775    } else {
776        unverified.iss.clone()
777    };
778
779    let sub = unverified.sub.clone();
780    check_nbf(token)?;
781
782    let token_endpoint = format!("{}/oauth/token", state.issuer_url.trim_end_matches('/'));
783
784    let (claims, service_signing_key) = if sub.starts_with("service:") {
785        let svc_name = sub.trim_start_matches("service:");
786        let (claims, vk) =
787            super::jwt_bearer::decode_with_any_local_service_key(token, svc_name, &token_endpoint)
788                .ok_or_else(|| format!("JWT verification failed for service: {svc_name}"))?;
789        (claims, Some(vk.to_bytes()))
790    } else {
791        let cfg = state
792            .trusted_issuers
793            .get(&iss)
794            .ok_or_else(|| format!("Issuer not in trusted_issuers allow-list: {iss}"))?
795            .clone();
796        let vk = super::jwt_bearer::resolve_federated_key(state, &iss, token, cfg.allow_http)
797            .await
798            .map_err(|e| format!("JWKS key resolution failed for {iss}: {e}"))?;
799        let claims = hyprstream_rpc::auth::decode_with_key(token, &vk, Some(&token_endpoint))
800            .map_err(|e| format!("JWT verification failed: {e}"))?;
801        (claims, None)
802    };
803
804    let mut claims = claims;
805    let atproto_issuer = state.atproto_issuer_url();
806    let local_issuers = [atproto_issuer.as_str(), state.issuer_url.as_str()];
807    claims.strip_federated_tenant(&local_issuers);
808    let subject = claims.subject(&local_issuers);
809    subject
810        .validate()
811        .map_err(|error| format!("invalid JWT subject: {error}"))?;
812    let cnf_key_bytes = service_signing_key.or_else(|| claims.cnf_key_bytes());
813    Ok(VerifiedSubject {
814        sub: subject
815            .name()
816            .ok_or_else(|| "JWT subject is empty".to_owned())?
817            .to_owned(),
818        cnf_key_bytes,
819        cnf_jkt: claims.cnf_jkt().map(str::to_owned),
820        iat: claims.iat,
821        granted_scopes: None,
822        verified_tenant: claims.tenant,
823        atproto_replay: None,
824        require_clearance: false,
825        ttl_ceiling: None,
826    })
827}
828
829#[derive(Deserialize)]
830struct AtprotoJwtHeader {
831    alg: String,
832    #[serde(default)]
833    typ: Option<String>,
834    #[serde(default)]
835    kid: Option<String>,
836}
837
838#[derive(Deserialize)]
839struct AtprotoServiceClaims {
840    iss: String,
841    aud: String,
842    exp: i64,
843    iat: i64,
844    lxm: String,
845    jti: String,
846}
847
848pub(super) async fn verify_atproto_service_jwt(
849    state: &Arc<OAuthState>,
850    token: &str,
851    expected_lxm: &str,
852) -> Result<VerifiedSubject, String> {
853    let parts: Vec<&str> = token.split('.').collect();
854    if parts.len() != 3 || parts.iter().any(|part| part.is_empty()) {
855        return Err("ATProto service JWT must contain exactly three segments".to_owned());
856    }
857    let header: AtprotoJwtHeader = decode_jwt_json(parts[0], "header")?;
858    let claims: AtprotoServiceClaims = decode_jwt_json(parts[1], "claims")?;
859    if !matches!(header.alg.as_str(), "ES256" | "ES256K") {
860        return Err("ATProto service JWT alg must be ES256 or ES256K".to_owned());
861    }
862    if header
863        .typ
864        .as_deref()
865        .is_some_and(|typ| !typ.eq_ignore_ascii_case("JWT"))
866    {
867        return Err("ATProto service JWT typ must be JWT when present".to_owned());
868    }
869    super::state::subject_did_for(&state.issuer_url, &claims.iss)
870        .map_err(|error| format!("invalid ATProto issuer DID: {error}"))?;
871    let expected_audience = state
872        .atproto_service_did()
873        .ok_or_else(|| "OAuth issuer cannot be represented as a host service DID".to_owned())?;
874    if claims.aud != expected_audience {
875        return Err(format!(
876            "ATProto service JWT aud must equal host DID {expected_audience}"
877        ));
878    }
879    if claims.lxm != expected_lxm {
880        return Err(format!("ATProto service JWT lxm must equal {expected_lxm}"));
881    }
882    let now = chrono::Utc::now().timestamp();
883    if claims.exp <= now {
884        return Err("ATProto service JWT is expired".to_owned());
885    }
886    if claims.iat > now.saturating_add(5) || claims.exp <= claims.iat {
887        return Err("ATProto service JWT has an invalid iat/exp interval".to_owned());
888    }
889    let _lifetime = claims
890        .exp
891        .checked_sub(claims.iat)
892        .filter(|lifetime| *lifetime > 0 && *lifetime <= MAX_ATPROTO_SERVICE_TOKEN_LIFETIME)
893        .ok_or_else(|| "ATProto service JWT has an invalid iat/exp interval".to_owned())?;
894    if claims.jti.is_empty() || claims.jti.len() > 256 {
895        return Err("ATProto service JWT jti must be 1..=256 bytes".to_owned());
896    }
897
898    let document = state
899        .atproto_did_resolver
900        .resolve_document(&claims.iss)
901        .await
902        .map_err(|error| format!("ATProto DID resolution failed: {error}"))?;
903    let fragment = header.kid.as_deref().unwrap_or("#atproto");
904    let key_id = if fragment.starts_with('#') {
905        format!("{}{fragment}", claims.iss)
906    } else {
907        fragment.to_owned()
908    };
909    if !key_id.starts_with(&format!("{}#", claims.iss)) {
910        return Err("ATProto signing kid must be a fragment of the issuer DID".to_owned());
911    }
912    let methods = document
913        .get("verificationMethod")
914        .and_then(serde_json::Value::as_array)
915        .ok_or_else(|| "ATProto DID document has no verificationMethod array".to_owned())?;
916    let mut matches = methods.iter().filter(|method| {
917        method.get("id").and_then(serde_json::Value::as_str) == Some(key_id.as_str())
918    });
919    let method = matches
920        .next()
921        .ok_or_else(|| format!("ATProto signing method {key_id} not found"))?;
922    if matches.next().is_some() {
923        return Err(format!("ATProto signing method {key_id} is ambiguous"));
924    }
925    if method.get("type").and_then(serde_json::Value::as_str) != Some("Multikey")
926        || method.get("controller").and_then(serde_json::Value::as_str) != Some(claims.iss.as_str())
927    {
928        return Err("ATProto signing method must be a subject-controlled Multikey".to_owned());
929    }
930    let multikey = method
931        .get("publicKeyMultibase")
932        .and_then(serde_json::Value::as_str)
933        .ok_or_else(|| "ATProto signing method has no publicKeyMultibase".to_owned())?;
934    verify_atproto_ecdsa(
935        &header.alg,
936        multikey,
937        format!("{}.{}", parts[0], parts[1]).as_bytes(),
938        parts[2],
939    )?;
940    // The service assertion proves the DID, not a tenant. Resolve any local
941    // tenant binding only after signature verification and only from the
942    // authority-owned hosted-account record store.
943    let verified_tenant = state.hosted_account_tenant(&claims.iss).await?;
944
945    Ok(VerifiedSubject {
946        sub: claims.iss.clone(),
947        cnf_key_bytes: None,
948        cnf_jkt: None,
949        iat: claims.iat,
950        granted_scopes: Some(vec!["transition:generic".to_owned()]),
951        verified_tenant,
952        atproto_replay: Some((claims.iss, claims.jti, claims.exp)),
953        require_clearance: true,
954        ttl_ceiling: Some(MAX_ATPROTO_EXCHANGE_TOKEN_TTL),
955    })
956}
957
958fn decode_jwt_json<T: serde::de::DeserializeOwned>(segment: &str, name: &str) -> Result<T, String> {
959    let bytes = URL_SAFE_NO_PAD
960        .decode(segment)
961        .map_err(|_| format!("ATProto service JWT {name} is not base64url"))?;
962    serde_json::from_slice(&bytes)
963        .map_err(|error| format!("ATProto service JWT {name} is invalid: {error}"))
964}
965
966fn verify_atproto_ecdsa(
967    alg: &str,
968    multikey: &str,
969    signing_input: &[u8],
970    signature_segment: &str,
971) -> Result<(), String> {
972    use p256::ecdsa::signature::Verifier as _;
973
974    let encoded = multikey
975        .strip_prefix('z')
976        .ok_or_else(|| "ATProto Multikey must use base58btc".to_owned())?;
977    let key = bs58::decode(encoded)
978        .into_vec()
979        .map_err(|_| "ATProto Multikey is invalid base58btc".to_owned())?;
980    let signature = URL_SAFE_NO_PAD
981        .decode(signature_segment)
982        .map_err(|_| "ATProto service JWT signature is not base64url".to_owned())?;
983    match alg {
984        "ES256" => {
985            let raw = key
986                .strip_prefix(&[0x80, 0x24])
987                .ok_or_else(|| "ES256 requires a p256-pub Multikey".to_owned())?;
988            let verifying_key = p256::ecdsa::VerifyingKey::from_sec1_bytes(raw)
989                .map_err(|_| "invalid P-256 ATProto signing key".to_owned())?;
990            let signature = p256::ecdsa::Signature::from_slice(&signature)
991                .map_err(|_| "invalid ES256 service JWT signature encoding".to_owned())?;
992            verifying_key
993                .verify(signing_input, &signature)
994                .map_err(|_| "ATProto service JWT signature verification failed".to_owned())
995        }
996        "ES256K" => {
997            let raw = key
998                .strip_prefix(&[0xe7, 0x01])
999                .ok_or_else(|| "ES256K requires a secp256k1-pub Multikey".to_owned())?;
1000            let verifying_key = k256::ecdsa::VerifyingKey::from_sec1_bytes(raw)
1001                .map_err(|_| "invalid secp256k1 ATProto signing key".to_owned())?;
1002            let signature = k256::ecdsa::Signature::from_slice(&signature)
1003                .map_err(|_| "invalid ES256K service JWT signature encoding".to_owned())?;
1004            verifying_key
1005                .verify(signing_input, &signature)
1006                .map_err(|_| "ATProto service JWT signature verification failed".to_owned())
1007        }
1008        _ => Err("unsupported ATProto service JWT algorithm".to_owned()),
1009    }
1010}
1011
1012fn exchange_tenant(
1013    subject: &VerifiedSubject,
1014    requested: Option<&str>,
1015) -> Result<Option<String>, &'static str> {
1016    let requested = requested.map(str::trim);
1017    if requested.is_some_and(|tenant| {
1018        tenant.is_empty()
1019            || tenant == "*"
1020            || tenant.len() > 128
1021            || tenant.chars().any(char::is_control)
1022    }) {
1023        return Err("tenant must be a concrete, non-empty domain");
1024    }
1025    match (subject.verified_tenant.as_deref(), requested) {
1026        (Some(verified), Some(requested)) if verified != requested => {
1027            Err("requested tenant differs from the verified source-token tenant")
1028        }
1029        (Some(verified), _) => Ok(Some(verified.to_owned())),
1030        // Tenant selection is an authority assertion, not an exchange
1031        // parameter. Federated identity proofs establish identity but do not
1032        // bind the subject to a local Casbin domain. Only a tenant preserved
1033        // from a verified local-issuer token or resolved from a hosted account
1034        // record may reach PolicyService.
1035        (None, Some(_)) => Err("subject token has no verified local tenant binding"),
1036        (None, None) if subject.require_clearance => {
1037            Err("tenant is required for the ATProto exchange")
1038        }
1039        (None, None) => Ok(None),
1040    }
1041}
1042
1043#[derive(Deserialize)]
1044pub struct AtprotoExchangeRequest {
1045    pub tenant: String,
1046    #[serde(default)]
1047    pub scope: Option<String>,
1048    #[serde(default)]
1049    pub audience: Option<String>,
1050}
1051
1052/// XRPC adapter over the RFC 8693 exchange core.
1053pub async fn exchange_atproto_ucan(
1054    State(state): State<Arc<OAuthState>>,
1055    headers: HeaderMap,
1056    Json(request): Json<AtprotoExchangeRequest>,
1057) -> Response {
1058    let Some(assertion) = headers
1059        .get(header::AUTHORIZATION)
1060        .and_then(|value| value.to_str().ok())
1061        .and_then(|value| value.split_once(' '))
1062        .filter(|(scheme, token)| {
1063            scheme.eq_ignore_ascii_case("Bearer")
1064                && !token.is_empty()
1065                && !token.chars().any(char::is_whitespace)
1066        })
1067        .map(|(_, token)| token)
1068    else {
1069        return xrpc_error(
1070            StatusCode::UNAUTHORIZED,
1071            "InvalidToken",
1072            "Authorization: Bearer service JWT is required",
1073        );
1074    };
1075    let endpoint = format!(
1076        "{}/xrpc/ai.hyprstream.identity.exchangeUcan",
1077        state.atproto_issuer_url().trim_end_matches('/')
1078    );
1079    let output_dpop_proof = match headers
1080        .get("DPoP")
1081        .and_then(|value| value.to_str().ok())
1082        .and_then(|proof| super::dpop::verify_dpop_proof(proof, "POST", &endpoint, None).ok())
1083    {
1084        Some(proof) => Some(proof),
1085        None => {
1086            return xrpc_error(
1087                StatusCode::BAD_REQUEST,
1088                "InvalidRequest",
1089                "a valid DPoP proof is required to bind the exchanged credential",
1090            );
1091        }
1092    };
1093    let response = exchange_token_exchange(
1094        &state,
1095        assertion,
1096        TOKEN_TYPE_JWT,
1097        request.audience.as_deref(),
1098        request.scope.as_deref(),
1099        None,
1100        output_dpop_proof,
1101        Some(ISSUED_TOKEN_TYPE),
1102        Some(&request.tenant),
1103        // The atproto XRPC exchange is a public-client (UCAN-authenticated)
1104        // flow; the public client identifier is the RFC 9068 `client_id` for a
1105        // user `at+jwt` output (unused for a service `wit+jwt` output).
1106        BROWSER_PUBLIC_CLIENT_ID,
1107    )
1108    .await;
1109    if response.status().is_success() {
1110        return response;
1111    }
1112
1113    let status = response.status();
1114    let body = axum::body::to_bytes(response.into_body(), 16 * 1024)
1115        .await
1116        .ok()
1117        .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
1118    let oauth_error = body
1119        .as_ref()
1120        .and_then(|value| value.get("error"))
1121        .and_then(serde_json::Value::as_str);
1122    let message = body
1123        .as_ref()
1124        .and_then(|value| value.get("error_description"))
1125        .and_then(serde_json::Value::as_str)
1126        .unwrap_or("ATProto credential exchange failed");
1127    let error = match oauth_error {
1128        Some("invalid_grant") => "InvalidToken",
1129        Some("invalid_scope" | "invalid_target" | "invalid_request") => "InvalidRequest",
1130        _ if status.is_server_error() => "InternalServerError",
1131        _ => "InvalidRequest",
1132    };
1133    xrpc_error(status, error, message)
1134}
1135
1136fn xrpc_error(status: StatusCode, error: &str, message: &str) -> Response {
1137    (
1138        status,
1139        [
1140            (header::CACHE_CONTROL, "no-store"),
1141            (header::PRAGMA, "no-cache"),
1142        ],
1143        Json(serde_json::json!({
1144            "error": error,
1145            "message": message,
1146        })),
1147    )
1148        .into_response()
1149}
1150
1151/// Bound an RFC 8693 scope request to authority already present on the verified
1152/// subject access token. The signed subject-token grant is the ceiling: callers
1153/// may retain or narrow it, never add authority. Subject types without a local
1154/// OAuth grant cannot mint a scope claim through token exchange.
1155fn attenuate_exchange_scopes(
1156    subject: &VerifiedSubject,
1157    requested: Option<&str>,
1158) -> Result<Option<Vec<String>>, &'static str> {
1159    let Some(granted) = subject.granted_scopes.as_ref() else {
1160        return if requested.is_some() {
1161            Err("subject token carries no OAuth grant to authorize requested scope")
1162        } else {
1163            Ok(None)
1164        };
1165    };
1166
1167    let Some(requested) = requested else {
1168        return Ok(Some(granted.clone()));
1169    };
1170    let requested: Vec<&str> = requested
1171        .split_whitespace()
1172        .map(|scope| {
1173            super::state::normalize_scope_token(scope)
1174                .ok_or("requested scope contains an invalid token")
1175        })
1176        .collect::<Result<_, _>>()?;
1177    if requested.is_empty() {
1178        return Err("requested scope must not be empty");
1179    }
1180    if requested
1181        .iter()
1182        .any(|scope| !granted.iter().any(|allowed| allowed == scope))
1183    {
1184        return Err("requested scope exceeds the subject token grant");
1185    }
1186
1187    Ok(Some(
1188        granted
1189            .iter()
1190            .filter(|allowed| requested.contains(&allowed.as_str()))
1191            .cloned()
1192            .collect(),
1193    ))
1194}
1195
1196/// Decode `nbf` from JWT payload and reject if in the future (±5s clock skew).
1197fn check_nbf(jwt: &str) -> Result<(), String> {
1198    let nbf = (|| -> Option<i64> {
1199        let payload_b64 = jwt.split('.').nth(1)?;
1200        let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
1201        let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
1202        value.get("nbf")?.as_i64()
1203    })();
1204    if let Some(nbf) = nbf {
1205        let now = chrono::Utc::now().timestamp();
1206        if nbf > now + 5 {
1207            return Err("token not yet valid (nbf)".to_owned());
1208        }
1209    }
1210    Ok(())
1211}
1212
1213fn tx_error(status: StatusCode, error: &str, description: &str) -> Response {
1214    (
1215        status,
1216        [
1217            (header::CACHE_CONTROL, "no-store"),
1218            (header::PRAGMA, "no-cache"),
1219        ],
1220        Json(serde_json::json!({
1221            "error": error,
1222            "error_description": description,
1223        })),
1224    )
1225        .into_response()
1226}
1227
1228// ─── S6: UCAN grant → access/refresh tokens (#572) ─────────────────────────
1229//
1230// This is the HTTP-layer wiring over `mac::exchange::evaluate_grant`. The
1231// security-critical logic (chain validation, ceiling-subset, MAC clearance,
1232// sender-binding) lives in `mac::exchange`; this handler is the RFC 8693
1233// adapter that decodes the grant, verifies the DPoP proof, resolves the
1234// subject's MAC context, calls `evaluate_grant`, and mints the short-ttl
1235// sender-bound token the decision authorizes.
1236//
1237// **S8 (#574) activation:** the MAC *clearance* now rides the verified `Claims`
1238// (the `clearance` field, signed by the issuing node) and the subject's
1239// assurance is derived from the DPoP proof key + the kid-anchored PQ trust
1240// store binding. The concrete `ClaimsSubjectContextResolver` does the real
1241// two-input S1 derivation. The caller supplies the resolver (built from the
1242// subject's verified claims + DPoP-derived key material); passing
1243// `DenyUnlabeledResolver` keeps the deny-by-default posture for a node that has
1244// not configured subject-clearance resolution.
1245
1246/// Resolve a UCAN audience DID → the S1 [`SecurityContext`] it presents at grant
1247/// time (clearance clamped to verified key material).
1248///
1249/// **S8 (#574) ships the real derivation.** The concrete
1250/// [`ClaimsSubjectContextResolver`] reads the authority-asserted `clearance`
1251/// off verified [`Claims`] and derives assurance from the `VerifiedKeyMaterial`
1252/// the caller resolved from the verified crypto (DPoP proof key + PQ trust
1253/// store binding). The two-input `security_context(key_material)` clamps the
1254/// assurance axis DOWN to what the verified key supports — the load-bearing
1255/// #548 invariant.
1256///
1257/// SECURITY: the resolution MUST be from *authority-asserted* clearance (a
1258/// field the issuing node signed), never from a self-asserted claim in the
1259/// UCAN. The UCAN is the grant; the clearance is independent state the MAC
1260/// model holds about the subject. `None` (→ `UnlabeledSubject` → deny) remains
1261/// the fail-closed posture for a subject the resolver has no verified claims
1262/// for.
1263pub trait SubjectContextResolver: Send + Sync {
1264    /// The clearance context for `audience_did`, or `None` if the subject is
1265    /// unlabeled / unverified. `None` ⇒ `evaluate_grant` denies.
1266    fn resolve(&self, audience_did: &str) -> Option<hyprstream_rpc::auth::mac::SecurityContext>;
1267}
1268
1269/// A no-op resolver that always returns `None` — the explicit fail-closed
1270/// choice for a node that has not configured subject-clearance resolution.
1271/// Production under MAC SHOULD wire [`ClaimsSubjectContextResolver`] instead.
1272pub struct DenyUnlabeledResolver;
1273
1274impl SubjectContextResolver for DenyUnlabeledResolver {
1275    fn resolve(&self, _audience_did: &str) -> Option<hyprstream_rpc::auth::mac::SecurityContext> {
1276        // Fail-closed: no clearance is known ⇒ no token. See the trait docs.
1277        None
1278    }
1279}
1280
1281/// **S8 (#574):** the concrete `SubjectContextResolver` that does the real
1282/// two-input MAC context derivation.
1283///
1284/// Construct it with the subject's verified [`Claims`] (carrying the
1285/// authority-asserted `clearance` field) and the [`VerifiedKeyMaterial`]
1286/// derived from the verified crypto (the DPoP proof key + the kid-anchored PQ
1287/// trust store binding, exactly what
1288/// [`EnvelopeContext::verified_key_material`](hyprstream_rpc::service::EnvelopeContext::verified_key_material)
1289/// computes). [`SubjectContextResolver::resolve`] then returns the assembled
1290/// [`SecurityContext`] — clearance clamped to the crypto-derived assurance.
1291///
1292/// The resolver matches `audience_did` against the claims' subject (the
1293/// principal the clearance was issued to). A mismatch ⇒ `None` ⇒ deny: the
1294/// clearance cannot be borrowed across identities.
1295///
1296/// This is what flips S6 from deny-everything to actually-issuing-tokens for
1297/// verified subjects. For a fully-verified PQ subject (PqHybrid key material +
1298/// a clearance that dominates the object label), `evaluate_grant` permits; for
1299/// a classical-key subject on a PQ-required object, the clamped assurance
1300/// floors to Classical and the dominance check denies (fail-closed).
1301pub struct ClaimsSubjectContextResolver {
1302    /// The audience DID this resolver's claims are bound to. `resolve()` checks
1303    /// the grant's audience matches before returning the context (anti-borrow).
1304    audience_did: String,
1305    /// The subject's verified claims, carrying the authority-asserted clearance.
1306    claims: hyprstream_rpc::auth::Claims,
1307    /// Assurance derived from the verified crypto (DPoP key + PQ anchor).
1308    key_material: hyprstream_rpc::auth::mac::VerifiedKeyMaterial,
1309}
1310
1311impl ClaimsSubjectContextResolver {
1312    /// Construct a resolver for a single subject. `claims` is the subject's
1313    /// verified JWT claims (signed by the issuing node, so the `clearance` is
1314    /// authority-asserted). `key_material` is the assurance derived from the
1315    /// verified DPoP proof key + PQ trust store binding. `audience_did` is the
1316    /// DID the clearance was issued to; a grant whose audience differs is
1317    /// denied (the clearance cannot cross identities).
1318    pub fn new(
1319        audience_did: impl Into<String>,
1320        claims: hyprstream_rpc::auth::Claims,
1321        key_material: hyprstream_rpc::auth::mac::VerifiedKeyMaterial,
1322    ) -> Self {
1323        Self {
1324            audience_did: audience_did.into(),
1325            claims,
1326            key_material,
1327        }
1328    }
1329}
1330
1331impl SubjectContextResolver for ClaimsSubjectContextResolver {
1332    fn resolve(&self, audience_did: &str) -> Option<hyprstream_rpc::auth::mac::SecurityContext> {
1333        use hyprstream_rpc::auth::mac::SubjectContextClaims as _;
1334        // Anti-borrow: the clearance was issued to `self.audience_did`; a grant
1335        // presented for a DIFFERENT audience cannot use this subject's clearance.
1336        if audience_did != self.audience_did.as_str() {
1337            return None;
1338        }
1339        // The two-input S1 derivation: clearance (from Claims) + assurance (from
1340        // verified key material). SecurityContext::from_clearance clamps the
1341        // assurance axis DOWN to what the crypto supports — no silent upgrade.
1342        self.claims.security_context(self.key_material)
1343    }
1344}
1345
1346/// The two principals a minted grant token carries (#680/#681). For a delegated
1347/// grant this splits the single `sub` into the delegator (source of authority)
1348/// and the actor (the presenter that signs the downstream envelope) — the
1349/// confused-deputy fix: the token records "actor acting for delegator" instead
1350/// of collapsing to one identity.
1351struct TokenPrincipals {
1352    /// The minted token's `sub`: the delegator (UCAN chain-root issuer) for a
1353    /// delegated grant, or the subject (the self-issued root's DID) for a root
1354    /// grant. This is always a UCAN principal DID — never the RFC 8707 resource
1355    /// indicator (which stays on the `aud` claim).
1356    sub: String,
1357    /// The minted token's RFC 8693 §4.1 `act` claim: the actor (grant audience /
1358    /// presenter). `None` for a self-issued root grant (single principal).
1359    act: Option<hyprstream_rpc::auth::ActClaim>,
1360}
1361
1362/// Derive the subject's MAC [`SecurityContext`] for a (possibly delegated) UCAN
1363/// grant, plus the [`TokenPrincipals`] the mint stamps on the token (#680/#681).
1364///
1365/// - **Self-issued root grant** (`root_issuer == audience`): single-principal.
1366///   Context is `resolve(audience)`; `sub = audience`, `act = None`.
1367/// - **Delegated grant** (`root_issuer != audience`): two-principal (#681). The
1368///   effective context is `meet(delegator = root_issuer, actor = audience)` via
1369///   [`SecurityContext::delegated`](hyprstream_rpc::auth::mac::SecurityContext::delegated)
1370///   — fail-closed if *either* principal is unresolved (no default clearance for
1371///   a missing principal). `sub = delegator`, `act = { sub: actor, clearance:
1372///   actor's }`, so the token is minted as "actor acting for delegator".
1373///
1374/// Pure over the resolver (a trait) so the delegation logic is unit-testable
1375/// without the async HTTP mint path.
1376fn resolve_grant_subject(
1377    grant: &hyprstream_rpc::auth::ucan::token::Ucan,
1378    resolver: &dyn SubjectContextResolver,
1379) -> ResolvedGrantSubject {
1380    let audience = grant.audience().as_str();
1381    let delegator = grant.root_issuer().as_str();
1382
1383    if delegator == audience {
1384        // Self-issued root — no delegation. Single principal = the subject.
1385        return ResolvedGrantSubject {
1386            subject: resolver.resolve(audience),
1387            on_behalf_of: None,
1388            principals: TokenPrincipals {
1389                sub: audience.to_owned(),
1390                act: None,
1391            },
1392        };
1393    }
1394
1395    // Delegation: resolve BOTH principals and take the fail-closed meet (#681).
1396    let delegator_ctx = resolver.resolve(delegator);
1397    let actor_ctx = resolver.resolve(audience);
1398    let ctx = hyprstream_rpc::auth::mac::SecurityContext::delegated(
1399        delegator_ctx.as_ref(),
1400        actor_ctx.as_ref(),
1401    );
1402    let principals = TokenPrincipals {
1403        sub: delegator.to_owned(),
1404        act: Some(hyprstream_rpc::auth::ActClaim {
1405            sub: audience.to_owned(),
1406            // The actor's authority-asserted clearance, carried so a downstream
1407            // reader can re-take the meet off the one verified token. `None` if
1408            // the actor is unresolved — in which case `ctx` above is already
1409            // `None` and the grant fails closed before minting.
1410            clearance: actor_ctx.map(|c| {
1411                hyprstream_rpc::auth::mac::CredentialClearance::from_label(*c.clearance())
1412            }),
1413            act: None,
1414        }),
1415    };
1416    ResolvedGrantSubject {
1417        subject: ctx,
1418        // The delegator (authority source), recorded on the grant audit record
1419        // as `on_behalf_of` (#680/#681). Carried separately from the met
1420        // `subject` so the audit trail names both principals of a delegated
1421        // decision. `None` if the delegator is unresolved (the grant already
1422        // fails closed via `subject` above).
1423        on_behalf_of: delegator_ctx,
1424        principals,
1425    }
1426}
1427
1428/// Outcome of [`resolve_grant_subject`]: the effective (met) subject context the
1429/// grant gates evaluate, the delegator context for two-principal audit
1430/// attribution (#680/#681), and the principals the mint stamps on the token.
1431struct ResolvedGrantSubject {
1432    /// Effective context: `meet(delegator, actor)` for a delegated grant, or the
1433    /// sole principal for a self-issued root grant. `None` ⇒ fail closed.
1434    subject: Option<hyprstream_rpc::auth::mac::SecurityContext>,
1435    /// The delegator principal, for the audit record's `on_behalf_of`. `None`
1436    /// for a self-issued root grant (single principal) or an unresolved delegator.
1437    on_behalf_of: Option<hyprstream_rpc::auth::mac::SecurityContext>,
1438    /// The delegator/actor split the mint stamps on the token.
1439    principals: TokenPrincipals,
1440}
1441
1442/// POST /oauth/token — UCAN grant (RFC 8693 token-exchange,
1443/// `subject_token_type = urn:hyprstream:token-type:ucan-grant`).
1444///
1445/// Accepts a CBOR-encoded UCAN as the `subject_token` (the subset-grant) and
1446/// mints a **short-ttl, sender-bound** access token (+ refresh token when the
1447/// store is configured) for the requested access — never the whole grant (ZSP).
1448///
1449/// `dpop_header` is the `DPoP` proof header; it is MANDATORY for this grant
1450/// type (ZSP: no bearer). The proof signature/htm/htu/replay are verified here
1451/// via the same `verify_dpop_proof` the other grant types use; the resulting
1452/// `jkt` is the sender-binding thumbprint. Passing `None` ⇒ `invalid_request`.
1453///
1454/// `subject_resolver` supplies the MAC clearance; `DenyUnlabeledResolver`
1455/// denies until S8 ships the real resolver.
1456///
1457/// Fail-closed: every `GrantError` maps to a concrete OAuth error. There is no
1458/// fallback path; authority-unreachable is a denial.
1459pub async fn exchange_ucan_grant(
1460    state: &Arc<OAuthState>,
1461    subject_token: &str,
1462    dpop_header: Option<&str>,
1463    requested_scope: Option<&str>,
1464    audience: Option<&str>,
1465    subject_resolver: &dyn SubjectContextResolver,
1466) -> Response {
1467    // ── 1. DPoP sender-binding is MANDATORY (ZSP) ──────────────────────────
1468    // No proof ⇒ no token. A bearer token minted from a grant re-introduces
1469    // standing access — the exact thing ZSP removes.
1470    let token_endpoint = format!("{}/oauth/token", state.issuer_url.trim_end_matches('/'));
1471    let dpop_jkt = match dpop_header.and_then(|h| {
1472        super::dpop::verify_dpop_proof(h, "POST", &token_endpoint, None)
1473            .ok()
1474            .map(|p| p.jkt)
1475    }) {
1476        Some(jkt) => jkt,
1477        None => {
1478            return tx_error(
1479                StatusCode::BAD_REQUEST,
1480                "invalid_request",
1481                "UCAN grant token-exchange requires a valid DPoP proof (sender-binding)",
1482            );
1483        }
1484    };
1485
1486    // ── 2. Decode the CBOR UCAN grant ──────────────────────────────────────
1487    let ucan_bytes = match URL_SAFE_NO_PAD.decode(subject_token) {
1488        Ok(b) => b,
1489        Err(_) => {
1490            return tx_error(
1491                StatusCode::BAD_REQUEST,
1492                "invalid_request",
1493                "subject_token is not valid base64url CBOR",
1494            );
1495        }
1496    };
1497    let grant = match hyprstream_rpc::auth::ucan::token::Ucan::from_cbor(&ucan_bytes) {
1498        Ok(u) => u,
1499        Err(e) => {
1500            return tx_error(
1501                StatusCode::BAD_REQUEST,
1502                "invalid_grant",
1503                &format!("subject_token is not a valid UCAN: {e}"),
1504            );
1505        }
1506    };
1507
1508    // ── 3. Resolve the subject's MAC context (S8 seam; deny until then). ────
1509    //    #680/#681: a delegated grant (chain root ≠ audience) resolves TWO
1510    //    principals and takes the fail-closed meet(delegator, actor); a
1511    //    self-issued root grant stays single-principal. `principals` carries the
1512    //    delegator/actor split the mint stamps onto the token.
1513    let ResolvedGrantSubject {
1514        subject: subject_ctx,
1515        on_behalf_of,
1516        principals,
1517    } = resolve_grant_subject(&grant, subject_resolver);
1518
1519    // ── 4. Parse the requested access off the form fields ──────────────────
1520    // TODO(#572-object-label): wire the manifest/TE object-label resolver so
1521    //   the S1 floor can be evaluated for real. Until then `object_label` is
1522    //   `None`, which makes the S1 object-label gate deny — the conservative
1523    //   direction.
1524    let request = match parse_grant_request(requested_scope, audience) {
1525        Ok(r) => r,
1526        Err(msg) => return tx_error(StatusCode::BAD_REQUEST, "invalid_scope", &msg),
1527    };
1528
1529    // ── 5. The single fail-closed S6 path ──────────────────────────────────
1530    // A no-op UcanVerifier is NOT acceptable — signatures MUST verify. The
1531    // verifier is built from the trust store's anchored ML-DSA-65 keys (the
1532    // same `register_pq_trust` binding the rest of the TCB uses). Until that
1533    // binding is wired into the OAuth state, the grant path fails closed here
1534    // rather than trusting an unverified chain. There is NO fallback path.
1535    //
1536    // TODO(#572-verifier): construct the UcanVerifier from the trust store's
1537    //   anchored ML-DSA-65 keys. Until that wiring lands, the HTTP grant path
1538    //   denies every request at this gate — the conservative direction. The
1539    //   core `evaluate_grant` (with full happy-path + denial coverage) is
1540    //   exercised through its own tests using a real `UcanVerifier`.
1541    let Some(verifier) = crate::mac::exchange_ucan_verifier(state) else {
1542        return tx_error(
1543            StatusCode::FORBIDDEN,
1544            "server_error",
1545            "UCAN grant verification is not configured on this node",
1546        );
1547    };
1548    // MAC #547 / B2 (#674): the grant path is a security decision, and S7's
1549    // complete-mediation guarantee is only real if every decision is on the
1550    // audit trail. No sink configured ⇒ fail closed (deny) rather than mint
1551    // an unaudited token — mirroring `AuditedAvc`'s rule at the TE path.
1552    let Some(sink) = state.audit_sink.as_deref() else {
1553        return tx_error(
1554            StatusCode::INTERNAL_SERVER_ERROR,
1555            "server_error",
1556            "MAC grant-path audit trail is not configured on this node",
1557        );
1558    };
1559    let now = chrono::Utc::now().timestamp().max(0) as u64;
1560    let decision = crate::mac::exchange::audited_evaluate_grant(
1561        &grant,
1562        &verifier,
1563        now,
1564        &request,
1565        subject_ctx.as_ref(),
1566        on_behalf_of.as_ref(),
1567        true, // sender-bound: dpop_jkt is present
1568        sink,
1569    );
1570
1571    let granted = match decision {
1572        Ok(GrantDecision::Permit(g)) => g,
1573        Ok(GrantDecision::Escalate { .. }) => {
1574            // Over-ceiling: the escalation tier (TODO #572-escalation) is not
1575            // wired; return insufficient_scope. Do NOT auto-mint.
1576            return tx_error(
1577                StatusCode::FORBIDDEN,
1578                "insufficient_scope",
1579                "grant request exceeds ceiling; escalation amendment required",
1580            );
1581        }
1582        Err(e) => return grant_error_response(e),
1583    };
1584
1585    // ── 6. Mint the short-ttl sender-bound access token (ZSP) ──────────────
1586    // Persist the grant re-evaluation context so a refresh re-runs the S6 gate
1587    // chain (B1 #673) rather than free-re-minting. The grant CID binds the
1588    // stored blob to exactly this grant.
1589    let grant_refresh = super::state::UcanGrantRefresh {
1590        grant_cbor_b64: subject_token.to_owned(),
1591        grant_cid: blake3::hash(&ucan_bytes).to_hex().to_string(),
1592        requested_scope: requested_scope.map(str::to_owned),
1593        audience: audience.map(str::to_owned),
1594    };
1595    // #698 issuer path: thread the resolved clearance into the mint so the
1596    // token carries it for downstream PEP enforcement. `subject_ctx` is the
1597    // met context from resolve_grant_subject — its clearance is the
1598    // authority-assigned label the enrollment table holds for this subject.
1599    let subject_clearance = subject_ctx.map(|c| *c.clearance());
1600    mint_grant_token(
1601        state,
1602        &granted,
1603        &dpop_jkt,
1604        Some(grant_refresh),
1605        principals,
1606        subject_clearance,
1607    )
1608    .await
1609}
1610
1611/// Re-evaluate a UCAN grant on refresh and re-mint (MAC #547 / B1 #673).
1612///
1613/// ZSP: a UCAN-grant refresh is NOT a free re-mint. The generic OAuth 2.1
1614/// refresh path would rotate the token without re-checking the grant and would
1615/// treat DPoP as optional; both break the S6 discipline. This path instead:
1616///
1617/// 1. requires a **fresh** DPoP proof (mandatory sender-binding — matching the
1618///    initial mint), and
1619/// 2. re-presents the persisted grant to [`crate::mac::exchange::audited_evaluate_refresh`], which runs the
1620///    same gate chain as mint against the *current* `now` and verifier state —
1621///    so a ceiling that has since been amended/revoked, or a grant that has
1622///    since expired, now denies.
1623///
1624/// The caller (`exchange_refresh_token`) has already atomically consumed
1625/// (rotated) the presented refresh token before delegating here. Every failure
1626/// is fail-closed. On permit, a new sender-bound access token + rotated refresh
1627/// token are minted, re-persisting the grant context for the next refresh.
1628pub(crate) async fn exchange_ucan_grant_refresh(
1629    state: &Arc<OAuthState>,
1630    ucan_grant: &super::state::UcanGrantRefresh,
1631    dpop_header: Option<&str>,
1632) -> Response {
1633    // 1. Fresh DPoP is MANDATORY (ZSP sender-binding) — same as the mint path.
1634    let token_endpoint = format!("{}/oauth/token", state.issuer_url.trim_end_matches('/'));
1635    let dpop_jkt = match dpop_header.and_then(|h| {
1636        super::dpop::verify_dpop_proof(h, "POST", &token_endpoint, None)
1637            .ok()
1638            .map(|p| p.jkt)
1639    }) {
1640        Some(jkt) => jkt,
1641        None => {
1642            return tx_error(
1643                StatusCode::BAD_REQUEST,
1644                "invalid_request",
1645                "UCAN grant refresh requires a valid DPoP proof (sender-binding)",
1646            );
1647        }
1648    };
1649
1650    // 2. Re-present the persisted grant. Verify the stored blob's content id
1651    //    first — a corrupted/substituted grant fails closed.
1652    let ucan_bytes = match URL_SAFE_NO_PAD.decode(&ucan_grant.grant_cbor_b64) {
1653        Ok(b) => b,
1654        Err(_) => {
1655            return tx_error(
1656                StatusCode::INTERNAL_SERVER_ERROR,
1657                "server_error",
1658                "stored UCAN grant is not valid base64url",
1659            );
1660        }
1661    };
1662    if blake3::hash(&ucan_bytes).to_hex().to_string() != ucan_grant.grant_cid {
1663        return tx_error(
1664            StatusCode::INTERNAL_SERVER_ERROR,
1665            "server_error",
1666            "stored UCAN grant failed its content-id check",
1667        );
1668    }
1669    let grant = match hyprstream_rpc::auth::ucan::token::Ucan::from_cbor(&ucan_bytes) {
1670        Ok(u) => u,
1671        Err(e) => {
1672            return tx_error(
1673                StatusCode::INTERNAL_SERVER_ERROR,
1674                "server_error",
1675                &format!("stored UCAN grant no longer decodes: {e}"),
1676            );
1677        }
1678    };
1679
1680    // Rebuild the S6 request from the persisted requested access.
1681    let request = match parse_grant_request(
1682        ucan_grant.requested_scope.as_deref(),
1683        ucan_grant.audience.as_deref(),
1684    ) {
1685        Ok(r) => r,
1686        Err(msg) => return tx_error(StatusCode::BAD_REQUEST, "invalid_scope", &msg),
1687    };
1688
1689    // Resolve the subject's MAC context exactly as the mint path does (#698
1690    // Decision D: enrollment-table resolver, actor assurance floored at
1691    // Classical), including the #680/#681 two-principal delegated meet —
1692    // refresh must not be more permissive than mint.
1693    let resolver = crate::mac::exchange_enrollment_resolver();
1694    let ResolvedGrantSubject {
1695        subject: subject_ctx,
1696        on_behalf_of,
1697        principals,
1698    } = resolve_grant_subject(&grant, resolver.as_ref());
1699
1700    // The verifier: same trust-store-anchored construction as mint. Absent ⇒
1701    // fail closed (no unverified chain).
1702    let Some(verifier) = crate::mac::exchange_ucan_verifier(state) else {
1703        return tx_error(
1704            StatusCode::FORBIDDEN,
1705            "server_error",
1706            "UCAN grant verification is not configured on this node",
1707        );
1708    };
1709    // MAC #547 / B2 (#674): refresh is a grant-path decision exactly like mint
1710    // — it must be on the audit trail too, with the same fail-closed rule (no
1711    // sink configured ⇒ deny rather than re-mint unaudited).
1712    let Some(sink) = state.audit_sink.as_deref() else {
1713        return tx_error(
1714            StatusCode::INTERNAL_SERVER_ERROR,
1715            "server_error",
1716            "MAC grant-path audit trail is not configured on this node",
1717        );
1718    };
1719    let now = chrono::Utc::now().timestamp().max(0) as u64;
1720    let decision = crate::mac::exchange::audited_evaluate_refresh(
1721        &grant,
1722        &verifier,
1723        now,
1724        &request,
1725        subject_ctx.as_ref(),
1726        on_behalf_of.as_ref(),
1727        true, // sender-bound: a fresh DPoP proof was just verified above
1728        sink,
1729    );
1730
1731    let granted = match decision {
1732        Ok(GrantDecision::Permit(g)) => g,
1733        Ok(GrantDecision::Escalate { .. }) => {
1734            return tx_error(
1735                StatusCode::FORBIDDEN,
1736                "insufficient_scope",
1737                "grant request exceeds ceiling; escalation amendment required",
1738            );
1739        }
1740        Err(e) => return grant_error_response(e),
1741    };
1742
1743    // Re-mint + rotate, re-persisting the grant context for the next refresh.
1744    // #698: same clearance threading as mint — refresh must not be more
1745    // permissive (B1/#673).
1746    let subject_clearance = subject_ctx.map(|c| *c.clearance());
1747    mint_grant_token(
1748        state,
1749        &granted,
1750        &dpop_jkt,
1751        Some(ucan_grant.clone()),
1752        principals,
1753        subject_clearance,
1754    )
1755    .await
1756}
1757
1758/// Map an S6 [`GrantError`] to a concrete OAuth 2.1 error response. Every variant
1759/// is fail-closed; no variant maps to a permissive outcome.
1760fn grant_error_response(e: GrantError) -> Response {
1761    let (status, code, desc) = match &e {
1762        GrantError::Chain(_) => (
1763            StatusCode::UNAUTHORIZED,
1764            "invalid_grant",
1765            "UCAN grant chain failed validation".to_owned(),
1766        ),
1767        // Over-ceiling and insufficient-clearance both surface as
1768        // `insufficient_scope`: the request is not within the grant/label the
1769        // subject is authorized for. Distinct GrantError variants (different
1770        // gates) but the same OAuth error shape for the client.
1771        GrantError::OverCeiling { .. } | GrantError::InsufficientClearance => {
1772            (StatusCode::FORBIDDEN, "insufficient_scope", e.to_string())
1773        }
1774        GrantError::MissingSenderBinding => {
1775            (StatusCode::BAD_REQUEST, "invalid_request", e.to_string())
1776        }
1777        GrantError::UnlabeledSubject | GrantError::EmptyGrant => {
1778            (StatusCode::FORBIDDEN, "invalid_grant", e.to_string())
1779        }
1780        // B2 (#674): a would-be Permit that could not be durably audited.
1781        // Fail-closed, not the client's fault — surfaced as server_error
1782        // (matches the "audit trail not configured" preflight response).
1783        GrantError::AuditUnavailable => (
1784            StatusCode::INTERNAL_SERVER_ERROR,
1785            "server_error",
1786            e.to_string(),
1787        ),
1788    };
1789    tx_error(status, code, &desc)
1790}
1791
1792/// Parse the RFC 8693 `scope` + `audience` form fields into the S6
1793/// [`GrantRequest`].
1794///
1795/// `scope` is the S3 `action:resource:identifier` triple (the requested access);
1796/// `audience` is the RFC 8707 resource indicator (optional). The object label
1797/// is `None` here (resolved separately — see TODO(#572-object-label)).
1798fn parse_grant_request(
1799    scope: Option<&str>,
1800    audience: Option<&str>,
1801) -> Result<GrantRequest, String> {
1802    use hyprstream_rpc::auth::ucan::capability::{Ability, Caveats, Resource};
1803
1804    let scope_str = scope.ok_or_else(|| "scope is required for UCAN grant".to_owned())?;
1805    let parsed = hyprstream_rpc::auth::Scope::parse(scope_str)
1806        .map_err(|e| format!("invalid scope '{scope_str}': {e}"))?;
1807    Ok(GrantRequest {
1808        // S3 Scope(action, resource, identifier) → S5 Capability(resource, ability).
1809        // The `resource` URI is assembled as `mac://<resource>/<identifier>`;
1810        // `*` identifier maps to the wildcard. This mapping is the S3↔S5
1811        // vocabulary seam (deferred to #582); this is the conservative
1812        // structural projection.
1813        resource: Resource::new(format!("mac://{}/{}", parsed.resource, parsed.identifier)),
1814        ability: Ability::new(parsed.action),
1815        caveats: Caveats::default(),
1816        audience: audience.map(str::to_owned),
1817        object_label: None, // TODO(#572-object-label): manifest/TE resolver.
1818    })
1819}
1820
1821/// Mint the short-ttl, sender-bound access token for a permitted grant.
1822///
1823/// ZSP: the token encodes the **requested subset** (the [`GrantedAccess`]),
1824/// never the whole grant. It is bound to the DPoP `jkt` (`cnf.jkt`) and carries
1825/// a short ttl. A refresh token is stored when a token DB is configured.
1826///
1827/// **S8 (#574) + Fu3/#677:** the minted token is signed with the **hybrid**
1828/// composite JWT signature (EdDSA + ML-DSA-65, `alg: "ML-DSA-65-Ed25519"`)
1829/// under a Hybrid policy, matching the hybrid signature on the UCAN grant and
1830/// approval it consumed. The minted token is the same kind of
1831/// confidentiality/integrity-critical authority artifact the rest of the MAC
1832/// stack signs hybridly. Under Hybrid policy with no provisioned ML-DSA-65 key
1833/// the mint **fails closed** (no silent classical downgrade); under Classical
1834/// policy the token is signed with the pinned classical Ed25519 suite.
1835async fn mint_grant_token(
1836    state: &Arc<OAuthState>,
1837    granted: &GrantedAccess,
1838    dpop_jkt: &str,
1839    grant_refresh: Option<super::state::UcanGrantRefresh>,
1840    principals: TokenPrincipals,
1841    // #698 issuer path: the clearance the enrollment resolver derived for
1842    // this subject, stamped on the minted token so downstream PEP lanes
1843    // (#1268/#1269) can enforce MAC without re-resolving from the enrollment
1844    // table. `None` (unenrolled/unverified) ⇒ no clearance claim ⇒ the
1845    // downstream `ClaimsSubjectContextResolver` denies (fail-closed).
1846    subject_clearance: Option<hyprstream_rpc::auth::mac::SecurityLabel>,
1847) -> Response {
1848    let now = chrono::Utc::now().timestamp();
1849    let ttl = state
1850        .token_ttl
1851        .min(crate::mac::exchange::MAX_ACCESS_TOKEN_TTL_SECS);
1852    let expires_at = now + ttl as i64;
1853
1854    // #680/#681: the token subject is the DELEGATOR (source of authority) for a
1855    // delegated grant, or the subject for a root grant — always a UCAN principal
1856    // DID, never the RFC 8707 resource indicator (which stays on `aud`). For a
1857    // delegation, the actor (presenter that signs downstream) is carried in the
1858    // `act` claim below, so the token records "actor acting for delegator"
1859    // rather than collapsing to one identity (the confused-deputy fix).
1860    let sub = principals.sub.clone();
1861
1862    // #1159 freeze: UCAN issuance signs directly instead of using
1863    // PolicyService, so it must enforce the same concrete-subject invariant at
1864    // its own mint-and-refresh-persistence boundary. Return before signing or
1865    // storing a refresh token so a legacy path-form chain cannot be extended.
1866    if is_path_form_did_web(&sub) {
1867        return tx_error(
1868            StatusCode::BAD_REQUEST,
1869            "invalid_grant",
1870            "path-form did:web account subjects are frozen; host-form account minting is not available yet (#1159)",
1871        );
1872    }
1873
1874    let scope_str = format!(
1875        "{}@{}",
1876        granted.capability.ability, granted.capability.resource
1877    );
1878
1879    // Fu1/#677 (was TODO(#572-scope-claim)): carry the attenuated capability
1880    // subset in the `cap` claim so the downstream PEP (S2) enforces the minted
1881    // least-authority on the wire, and a refresh can only re-grant this subset
1882    // — not just log it. The cnf.jkt binding + short ttl remain load-bearing.
1883    let mut claims = hyprstream_rpc::auth::Claims::new(sub.clone(), now, expires_at)
1884        .with_issuer(state.issuer_url.clone())
1885        .with_audience(granted.audience.clone())
1886        .with_cap(scope_str)
1887        .with_jti();
1888    // #680/#681: stamp the actor (delegate) so the two-principal delegation is
1889    // verifiable downstream (`meet(delegator, actor)`, assurance from the actor
1890    // who signs the envelope). Absent for a self-issued root grant.
1891    if let Some(actor) = principals.act {
1892        claims = claims.with_act(actor);
1893    }
1894    // #698 issuer path: stamp the authority-resolved clearance on the minted
1895    // token. This is the wire that was missing — the enrollment resolver
1896    // resolved DID→clearance for the S6 gate, then threw it away. Now the
1897    // minted JWT carries it under the hybrid signature, so a downstream PEP
1898    // (ClaimsSubjectContextResolver, #1268/#1269) reads it from verified
1899    // Claims without re-resolving from the enrollment table. `None`
1900    // (unenrolled) ⇒ no claim ⇒ downstream deny (fail-closed).
1901    if let Some(clearance) = subject_clearance {
1902        claims = claims.with_clearance(clearance);
1903    }
1904
1905    // DPoP sender-binding via cnf.jkt (RFC 9449 §6). ZSP: no cnf ⇒ bearer ⇒
1906    // rejected. We set jkt directly from the verified proof.
1907    claims = claims.with_cnf_jkt_thumbprint(dpop_jkt.to_owned());
1908
1909    // S8 (#574) + Fu3/#677: sign via the mandatory hybrid composite (EdDSA +
1910    // ML-DSA-65). If no ML-DSA-65 signing key is provisioned, refuse to mint
1911    // rather than silently downgrade to a classical-only token — mirroring
1912    // `PolicyService::sign_token` and
1913    // `CoseAuditSigner`. The UCAN grant and approval this token was minted from
1914    // are already hybrid-signed, so a classical-only minted token would break
1915    // that chain of hybrid authority.
1916    let snapshot = match hyprstream_rpc::auth::global_composite_key_set().mint_snapshot() {
1917        Ok(snapshot) => snapshot,
1918        Err(error) => {
1919            tracing::error!("composite authority unavailable or stale; refusing to mint: {error}");
1920            return tx_error(
1921                StatusCode::INTERNAL_SERVER_ERROR,
1922                "server_error",
1923                "hybrid token authority is not current",
1924            );
1925        }
1926    };
1927    let signing = snapshot
1928        .active_signing_pair(hyprstream_rpc::auth::CompositePairRole::OAuth)
1929        .and_then(hyprstream_rpc::auth::CompositeKeyPair::signing_keys);
1930    let token = match signing {
1931        Some((pq, ed)) => crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(&claims, &pq, &ed),
1932        None => {
1933            tracing::error!(
1934                "no authorized active OAuth composite pair; refusing to mint (fail-closed)"
1935            );
1936            return tx_error(
1937                StatusCode::INTERNAL_SERVER_ERROR,
1938                "server_error",
1939                "hybrid token signing pair not provisioned",
1940            );
1941        }
1942    };
1943
1944    // Optional refresh token (ZSP: refresh re-runs evaluate_refresh, not a free
1945    // re-mint). Stored only when a token DB is configured. B1 (#673): the grant
1946    // re-evaluation context is persisted with the refresh token so the refresh
1947    // path re-presents the grant to the S6 gate chain.
1948    let refresh_token = if state.token_db.is_some() {
1949        Some(issue_grant_refresh_token(state, &sub, expires_at, grant_refresh).await)
1950    } else {
1951        None
1952    };
1953
1954    let mut body = serde_json::json!({
1955        "access_token": token,
1956        "issued_token_type": ISSUED_TOKEN_TYPE,
1957        "token_type": "DPoP", // sender-bound, not Bearer
1958        "expires_in": ttl,
1959    });
1960    if let Some(rt) = refresh_token {
1961        body["refresh_token"] = serde_json::Value::String(rt);
1962    }
1963
1964    tracing::info!(sub = %sub, ttl, "UCAN grant token minted (sender-bound, short-ttl)");
1965    (
1966        StatusCode::OK,
1967        [
1968            (header::CACHE_CONTROL, "no-store"),
1969            (header::PRAGMA, "no-cache"),
1970        ],
1971        Json(body),
1972    )
1973        .into_response()
1974}
1975
1976/// Issue an opaque refresh token for a UCAN grant, stored in the token DB.
1977///
1978/// The refresh token does NOT carry authority itself — it is a handle that lets
1979/// the presenter re-present the grant (which the refresh path re-validates via
1980/// `evaluate_refresh`). ZSP: refresh is re-evaluated, never automatic.
1981async fn issue_grant_refresh_token(
1982    state: &Arc<OAuthState>,
1983    sub: &str,
1984    access_expires_at: i64,
1985    grant_refresh: Option<super::state::UcanGrantRefresh>,
1986) -> String {
1987    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1988    use rand::RngCore as _;
1989
1990    // 256-bit opaque token.
1991    let mut bytes = [0u8; 32];
1992    rand::rngs::OsRng.fill_bytes(&mut bytes);
1993    let refresh = URL_SAFE_NO_PAD.encode(bytes);
1994
1995    // The verifying key binding for cnf continuity on refresh is re-established
1996    // by the re-presented DPoP proof at refresh time (jkt is a thumbprint, not
1997    // a raw key), so verifying_key_bytes stays None here.
1998    let _ = access_expires_at;
1999    let entry = super::state::RefreshTokenEntry {
2000        client_id: format!("ucan-grant:{sub}"),
2001        username: sub.to_owned(),
2002        scopes: vec!["urn:hyprstream:grant-type:ucan".to_owned()],
2003        resource: None,
2004        expires_at_unix: chrono::Utc::now().timestamp() + state.refresh_token_ttl as i64,
2005        verifying_key_bytes: None,
2006        dpop_jkt: None,
2007        client_assertion_jkt: None,
2008        ucan_grant: grant_refresh,
2009        session_id: None,
2010    };
2011
2012    if let Some(db) = &state.token_db {
2013        if let Err(e) = db
2014            .put(&refresh, &entry, state.refresh_token_ttl as u64)
2015            .await
2016        {
2017            tracing::warn!(error = %e, "failed to persist UCAN grant refresh token");
2018        }
2019    }
2020    refresh
2021}
2022
2023#[cfg(test)]
2024#[allow(clippy::unwrap_used, clippy::expect_used)]
2025mod tests {
2026    //! S8 (#574) activation tests for the concrete `SubjectContextResolver`.
2027    //! These cover the two input MAC context derivation (clearance from Claims
2028    //! plus assurance from verified key material) and the fail closed
2029    //! properties: anti borrow, classical key on PQ object denial, and
2030    //! unlabeled denial.
2031    use super::*;
2032    use hyprstream_rpc::auth::mac::{
2033        Assurance, CompartmentSet, Level, SecurityLabel, VerifiedKeyMaterial,
2034    };
2035
2036    #[test]
2037    fn atproto_ecdsa_accepts_p256_and_secp256k1_multikeys() {
2038        use p256::ecdsa::signature::Signer as _;
2039
2040        let message = b"header.payload";
2041        let p256_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
2042        let mut p256_multikey = vec![0x80, 0x24];
2043        p256_multikey.extend_from_slice(p256_key.verifying_key().to_encoded_point(true).as_bytes());
2044        let p256_signature: p256::ecdsa::Signature = p256_key.sign(message);
2045        verify_atproto_ecdsa(
2046            "ES256",
2047            &format!("z{}", bs58::encode(p256_multikey).into_string()),
2048            message,
2049            &URL_SAFE_NO_PAD.encode(p256_signature.to_bytes()),
2050        )
2051        .unwrap();
2052
2053        let k256_key = k256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
2054        let mut k256_multikey = vec![0xe7, 0x01];
2055        k256_multikey.extend_from_slice(k256_key.verifying_key().to_encoded_point(true).as_bytes());
2056        let k256_signature: k256::ecdsa::Signature = k256_key.sign(message);
2057        verify_atproto_ecdsa(
2058            "ES256K",
2059            &format!("z{}", bs58::encode(k256_multikey).into_string()),
2060            message,
2061            &URL_SAFE_NO_PAD.encode(k256_signature.to_bytes()),
2062        )
2063        .unwrap();
2064    }
2065
2066    #[test]
2067    fn federate_tui_class_is_never_a_generic_exchange_subject() {
2068        let issuer = "https://cell.test";
2069        // Marker path: any TUI marker classifies, regardless of the global
2070        // reservation.
2071        let mut claims = hyprstream_rpc::auth::Claims::new("did:plc:abc".into(), 1, 2);
2072        claims.iss = issuer.into();
2073        claims.client_id = Some("anything".into());
2074        assert!(reject_federate_tui_exchange_subject(&claims, issuer).is_ok());
2075        claims.hs_tui_profile = Some("federate-tui-v1".into());
2076        assert!(reject_federate_tui_exchange_subject(&claims, issuer).is_err());
2077
2078        // Pin path: the deployment reservation classifies by
2079        // (local iss, configured client id) even with markers stripped.
2080        // The reservation is process-global and install-once; no other test
2081        // in this process installs it, and no other test uses this client id.
2082        if hyprstream_rpc::auth::federate_tui_class_client().is_none() {
2083            hyprstream_rpc::auth::install_federate_tui_class_client(Some("hyprstream-tui-staging"))
2084                .expect("install class reservation");
2085        }
2086        let mut pinned = hyprstream_rpc::auth::Claims::new("did:plc:abc".into(), 1, 2);
2087        pinned.iss = issuer.into();
2088        pinned.client_id = Some("hyprstream-tui-staging".into());
2089        assert!(reject_federate_tui_exchange_subject(&pinned, issuer).is_err());
2090        // A foreign issuer with the reserved client id is NOT classified.
2091        pinned.iss = "https://other.example".into();
2092        assert!(reject_federate_tui_exchange_subject(&pinned, issuer).is_ok());
2093    }
2094
2095    #[test]
2096    fn exchange_tenant_requires_verified_local_binding() {
2097        let local_subject = VerifiedSubject {
2098            sub: "did:plc:abcdefghijklmnqrstuvwx2p".to_owned(),
2099            cnf_key_bytes: None,
2100            cnf_jkt: None,
2101            iat: 1,
2102            granted_scopes: None,
2103            verified_tenant: Some("tenant-source".to_owned()),
2104            atproto_replay: None,
2105            require_clearance: false,
2106            ttl_ceiling: None,
2107        };
2108        assert_eq!(
2109            exchange_tenant(&local_subject, None).unwrap().as_deref(),
2110            Some("tenant-source")
2111        );
2112        assert_eq!(
2113            exchange_tenant(&local_subject, Some("tenant-source"))
2114                .unwrap()
2115                .as_deref(),
2116            Some("tenant-source")
2117        );
2118        assert!(exchange_tenant(&local_subject, Some("tenant-other")).is_err());
2119
2120        let external_enrolled_subject = VerifiedSubject {
2121            sub: "did:plc:externalenrolledsubject".to_owned(),
2122            cnf_key_bytes: None,
2123            cnf_jkt: None,
2124            iat: 1,
2125            granted_scopes: Some(vec!["transition:generic".to_owned()]),
2126            verified_tenant: None,
2127            atproto_replay: None,
2128            require_clearance: true,
2129            ttl_ceiling: Some(MAX_ATPROTO_EXCHANGE_TOKEN_TTL),
2130        };
2131        assert_eq!(
2132            exchange_tenant(&external_enrolled_subject, Some("tenant-foreign")),
2133            Err("subject token has no verified local tenant binding"),
2134            "an enrolled external DID cannot turn a client assertion into a local tenant binding"
2135        );
2136    }
2137
2138    fn mint_test_state() -> Arc<OAuthState> {
2139        use crate::config::OAuthConfig;
2140        use hyprstream_rpc::rpc_client::RpcClientImpl;
2141        use hyprstream_rpc::signer::LocalSigner;
2142        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
2143        use hyprstream_rpc_std::discovery_client::DiscoveryClient;
2144        use hyprstream_rpc_std::policy_client::PolicyClient;
2145
2146        let key = ed25519_dalek::SigningKey::from_bytes(&[0x65; 32]);
2147        let dummy = std::path::PathBuf::from("/dev/null/path-form-mint-test.sock");
2148        let mk_client = || {
2149            Arc::new(
2150                RpcClientImpl::new(
2151                    LocalSigner::new(key.clone()),
2152                    LazyUdsTransport::new(dummy.clone()),
2153                    Some(key.verifying_key()),
2154                )
2155                .with_response_verify_policy(hyprstream_rpc::crypto::CryptoPolicy::Classical),
2156            )
2157        };
2158        Arc::new(OAuthState::new(
2159            &OAuthConfig::default(),
2160            PolicyClient::new(mk_client()),
2161            DiscoveryClient::new(mk_client()),
2162            key.verifying_key().to_bytes(),
2163        ))
2164    }
2165
2166    #[tokio::test]
2167    async fn ucan_mint_rejects_path_form_subject_before_signing() {
2168        use hyprstream_rpc::auth::ucan::{Ability, Capability, Resource};
2169
2170        let granted = GrantedAccess {
2171            capability: Capability::new(Resource::new("mac://model/demo"), Ability::new("read")),
2172            audience: None,
2173        };
2174        let response = mint_grant_token(
2175            &mint_test_state(),
2176            &granted,
2177            "test-dpop-jkt",
2178            None,
2179            TokenPrincipals {
2180                sub: "did:web:accounts.example:users:alice".to_owned(),
2181                act: None,
2182            },
2183            // No clearance — this test checks the path-form freeze, not MAC.
2184            None,
2185        )
2186        .await;
2187
2188        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
2189        let body = axum::body::to_bytes(response.into_body(), 4096)
2190            .await
2191            .unwrap();
2192        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2193        assert_eq!(value["error"].as_str(), Some("invalid_grant"));
2194        assert!(value["error_description"]
2195            .as_str()
2196            .unwrap()
2197            .contains("frozen"));
2198        assert!(value.get("access_token").is_none());
2199        assert!(value.get("refresh_token").is_none());
2200    }
2201
2202    /// A compartment bitset from bit indices.
2203    fn comps(bits: &[u32]) -> CompartmentSet {
2204        bits.iter().copied().collect()
2205    }
2206
2207    /// A PqHybrid-cleared subject mints a context whose assurance is PqHybrid.
2208    /// This is the activation: a fully-verified PQ subject gets a real context,
2209    /// not a denial.
2210    #[test]
2211    fn pqhybrid_subject_resolves_to_pqhybrid_context() {
2212        let did = "did:key:z6MkpTHR8VNsBxYAAHWutMGeQ4hz2FV6B14xd9CZpkmS5i5o";
2213        let clearance = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, comps(&[0, 1]));
2214        let claims =
2215            hyprstream_rpc::auth::Claims::new("sub".to_owned(), 1, 2).with_clearance(clearance);
2216        let resolver =
2217            ClaimsSubjectContextResolver::new(did, claims, VerifiedKeyMaterial::PqHybrid);
2218
2219        let ctx = resolver.resolve(did).expect("PqHybrid subject resolves");
2220        assert_eq!(ctx.assurance(), Assurance::PqHybrid);
2221        assert_eq!(ctx.level(), Level::Secret);
2222    }
2223
2224    /// Anti-borrow: a grant whose audience DID differs from the one the
2225    /// clearance was issued to MUST be denied (`None`). The clearance cannot
2226    /// cross identities.
2227    #[test]
2228    fn resolver_denies_mismatched_audience_did() {
2229        let owner = "did:key:z6MkpTHR8VNsBxYAAHWutMGeQ4hz2FV6B14xd9CZpkmS5i5o";
2230        let impostor = "did:key:z6MkmFpYUWaBjIA4ZJarQtz5FaGGCLpJ4xjXQqRuV4Dx4q6P";
2231        let clearance =
2232            SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY);
2233        let claims =
2234            hyprstream_rpc::auth::Claims::new("sub".to_owned(), 1, 2).with_clearance(clearance);
2235        let resolver =
2236            ClaimsSubjectContextResolver::new(owner, claims, VerifiedKeyMaterial::PqHybrid);
2237
2238        assert!(
2239            resolver.resolve(impostor).is_none(),
2240            "a grant for a different audience MUST NOT borrow this subject's clearance"
2241        );
2242    }
2243
2244    /// **Fail-closed (the #548 invariant at the resolver):** a Classical-key
2245    /// subject carrying a PqHybrid clearance MUST clamp to Classical assurance.
2246    /// The resolver does not grant assurance the key does not back.
2247    #[test]
2248    fn classical_key_clamps_pqhybrid_clearance_down() {
2249        let did = "did:key:z6MkpTHR8VNsBxYAAHWutMGeQ4hz2FV6B14xd9CZpkmS5i5o";
2250        // Policy mistakenly assigned PqHybrid...
2251        let claimed = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY);
2252        let claims =
2253            hyprstream_rpc::auth::Claims::new("sub".to_owned(), 1, 2).with_clearance(claimed);
2254        // ...but the verified key is Classical:
2255        let resolver =
2256            ClaimsSubjectContextResolver::new(did, claims, VerifiedKeyMaterial::Classical);
2257
2258        let ctx = resolver.resolve(did).expect("labeled subject resolves");
2259        assert_eq!(
2260            ctx.assurance(),
2261            Assurance::Classical,
2262            "Classical key must clamp a PqHybrid clearance down (no silent upgrade)"
2263        );
2264
2265        // Consequently the MAC floor DENIES a PqHybrid object.
2266        let pq_object =
2267            SecurityLabel::new(Level::Public, Assurance::PqHybrid, CompartmentSet::EMPTY);
2268        assert!(
2269            !ctx.can_access(&pq_object),
2270            "Classical-assurance subject MUST be denied on a PqHybrid object (fail-closed)"
2271        );
2272    }
2273
2274    /// A subject with no clearance claim ⇒ `None` ⇒ the S1 monitor denies.
2275    #[test]
2276    fn unlabeled_subject_resolves_to_none() {
2277        let did = "did:key:z6MkpTHR8VNsBxYAAHWutMGeQ4hz2FV6B14xd9CZpkmS5i5o";
2278        // No `with_clearance` ⇒ no clearance field.
2279        let claims = hyprstream_rpc::auth::Claims::new("sub".to_owned(), 1, 2);
2280        let resolver =
2281            ClaimsSubjectContextResolver::new(did, claims, VerifiedKeyMaterial::PqHybrid);
2282
2283        assert!(
2284            resolver.resolve(did).is_none(),
2285            "unlabeled subject MUST resolve to None (S1 deny)"
2286        );
2287    }
2288
2289    /// `DenyUnlabeledResolver` remains the explicit deny-by-default choice.
2290    #[test]
2291    fn deny_unlabeled_resolver_always_denies() {
2292        let r = DenyUnlabeledResolver;
2293        assert!(r.resolve("did:key:anything").is_none());
2294    }
2295
2296    // ── #698: issuer path — enrollment → Claims.clearance → PEP resolver ────
2297    //
2298    // These tests prove the issuer path contract: the clearance the
2299    // enrollment resolver derives gets stamped on Claims (via
2300    // `with_clearance`, as `mint_grant_token` now does) and is readable by
2301    // the downstream `ClaimsSubjectContextResolver` the #1268/#1269 PEP lanes
2302    // consume. They exercise the real types end-to-end without the JWT signing
2303    // infrastructure (which is orthogonal — the Claims construction is what
2304    // carries the clearance, and it happens before signing).
2305
2306    use crate::mac::{CompiledPolicy, EnrollmentSubjectContextResolver, TeMatrix};
2307    use hyprstream_rpc::auth::mac::{Lattice as LatticeType, LatticeVersion};
2308    use std::collections::BTreeMap;
2309    use std::sync::Arc;
2310
2311    /// Build a compiled policy with one enrolled DID at the given clearance.
2312    fn policy_with_enrollment(did: &str, clearance: SecurityLabel) -> Arc<CompiledPolicy> {
2313        let lattice = LatticeType::new(LatticeVersion(1), []);
2314        let policy = CompiledPolicy::new(TeMatrix::default(), &lattice)
2315            .with_enrollment(BTreeMap::from([(did.to_owned(), clearance)]));
2316        Arc::new(policy)
2317    }
2318
2319    /// **Issuer path round-trip (happy path):** an enrolled DID resolves to a
2320    /// clearance via `EnrollmentSubjectContextResolver`, the issuer stamps it
2321    /// on Claims (exactly as `mint_grant_token` now does via `with_clearance`),
2322    /// and the downstream `ClaimsSubjectContextResolver` reads it back with the
2323    /// correct level and compartments. This is the full provenance chain the PEP
2324    /// lanes depend on.
2325    #[test]
2326    fn issuer_path_stamps_clearance_readable_by_pep_resolver() {
2327        let did = "did:key:z6MkpTHR8VNsBxYAAHWutMGeQ4hz2FV6B14xd9CZpkmS5i5o";
2328        let enrolled = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, comps(&[0, 1]));
2329
2330        // Step 1: enrollment resolver derives the clearance (what the grant
2331        // path does via `exchange_enrollment_resolver()`).
2332        let resolver = EnrollmentSubjectContextResolver::new(policy_with_enrollment(did, enrolled));
2333        let ctx = resolver
2334            .resolve(did)
2335            .expect("enrolled DID must resolve to a SecurityContext");
2336        let clearance = *ctx.clearance();
2337
2338        // Step 2: issuer stamps it on Claims (what `mint_grant_token` now does
2339        // via `claims.with_clearance(clearance)`).
2340        let claims =
2341            hyprstream_rpc::auth::Claims::new(did.to_owned(), 1, 9999).with_clearance(clearance);
2342
2343        // Step 3: downstream PEP resolver reads it back from verified Claims.
2344        let pep_resolver =
2345            ClaimsSubjectContextResolver::new(did, claims, VerifiedKeyMaterial::Classical);
2346        let pep_ctx = pep_resolver
2347            .resolve(did)
2348            .expect("PEP resolver must read the stamped clearance");
2349
2350        // The level + compartments survive the round-trip.
2351        assert_eq!(pep_ctx.level(), Level::Secret);
2352        assert_eq!(pep_ctx.compartments(), comps(&[0, 1]));
2353        // Decision D: assurance is Classical (the resolver floored it).
2354        assert_eq!(pep_ctx.assurance(), Assurance::Classical);
2355    }
2356
2357    /// **Issuer path fail-closed:** an unenrolled DID resolves to `None` at the
2358    /// enrollment resolver, so the issuer passes `None` to `mint_grant_token`,
2359    /// so no clearance is stamped on Claims, so the downstream PEP resolver
2360    /// returns `None` → deny. This is the fail-closed chain the whole MAC model
2361    /// depends on.
2362    #[test]
2363    fn issuer_path_unenrolled_did_produces_no_clearance_pep_denies() {
2364        let enrolled_did = "did:key:z6MkpTHR8VNsBxYAAHWutMGeQ4hz2FV6B14xd9CZpkmS5i5o";
2365        let stranger = "did:key:z6MkmFpYUWaBjIA4ZJarQtz5FaGGCLpJ4xjXQqRuV4Dx4q6P";
2366        let clearance =
2367            SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY);
2368
2369        // The enrollment table only knows `enrolled_did`.
2370        let resolver =
2371            EnrollmentSubjectContextResolver::new(policy_with_enrollment(enrolled_did, clearance));
2372
2373        // The stranger is NOT enrolled → None (fail-closed at the resolver).
2374        assert!(
2375            resolver.resolve(stranger).is_none(),
2376            "unenrolled DID must not resolve to a clearance"
2377        );
2378
2379        // The issuer has no clearance to stamp (None) → Claims carry no clearance.
2380        let claims = hyprstream_rpc::auth::Claims::new(stranger.to_owned(), 1, 9999);
2381        assert!(
2382            claims.clearance.is_none(),
2383            "no clearance stamped for an unenrolled subject"
2384        );
2385
2386        // The downstream PEP resolver denies.
2387        let pep_resolver =
2388            ClaimsSubjectContextResolver::new(stranger, claims, VerifiedKeyMaterial::PqHybrid);
2389        assert!(
2390            pep_resolver.resolve(stranger).is_none(),
2391            "PEP resolver MUST deny a subject with no stamped clearance"
2392        );
2393    }
2394
2395    /// **Delegated grant — met clearance is what gets stamped:** for a delegated
2396    /// grant, `resolve_grant_subject` takes `meet(delegator, actor)`. The
2397    /// clearance stamped on the minted token is the MET clearance (the
2398    /// effective one), not the delegator's higher one — so the downstream PEP
2399    /// sees the least-privilege label.
2400    #[test]
2401    fn issuer_path_stamps_met_clearance_not_delegator_higher() {
2402        let mcp_did = "did:key:zMcp".to_owned();
2403
2404        // Delegator: Secret / {0,1}. Actor: Confidential / {1}.
2405        // meet = Confidential / {1}.
2406        let user_clearance =
2407            SecurityLabel::new(Level::Secret, Assurance::Classical, comps(&[0, 1]));
2408        let mcp_clearance =
2409            SecurityLabel::new(Level::Confidential, Assurance::Classical, comps(&[1]));
2410
2411        // Both enrolled in their own resolver (simulating two enrollment entries).
2412        let user_ctx =
2413            SecurityContext::from_clearance(user_clearance, VerifiedKeyMaterial::Classical);
2414        let mcp_ctx =
2415            SecurityContext::from_clearance(mcp_clearance, VerifiedKeyMaterial::Classical);
2416        let met = SecurityContext::delegated(Some(&user_ctx), Some(&mcp_ctx))
2417            .expect("both principals resolved");
2418
2419        // The issuer stamps the MET clearance (what `exchange_ucan_grant`
2420        // passes as `subject_ctx.clearance()` to `mint_grant_token`).
2421        let stamped = *met.clearance();
2422        let claims =
2423            hyprstream_rpc::auth::Claims::new(mcp_did.clone(), 1, 9999).with_clearance(stamped);
2424
2425        // The PEP resolver reads it back.
2426        let pep_resolver =
2427            ClaimsSubjectContextResolver::new(&mcp_did, claims, VerifiedKeyMaterial::Classical);
2428        let pep_ctx = pep_resolver
2429            .resolve(&mcp_did)
2430            .expect("met clearance resolves");
2431
2432        // It's the meet (Confidential / {1}), NOT the delegator's Secret / {0,1}.
2433        assert_eq!(
2434            pep_ctx.level(),
2435            Level::Confidential,
2436            "met level, not delegator's"
2437        );
2438        assert_eq!(
2439            pep_ctx.compartments(),
2440            comps(&[1]),
2441            "met compartments, not delegator's"
2442        );
2443    }
2444
2445    /// B1 (#673): a persisted refresh token from BEFORE this field existed (no
2446    /// `ucan_grant` key) MUST still deserialize — as `None` — so existing stored
2447    /// tokens keep working and are simply treated as generic (non-UCAN-grant)
2448    /// refresh tokens. Guards the `#[serde(default)]` on the new field.
2449    #[test]
2450    fn refresh_entry_without_ucan_grant_field_deserializes_as_none() {
2451        let legacy = r#"{
2452            "client_id": "abc",
2453            "username": "alice",
2454            "scopes": ["openid"],
2455            "resource": null,
2456            "expires_at_unix": 9999999999,
2457            "verifying_key_bytes": null
2458        }"#;
2459        let entry: super::super::state::RefreshTokenEntry =
2460            serde_json::from_str(legacy).expect("legacy refresh entry must still deserialize");
2461        assert!(
2462            entry.ucan_grant.is_none(),
2463            "a legacy entry is a generic refresh token, never a UCAN grant"
2464        );
2465    }
2466
2467    /// B1 (#673): a UCAN-grant refresh entry round-trips through serde with its
2468    /// re-evaluation context intact — the grant blob, its content id, and the
2469    /// requested access the refresh path re-presents to `evaluate_refresh`.
2470    #[test]
2471    fn ucan_grant_refresh_entry_roundtrips() {
2472        let entry = super::super::state::RefreshTokenEntry {
2473            client_id: "ucan-grant:did:key:zAlice".to_owned(),
2474            username: "did:key:zAlice".to_owned(),
2475            scopes: vec!["urn:hyprstream:grant-type:ucan".to_owned()],
2476            resource: None,
2477            expires_at_unix: 9999999999,
2478            verifying_key_bytes: None,
2479            dpop_jkt: None,
2480            client_assertion_jkt: None,
2481            ucan_grant: Some(super::super::state::UcanGrantRefresh {
2482                grant_cbor_b64: "Zm9vYmFy".to_owned(),
2483                grant_cid: blake3::hash(b"the-grant").to_hex().to_string(),
2484                requested_scope: Some("read:model:llama".to_owned()),
2485                audience: Some("https://api.example".to_owned()),
2486            }),
2487            session_id: None,
2488        };
2489        let json = serde_json::to_string(&entry).unwrap();
2490        let back: super::super::state::RefreshTokenEntry = serde_json::from_str(&json).unwrap();
2491        let ug = back.ucan_grant.expect("ucan_grant survives round-trip");
2492        assert_eq!(ug.grant_cbor_b64, "Zm9vYmFy");
2493        assert_eq!(
2494            ug.grant_cid,
2495            blake3::hash(b"the-grant").to_hex().to_string()
2496        );
2497        assert_eq!(ug.requested_scope.as_deref(), Some("read:model:llama"));
2498    }
2499
2500    // ── #680/#681: two-principal delegated grant derivation ─────────────────
2501
2502    use hyprstream_rpc::auth::mac::SecurityContext;
2503    use hyprstream_rpc::auth::ucan::token::{Did, Ucan, UcanPayload};
2504    use std::collections::HashMap;
2505
2506    fn did(seed: u8) -> Did {
2507        Did::from_ed25519(&[seed; 32])
2508    }
2509
2510    /// A minimal UCAN (payload only; `resolve_grant_subject` reads
2511    /// `audience()`/`root_issuer()` off the structure, not the signature).
2512    fn ucan(issuer: Did, audience: Did, proofs: Vec<Ucan>) -> Ucan {
2513        Ucan {
2514            payload: UcanPayload {
2515                issuer,
2516                audience,
2517                capabilities: vec![],
2518                not_before: None,
2519                expiration: Some(9_999_999_999),
2520                nonce: vec![],
2521            },
2522            proofs,
2523            signature: vec![],
2524        }
2525    }
2526
2527    fn ctx(level: Level, bits: &[u32], km: VerifiedKeyMaterial) -> SecurityContext {
2528        SecurityContext::new(level, comps(bits), km)
2529    }
2530
2531    /// A resolver that maps specific DIDs to contexts; everything else `None`.
2532    struct MapResolver(HashMap<String, SecurityContext>);
2533    impl SubjectContextResolver for MapResolver {
2534        fn resolve(&self, did: &str) -> Option<SecurityContext> {
2535            self.0.get(did).cloned()
2536        }
2537    }
2538
2539    /// A self-issued root grant (issuer == audience) is single-principal: `sub`
2540    /// is the subject, no `act`, and the context is a plain `resolve(audience)`.
2541    #[test]
2542    fn root_grant_is_single_principal() {
2543        let subject = did(1);
2544        let subject_did = subject.as_str().to_owned();
2545        let grant = ucan(subject.clone(), subject, vec![]);
2546        let resolver = MapResolver(HashMap::from([(
2547            subject_did.clone(),
2548            ctx(Level::Secret, &[0], VerifiedKeyMaterial::PqHybrid),
2549        )]));
2550
2551        let ResolvedGrantSubject {
2552            subject: context,
2553            on_behalf_of,
2554            principals,
2555        } = resolve_grant_subject(&grant, &resolver);
2556        assert!(principals.act.is_none(), "root grant has no actor");
2557        assert!(
2558            on_behalf_of.is_none(),
2559            "a single-principal grant records no delegator (audit on_behalf_of = None)"
2560        );
2561        assert_eq!(principals.sub, subject_did);
2562        assert_eq!(context.map(|c| c.level()), Some(Level::Secret));
2563    }
2564
2565    /// A delegated grant (root issuer ≠ audience) splits into delegator (`sub`)
2566    /// and actor (`act`), and the derived context is the fail-closed
2567    /// `meet(delegator, actor)` — never either principal alone (#681).
2568    #[test]
2569    fn delegated_grant_splits_principals_and_meets() {
2570        let user = did(2); // delegator / source of authority
2571        let mcp = did(3); // actor / presenter
2572        let user_did = user.as_str().to_owned();
2573        let mcp_did = mcp.as_str().to_owned();
2574        // user delegates directly to mcp (issuer=user, audience=mcp).
2575        let grant = ucan(user, mcp, vec![]);
2576        let resolver = MapResolver(HashMap::from([
2577            // delegator: Secret / {0,1}
2578            (
2579                user_did.clone(),
2580                ctx(Level::Secret, &[0, 1], VerifiedKeyMaterial::PqHybrid),
2581            ),
2582            // actor: Confidential / {1,2}
2583            (
2584                mcp_did.clone(),
2585                ctx(Level::Confidential, &[1, 2], VerifiedKeyMaterial::PqHybrid),
2586            ),
2587        ]));
2588
2589        let ResolvedGrantSubject {
2590            subject: context,
2591            on_behalf_of,
2592            principals,
2593        } = resolve_grant_subject(&grant, &resolver);
2594        assert_eq!(principals.sub, user_did, "sub is the delegator");
2595        let act = principals.act.expect("delegation carries an actor");
2596        assert_eq!(act.sub, mcp_did, "act is the actor");
2597        // meet = min level (Confidential) ∩ compartments ({1}).
2598        let context = context.expect("both principals resolved ⇒ Some");
2599        assert_eq!(context.level(), Level::Confidential, "min level");
2600        assert_eq!(
2601            context.compartments(),
2602            comps(&[1]),
2603            "compartment intersection"
2604        );
2605        // The audit `on_behalf_of` carries the DELEGATOR (the user's own
2606        // clearance), distinct from the met `subject` context above — this is
2607        // the two-principal attribution (#445/#681): the met context is what the
2608        // gates saw, the delegator is who the actor acted for.
2609        let obo = on_behalf_of.expect("a delegated grant records its delegator");
2610        assert_eq!(
2611            obo.level(),
2612            Level::Secret,
2613            "on_behalf_of is the delegator's own level"
2614        );
2615        assert_eq!(
2616            obo.compartments(),
2617            comps(&[0, 1]),
2618            "on_behalf_of is the delegator's own compartments, not the meet"
2619        );
2620    }
2621
2622    /// The delegated derivation fails closed if EITHER principal is unresolved
2623    /// — no default clearance for a missing principal (#681 AC).
2624    #[test]
2625    fn delegated_grant_fails_closed_if_either_principal_unresolved() {
2626        let user = did(4);
2627        let mcp = did(5);
2628        let user_did = user.as_str().to_owned();
2629        let grant = ucan(user, mcp, vec![]);
2630        // Only the delegator resolves; the actor does not.
2631        let resolver = MapResolver(HashMap::from([(
2632            user_did,
2633            ctx(Level::Secret, &[0], VerifiedKeyMaterial::PqHybrid),
2634        )]));
2635
2636        let ResolvedGrantSubject {
2637            subject: context,
2638            on_behalf_of,
2639            principals,
2640        } = resolve_grant_subject(&grant, &resolver);
2641        assert!(
2642            context.is_none(),
2643            "missing actor clearance ⇒ deny (no default clearance)"
2644        );
2645        // The principal split is still reported (the actor clearance is None),
2646        // but the None context makes evaluate_grant deny before any mint.
2647        assert!(principals.act.is_some());
2648        // The delegator resolved, so it is still available for audit even though
2649        // the decision itself fails closed on the unresolved actor.
2650        assert!(
2651            on_behalf_of.is_some(),
2652            "the resolved delegator is still recorded"
2653        );
2654    }
2655
2656    /// Multi-hop delegation roots the delegator at the CHAIN ROOT issuer, not
2657    /// the nearest hop (RFC 8693 §4.1 — authority flows from the root).
2658    #[test]
2659    fn multihop_delegation_roots_at_chain_root() {
2660        let user = did(6); // ultimate authority (chain root)
2661        let intermediate = did(7);
2662        let mcp = did(8); // final presenter
2663        let root_proof = ucan(user.clone(), intermediate.clone(), vec![]);
2664        let leaf = ucan(intermediate, mcp.clone(), vec![root_proof]);
2665
2666        // No clearances resolved — we only assert the principal identities.
2667        let resolver = MapResolver(HashMap::new());
2668        let ResolvedGrantSubject {
2669            on_behalf_of,
2670            principals,
2671            ..
2672        } = resolve_grant_subject(&leaf, &resolver);
2673        assert!(
2674            on_behalf_of.is_none(),
2675            "no clearance resolved ⇒ no delegator context (fails closed on subject anyway)"
2676        );
2677        assert_eq!(
2678            principals.sub,
2679            user.as_str(),
2680            "delegator is the chain-root issuer, not the intermediate"
2681        );
2682        assert_eq!(
2683            principals.act.expect("delegation").sub,
2684            mcp.as_str(),
2685            "actor is the final audience/presenter"
2686        );
2687    }
2688}