Skip to main content

hyprstream_rpc/auth/
claims.rs

1//! JWT claims for authentication.
2//!
3//! Two claim types:
4//! - [`Claims`] — access token claims used throughout the RPC layer.
5//!   OAuth grants carry their granted scope set in the signed JWT so consumers
6//!   can attenuate authority without falling back to subject-wide policy.
7//! - [`IdTokenClaims`] — OIDC ID Token claims (Section 2 of OpenID Connect
8//!   Core 1.0). Only used by the OAuth token endpoint when `scope=openid`.
9
10use crate::capnp::{FromCapnp, ToCapnp};
11use crate::common_capnp;
12use crate::identity::UNAUTHENTICATED_DID_SENTINEL;
13use anyhow::Result;
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15
16/// Compute the RFC 7638 JWK Thumbprint for an Ed25519 key.
17///
18/// Delegates to [`crate::auth::jwk_thumbprint`] — kept as a named entry-point
19/// so callers that only have a raw `[u8; 32]` don't need to construct a
20/// [`crate::auth::JwkThumbprintInput`] themselves. (#155 cleanup)
21pub fn compute_jkt(key_bytes: &[u8; 32]) -> String {
22    crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Ed25519 { x: key_bytes })
23}
24
25/// Returns true if `iss` belongs to a local node.
26///
27/// Used for pre-decode key routing (before a `Claims` object exists) and by
28/// [`Claims::is_local_to`] for post-decode subject derivation — both use
29/// identical criteria so routing and subject resolution are always consistent.
30///
31/// Rules:
32/// - Empty `iss` is always local (cluster-internal tokens have no issuer claim).
33/// - If `local_issuers` is non-empty: `iss` must exactly match one entry.
34/// - If `local_issuers` is empty (unconfigured node): only an empty `iss` is
35///   accepted as local; any non-empty `iss` is treated as federated.
36pub fn is_local_iss(iss: &str, local_issuers: &[&str]) -> bool {
37    if iss.is_empty() {
38        return true;
39    }
40    if local_issuers.is_empty() {
41        false
42    } else {
43        local_issuers.contains(&iss)
44    }
45}
46
47/// JWK (JSON Web Key) for an Ed25519 public key — RFC 7517 OKP key type.
48#[derive(Clone, Debug, Default, Serialize, Deserialize)]
49pub struct CnfJwk {
50    pub kty: String,
51    pub crv: String,
52    /// Base64url-encoded Ed25519 public key (32 bytes), RFC 8037 §2.
53    pub x: String,
54}
55
56/// RFC 8705 / RFC 8747 Proof-of-Possession `cnf` claim.
57///
58/// Key-binding modes:
59/// - `jwk`: Full OKP JWK object — legacy single-Ed25519 binding (`cnf.jwk`).
60/// - `jkt`: JWK Thumbprint (RFC 7638 SHA-256, base64url) — DPoP user tokens
61///   (`cnf.jkt`, per RFC 9449 § 6).
62/// - `hs_signer_suite`: the generic v16 signer-suite content thumbprint (frozen WS-A
63///   credential-profile §1.1/§5) — base64url(SHA-256(det-CBOR `[suite_id,
64///   [ordered raw component public keys]]`)). In the frozen generic v16 profile,
65///   this is the ONLY confirmation method for a **hybrid** (multi-key) primary
66///   signer group; it also covers a classical (single-key) group. A generic v16
67///   dispatch credential MUST
68///   carry it. Computed via [`crate::auth::signer_suite_thumbprint`] — the one
69///   shared helper mint (WS-B) and verify (WS-C) both use. Legacy `jwk`/`jkt`
70///   are preserved ALONGSIDE it where those protocols still require them; adding
71///   `hs_signer_suite` never overwrites them. The opt-in Federate subprofile
72///   instead has one `cnf.jwk` key and a top-level `hs_signer_suite_v1` digest.
73///
74/// All fields are optional so the struct serialises correctly for each mode.
75#[derive(Clone, Debug, Default, Serialize, Deserialize)]
76pub struct Cnf {
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub jwk: Option<CnfJwk>,
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub jkt: Option<String>,
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub hs_signer_suite: Option<String>,
83}
84
85/// RFC 8693 §4.1 actor claim — the two-principal carrier for delegated calls
86/// (#680/#681).
87///
88/// A delegated (on-behalf-of) token sets [`Claims::sub`] = the **delegator**
89/// (source of authority, e.g. the user) and [`Claims::act`] = the **actor** that
90/// signs the downstream envelope (e.g. `service:mcp`). This is delegation, not
91/// impersonation: the actor holds no standing access, only the attenuated
92/// authority the delegator granted it.
93///
94/// **Composition (#681):** the effective MAC clearance is `meet(delegator,
95/// actor)` on level/compartments — never either principal alone. The actor's
96/// authority-asserted clearance is carried here so the PDP can take the meet off
97/// the one verified JWT. Like [`Claims::clearance`] it is *authority-asserted*
98/// (the issuing node signs the JWT) and carries **no** assurance: assurance is
99/// derived from the *verified signer* (the actor, who signs the downstream
100/// envelope) and clamped DOWN at enforcement time — never trusted from this claim.
101///
102/// `act` MAY nest (`act.act`) for multi-hop delegation (RFC 8693 §4.1); each hop
103/// composes into the meet. **JWT-carried only** (mirrors [`Claims::clearance`]):
104/// not written to the Cap'n Proto envelope surface — read off the verified JWT by
105/// the MAC PDP.
106#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
107pub struct ActClaim {
108    /// The actor's subject identifier (e.g. `service:mcp`). At enforcement time
109    /// this MUST equal the verified downstream envelope signer (`cnf`): an actor
110    /// cannot claim to act as an identity whose key it does not hold — the
111    /// #680 anti-confused-deputy invariant.
112    pub sub: String,
113    /// The actor's authority-asserted MAC clearance, carried so #681 can take
114    /// `meet(delegator, actor)` without a second lookup. `None` ⇒ the actor is
115    /// unlabeled ⇒ the delegated derivation **fails closed** (no default
116    /// clearance for a missing principal; the S1 rule).
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub clearance: Option<crate::auth::mac::CredentialClearance>,
119    /// Nested actor for multi-hop delegation (RFC 8693 §4.1). Boxed to keep
120    /// [`Claims`] sized. Each hop composes into the clearance meet.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub act: Option<Box<ActClaim>>,
123}
124
125// v16 credentials are Reusable-only. The `OneShotTransaction` credential-use
126// profile and its atomic consume-(iss,cti) path were CUT from v16 scope
127// (operator decision `DECISION-defer-oneshot-credentials-2026-08-20`); if
128// exactly-once mutation semantics are needed later they return as a scoped
129// future amendment with its own claim allocation and review. Absence of any
130// use-profile == Reusable, so no field is carried.
131
132/// JWT claims for authentication.
133///
134/// Casbin remains the server-side policy authority. OAuth access tokens also
135/// carry the grant's scope ceiling so a verifier can enforce the intersection
136/// of subject policy and the authority delegated by that specific grant.
137#[derive(Clone, Serialize, Deserialize)]
138pub struct Claims {
139    /// Issuer URL — the hyprstream node that minted this token.
140    /// Matches the OAuth issuer URL (e.g. "https://cloud-a.example.com").
141    /// Required for federation: receiving nodes use this to fetch JWKS.
142    /// Defaults to empty string for backward compat (treated as local-only).
143    #[serde(default)]
144    pub iss: String,
145    pub sub: String,
146    /// Verified tenant/Casbin domain assigned by the token authority.
147    ///
148    /// This value is consumed only after JWT signature verification. Missing,
149    /// empty, or wildcard tenants cannot be used as authorization domains.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub tenant: Option<String>,
152    pub exp: i64,
153    pub iat: i64,
154    /// RFC 7519 JWT ID — unique token identifier for revocation.
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub jti: Option<String>,
157    /// Registered OIDC session ID (`sid`) — groups an interactive session
158    /// whose access-token rotations share one revocable session. Absent on
159    /// standalone service credentials (no session lifecycle).
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub sid: Option<String>,
162    /// Signed generation for profiles that use server-side session authority.
163    /// Stateless Federate proof credentials use `hs_signer_inventory_v1`
164    /// instead. This is JWT-only; envelope claims cannot assert this state.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub hs_session_authority_generation: Option<String>,
167    /// Exact opt-in Federate PoP/COSE subprofile. This is not authority on its
168    /// own; the reserved host path must verify the signed issuer and holder.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub hs_profile: Option<String>,
171    /// Federate-only top-level commitment to the ordered hybrid signer suite.
172    /// Unlike generic v16 `cnf.hs_signer_suite`, this is not a second RFC 7800
173    /// confirmation method: `cnf.jwk` remains the sole confirmation key.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub hs_signer_suite_v1: Option<String>,
176    /// The public ML-DSA-65 half of the COSE proof key pair. It is safe to
177    /// carry in the issuer-signed credential and lets a verifier validate the
178    /// holder proof without resolving a session row just to recover a key.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub hs_signer_pq_key_v1: Option<String>,
181    /// Digest of the issuer's trusted signer inventory at login. This expires
182    /// stale proof credentials after an inventory change without a session DB.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub hs_signer_inventory_v1: Option<String>,
185    /// Signed login provenance. `sub` remains the canonical ATProto DID;
186    /// these claims retain the upstream OIDC identity used to establish it.
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub hs_source_issuer_v1: Option<String>,
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub hs_source_subject_v1: Option<String>,
191    /// TUI-consumer Federate profile (W1.3), deliberately namespaced
192    /// `hs_tui_*` and DISTINCT from every www `federate-session-v1`
193    /// suite/inventory marker above. A credential of the TUI client class
194    /// must NOT enter the deferred federate-session dispatch branch, so
195    /// none of these claims may ever appear in
196    /// [`Claims::has_federate_profile_marker`]: the TUI credential
197    /// authenticates through normal JWT verification with `cnf.jwk` holder
198    /// binding instead. The exact profile string pins the class.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub hs_tui_profile: Option<String>,
201    /// The public ML-DSA-65 half of the TUI holder's COSE proof key pair
202    /// (TUI-namespaced analogue of `hs_signer_pq_key_v1`).
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub hs_tui_signer_pq_key_v1: Option<String>,
205    /// Signed login provenance for the TUI class (TUI-namespaced analogue
206    /// of `hs_source_issuer_v1`/`hs_source_subject_v1`).
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub hs_tui_source_issuer_v1: Option<String>,
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub hs_tui_source_subject_v1: Option<String>,
211    /// Workload credential family session ID (`workload_session_id`) — a
212    /// distinct namespace from OIDC `sid` (v16 §3.3). Present only on
213    /// credentials of an enrolled workload family (e.g. a service-JWT
214    /// renewal chain); a standalone service credential omits it.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub workload_session_id: Option<String>,
217    /// RFC 8707 audience claim for resource indicator binding.
218    #[serde(skip_serializing_if = "Option::is_none")]
219    pub aud: Option<String>,
220    /// RFC 9068 §2.2.1 `client_id` — the OAuth client the access token was
221    /// issued to. REQUIRED (non-empty) on locally issued `at+jwt` credentials
222    /// (v16 credential profile; JWT-only, no CWT mapping). Distinct from `aud`
223    /// (the RFC 8707 resource indicator) and from `sub` (the resource owner).
224    /// Absent on non-`at+jwt` credentials (e.g. `wit+jwt` service tokens) and
225    /// on the in-process empty-issuer provenance path.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub client_id: Option<String>,
228    /// OAuth 2.0 granted scope set, serialized as a space-delimited string.
229    ///
230    /// This is optional because non-OAuth service tokens do not originate from
231    /// an OAuth grant. Consumers that derive authority from OAuth scopes MUST
232    /// use [`Self::has_scope`] and fail closed when this claim is absent.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub scope: Option<String>,
235    /// RFC 8705 / WIMSE proof-of-possession confirmation claim.
236    ///
237    /// Binds the Ed25519 signing key to the JWT-attested identity via a standard
238    /// JWK object (`cnf.jwk`). For service tokens (WIT), derived by the CA from
239    /// the root key. For user tokens, set during OAuth flow from the verified
240    /// Ed25519 challenge-response.
241    #[serde(skip_serializing_if = "Option::is_none")]
242    pub cnf: Option<Cnf>,
243    /// Original JWT token for end-to-end verification.
244    /// When present, downstream services MUST verify this token
245    /// independently rather than trusting the envelope claims alone.
246    ///
247    /// SECURITY:
248    /// - `#[serde(skip)]` prevents recursive JWT-in-JWT embedding and JSON exposure.
249    /// - This field is ONLY populated via Cap'n Proto (`ToCapnp`/`FromCapnp`).
250    /// - Custom Debug impl redacts this field as `[REDACTED]`.
251    /// - Do NOT change to `skip_serializing_if` — that would leak the token in JSON.
252    #[serde(skip)]
253    pub token: Option<String>,
254
255    /// **MAC clearance (S8/#574, design §3, §11).** The authority-asserted
256    /// clearance the issuing node grants this subject: a `SecurityLabel`
257    /// carrying `level` + `compartments`. This is the **authority-asserted**
258    /// half of the S1 subject context; the issuing node signs the JWT, so the
259    /// clearance cannot be self-asserted by the subject.
260    ///
261    /// **Assurance is NOT carried here.** Per the S1/#548 contract, the
262    /// assurance axis of a subject's context is *derived from the verified key
263    /// material*, never trusted from a claim. The MAC PDP clamps the
264    /// clearance's assurance DOWN to what the verified crypto supports (see
265    /// [`crate::auth::mac::SecurityContext::from_clearance`]). So an Ed25519-only
266    /// identity carrying a `PqHybrid` clearance floors to `Classical` at
267    /// enforcement time — the claim cannot grant assurance the key does not back.
268    ///
269    /// `None` ⇒ unlabeled subject ⇒ the MAC monitor denies (no default
270    /// clearance; the S1 fail-closed rule). Carried on the hybrid-signed
271    /// envelope/JWT so it is itself PQ-forgery-resistant.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub clearance: Option<crate::auth::mac::CredentialClearance>,
274
275    /// **Delegation actor (RFC 8693 §4.1 `act`, #680/#681).** Present iff this is
276    /// a delegated (on-behalf-of) token: [`Self::sub`] is the delegator (source of
277    /// authority), `act` the actor that signs the downstream envelope. Drives the
278    /// two-principal MAC derivation (#681): clearance = `meet(sub, act)`, assurance
279    /// from the verified signer (the actor). See [`ActClaim`]. JWT-carried only
280    /// (mirrors [`Self::clearance`]); reconstructed `None` on the Cap'n Proto path.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub act: Option<ActClaim>,
283
284    /// **Attenuated capability subset (ZSP, Fu1/#677, `TODO(#572-scope-claim)`).**
285    /// The least-authority capability the minted token actually encodes, in
286    /// `ability@resource` form. ZSP mints the *subset* that covers the request,
287    /// never the whole grant — this claim puts that subset **on the wire** so the
288    /// downstream PEP (S2) enforces the minted authority (and a refresh can only
289    /// re-grant this subset, never widen). Distinct from Casbin scopes (which are
290    /// NOT in JWTs): this is the MAC/UCAN capability the S6 exchange authorized.
291    ///
292    /// `None` ⇒ not a grant-minted token (ordinary auth token). JWT-carried only
293    /// (mirrors [`Self::clearance`]/[`Self::act`]); reconstructed `None` on the
294    /// Cap'n Proto path.
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub cap: Option<String>,
297}
298
299/// Fixed staging Federate issuer/client reservation. Keep these in the JWT
300/// verifier, not only Registry/Model, so a generation-stripped token cannot
301/// authenticate on another RPC, 9P, or HTTP entry point as a static token.
302pub const FEDERATE_STAGING_HOST: &str = "https://discovery.staging.lab.hyprstream.com";
303pub const FEDERATE_STAGING_CLIENT: &str = "cyberdione-www-staging";
304
305/// The deployment-configured Federate TUI client class id (W1.3), installed
306/// once per process from the trusted-issuer configuration at service
307/// startup (before any service factory runs). This is the authority-owned,
308/// marker-independent class reservation: the RPC layer classifies a
309/// credential naming this client id at a local issuer as TUI-class even with
310/// every TUI marker stripped, so the stripped shape can never fall through
311/// to generic handling. `None` (unconfigured deployment) leaves only the
312/// marker-set classification; nothing can mint the class then.
313static FEDERATE_TUI_CLASS_CLIENT: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
314
315/// Install the TUI class reservation. Idempotent when the value matches a
316/// previous install (startup paths may run more than once); a conflicting
317/// re-install is an error (the class is an authority pin, never reseated).
318pub fn install_federate_tui_class_client(client_id: Option<&str>) -> anyhow::Result<()> {
319    let value = client_id.map(str::to_owned);
320    // get_or_init is race-safe; a conflicting re-install is still an error
321    // (the class is an authority pin, never reseated).
322    let existing = FEDERATE_TUI_CLASS_CLIENT.get_or_init(|| value.clone());
323    anyhow::ensure!(
324        *existing == value,
325        "federate TUI class client already installed with a different id"
326    );
327    Ok(())
328}
329
330/// The configured TUI class client id, or `None` when the class is
331/// unconfigured (or startup never installed the reservation).
332pub fn federate_tui_class_client() -> Option<&'static str> {
333    FEDERATE_TUI_CLASS_CLIENT.get().and_then(Option::as_deref)
334}
335
336/// Server-configured Federate API identity. Accept only an exact canonical
337/// HTTPS origin; never construct this authority from a request or JWT claim.
338#[derive(Clone, Debug, PartialEq, Eq)]
339pub struct FederateHost(String);
340
341impl FederateHost {
342    pub fn new(configured: &str) -> anyhow::Result<Self> {
343        let parsed = url::Url::parse(configured)?;
344        anyhow::ensure!(
345            parsed.scheme() == "https"
346                && parsed.host_str().is_some()
347                && parsed.username().is_empty()
348                && parsed.password().is_none()
349                && parsed.query().is_none()
350                && parsed.fragment().is_none()
351                && parsed.path() == "/"
352                && parsed.origin().ascii_serialization() == configured,
353            "Federate requires an exact canonical HTTPS origin"
354        );
355        Ok(Self(configured.to_owned()))
356    }
357
358    pub fn as_str(&self) -> &str {
359        &self.0
360    }
361
362    pub fn token_endpoint(&self) -> String {
363        format!("{}/oauth/token", self.0)
364    }
365}
366
367// Custom Debug impl — NEVER log the bearer token
368impl std::fmt::Debug for Claims {
369    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370        f.debug_struct("Claims")
371            .field("iss", &self.iss)
372            .field("sub", &self.sub)
373            .field("tenant", &self.tenant)
374            .field("exp", &self.exp)
375            .field("iat", &self.iat)
376            .field("jti", &self.jti)
377            .field("sid", &self.sid)
378            .field(
379                "hs_session_authority_generation",
380                &self.hs_session_authority_generation,
381            )
382            .field("hs_profile", &self.hs_profile)
383            .field("hs_signer_suite_v1", &self.hs_signer_suite_v1)
384            .field("hs_signer_pq_key_v1", &self.hs_signer_pq_key_v1)
385            .field("hs_signer_inventory_v1", &self.hs_signer_inventory_v1)
386            .field("hs_source_issuer_v1", &self.hs_source_issuer_v1)
387            .field("hs_source_subject_v1", &self.hs_source_subject_v1)
388            .field("hs_tui_profile", &self.hs_tui_profile)
389            .field("hs_tui_signer_pq_key_v1", &self.hs_tui_signer_pq_key_v1)
390            .field("hs_tui_source_issuer_v1", &self.hs_tui_source_issuer_v1)
391            .field("hs_tui_source_subject_v1", &self.hs_tui_source_subject_v1)
392            .field("workload_session_id", &self.workload_session_id)
393            .field("aud", &self.aud)
394            .field("client_id", &self.client_id)
395            .field("scope", &self.scope)
396            .field("cnf", &self.cnf)
397            .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))
398            .field("clearance", &self.clearance)
399            .field("act", &self.act)
400            .field("cap", &self.cap)
401            .finish()
402    }
403}
404
405impl ToCapnp for Claims {
406    type Builder<'a> = common_capnp::claims::Builder<'a>;
407
408    fn write_to(&self, builder: &mut Self::Builder<'_>) {
409        builder.set_sub(&self.sub);
410        builder.set_exp(self.exp);
411        builder.set_iat(self.iat);
412        builder.set_admin(false); // Deprecated: always false
413        if let Some(ref aud) = self.aud {
414            builder.set_aud(aud);
415        }
416        if let Some(ref token) = self.token {
417            builder.set_token(token);
418        }
419        if !self.iss.is_empty() {
420            builder.set_iss(&self.iss);
421        }
422        if let Some(ref cnf) = self.cnf {
423            if let Some(ref jwk) = cnf.jwk {
424                builder.set_pub_key(&jwk.x);
425            }
426        }
427        if let Some(ref scope) = self.scope {
428            builder.set_oauth_scope(scope);
429        }
430        // Write empty scopes list for wire compatibility
431        builder.reborrow().init_scopes(0);
432    }
433}
434
435impl FromCapnp for Claims {
436    type Reader<'a> = common_capnp::claims::Reader<'a>;
437
438    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
439        let aud = reader
440            .get_aud()
441            .ok()
442            .and_then(|s| s.to_str().ok())
443            .map(std::borrow::ToOwned::to_owned)
444            .filter(|s| !s.is_empty());
445
446        let scope = reader
447            .get_oauth_scope()
448            .ok()
449            .and_then(|s| s.to_str().ok())
450            .map(std::borrow::ToOwned::to_owned)
451            .filter(|s| !s.is_empty());
452
453        let token = reader
454            .get_token()
455            .ok()
456            .and_then(|s| s.to_str().ok())
457            .map(std::borrow::ToOwned::to_owned)
458            .filter(|s| !s.is_empty());
459
460        let iss = reader
461            .get_iss()
462            .ok()
463            .and_then(|s| s.to_str().ok())
464            .map(std::borrow::ToOwned::to_owned)
465            .unwrap_or_default();
466
467        let cnf = reader
468            .get_pub_key()
469            .ok()
470            .and_then(|s| s.to_str().ok())
471            .filter(|s| !s.is_empty())
472            .map(|x| Cnf {
473                jwk: Some(CnfJwk {
474                    kty: "OKP".to_owned(),
475                    crv: "Ed25519".to_owned(),
476                    x: x.to_owned(),
477                }),
478                jkt: None,
479                hs_signer_suite: None,
480            });
481
482        Ok(Self {
483            iss,
484            sub: reader.get_sub()?.to_str()?.to_owned(),
485            // Tenant authorization is JWT-only so the verifier can establish
486            // its authority; legacy envelope claims cannot assert it.
487            tenant: None,
488            exp: reader.get_exp(),
489            iat: reader.get_iat(),
490            jti: None,
491            // `sid` / `workload_session_id` are JWT-carried, like `jti`;
492            // the envelope Claims surface does not carry them.
493            sid: None,
494            hs_session_authority_generation: None,
495            hs_profile: None,
496            hs_signer_suite_v1: None,
497            hs_signer_pq_key_v1: None,
498            hs_signer_inventory_v1: None,
499            hs_source_issuer_v1: None,
500            hs_source_subject_v1: None,
501            hs_tui_profile: None,
502            hs_tui_signer_pq_key_v1: None,
503            hs_tui_source_issuer_v1: None,
504            hs_tui_source_subject_v1: None,
505            workload_session_id: None,
506            aud,
507            client_id: None,
508            // The dedicated OAuth field preserves the signed grant ceiling;
509            // the legacy structured scope list remains unused by Claims.
510            scope,
511            cnf,
512            token,
513            // MAC clearance (S8/#574) is not carried on the Cap'n Proto envelope
514            // surface today; it rides the JWT (the hybrid-signed authority token).
515            // The envelope Claims are a distinct carrier from the JWT Claims; the
516            // clearance is read off the verified JWT by the MAC PDP.
517            clearance: None,
518            // `act` (RFC 8693 delegation) likewise rides the JWT, not this
519            // envelope surface; reconstructed None here (#680/#681).
520            act: None,
521            // `cap` (attenuated capability subset) is JWT-carried too (Fu1/#677).
522            cap: None,
523        })
524    }
525}
526
527/// Session-claim parsing failure (v16 §3.3 exact-one rule). Any error is a
528/// malformed-credential rejection at a verification boundary.
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum SessionClaimError {
531    /// Both `sid` and `workload_session_id` present — the namespaces are
532    /// disjoint; carrying both is ambiguous and never valid.
533    AmbiguousSessionClaims,
534    /// A present session identifier is empty or whitespace.
535    EmptySessionIdentifier,
536}
537
538impl std::fmt::Display for SessionClaimError {
539    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
540        match self {
541            Self::AmbiguousSessionClaims => write!(
542                f,
543                "credential carries both sid and workload_session_id (disjoint namespaces)"
544            ),
545            Self::EmptySessionIdentifier => {
546                write!(f, "session identifier is empty")
547            }
548        }
549    }
550}
551
552impl std::error::Error for SessionClaimError {}
553
554impl Claims {
555    /// Create new claims.
556    pub fn new(sub: String, iat: i64, exp: i64) -> Self {
557        Self {
558            iss: String::new(),
559            sub,
560            tenant: None,
561            exp,
562            iat,
563            jti: None,
564            sid: None,
565            hs_session_authority_generation: None,
566            hs_profile: None,
567            hs_signer_suite_v1: None,
568            hs_signer_pq_key_v1: None,
569            hs_signer_inventory_v1: None,
570            hs_source_issuer_v1: None,
571            hs_source_subject_v1: None,
572            hs_tui_profile: None,
573            hs_tui_signer_pq_key_v1: None,
574            hs_tui_source_issuer_v1: None,
575            hs_tui_source_subject_v1: None,
576            workload_session_id: None,
577            aud: None,
578            client_id: None,
579            scope: None,
580            cnf: None,
581            token: None,
582            clearance: None,
583            act: None,
584            cap: None,
585        }
586    }
587
588    /// Attach a delegation actor (RFC 8693 `act`).
589    pub fn with_actor(mut self, actor: Option<ActClaim>) -> Self {
590        self.act = actor;
591        self
592    }
593
594    /// The terminal (deepest) actor subject in the delegation chain, if any.
595    pub fn terminal_actor(&self) -> Option<&str> {
596        let mut current = self.act.as_ref()?;
597        while let Some(next) = current.act.as_deref() {
598            current = next;
599        }
600        Some(current.sub.as_str())
601    }
602
603    /// Set a random JWT ID (RFC 7519 `jti` claim) for revocation support.
604    pub fn with_jti(mut self) -> Self {
605        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
606        use rand::RngCore as _;
607        let mut bytes = [0u8; 16];
608        rand::rngs::OsRng.fill_bytes(&mut bytes);
609        self.jti = Some(URL_SAFE_NO_PAD.encode(bytes));
610        self
611    }
612
613    /// Set the OIDC session ID (`sid` claim).
614    pub fn with_sid(mut self, sid: impl Into<String>) -> Self {
615        self.sid = Some(sid.into());
616        self
617    }
618
619    /// Set a session-authority generation in its one canonical encoding.
620    /// This does not make a token eligible for dispatch; profile, proof,
621    /// replay and Policy checks remain mandatory.
622    pub fn with_session_authority_generation(mut self, generation: [u8; 32]) -> Self {
623        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
624        self.hs_session_authority_generation = Some(URL_SAFE_NO_PAD.encode(generation));
625        self
626    }
627
628    /// Parse the signed generation without accepting padding, alternate
629    /// alphabets, truncation, or a wire-provided state locator.
630    pub fn session_authority_generation(&self) -> anyhow::Result<Option<[u8; 32]>> {
631        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
632        let Some(encoded) = self.hs_session_authority_generation.as_deref() else {
633            return Ok(None);
634        };
635        anyhow::ensure!(encoded.len() == 43, "invalid session generation length");
636        let raw = URL_SAFE_NO_PAD.decode(encoded)?;
637        let generation: [u8; 32] = raw
638            .try_into()
639            .map_err(|_| anyhow::anyhow!("invalid session generation length"))?;
640        anyhow::ensure!(
641            URL_SAFE_NO_PAD.encode(generation) == encoded,
642            "noncanonical session generation"
643        );
644        Ok(Some(generation))
645    }
646
647    /// Set the trusted signer-inventory digest for the stateless Federate
648    /// proof profile. This binds a short-lived credential to the host's current
649    /// verifier inventory without naming a database or session row.
650    pub fn with_federate_signer_inventory(mut self, inventory: [u8; 32]) -> Self {
651        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
652        self.hs_signer_inventory_v1 = Some(URL_SAFE_NO_PAD.encode(inventory));
653        self
654    }
655
656    /// Parse the signed Federate signer-inventory digest in its sole canonical
657    /// base64url encoding. Callers decide whether the all-zero value is valid
658    /// for their configured inventory.
659    pub fn federate_signer_inventory(&self) -> anyhow::Result<Option<[u8; 32]>> {
660        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
661        let Some(encoded) = self.hs_signer_inventory_v1.as_deref() else {
662            return Ok(None);
663        };
664        anyhow::ensure!(
665            encoded.len() == 43,
666            "invalid signer inventory digest length"
667        );
668        let raw = URL_SAFE_NO_PAD.decode(encoded)?;
669        let inventory: [u8; 32] = raw
670            .try_into()
671            .map_err(|_| anyhow::anyhow!("invalid signer inventory digest length"))?;
672        anyhow::ensure!(
673            URL_SAFE_NO_PAD.encode(inventory) == encoded,
674            "noncanonical signer inventory digest"
675        );
676        Ok(Some(inventory))
677    }
678
679    /// Recognize the fixed host/client even when one profile marker was
680    /// removed by a faulty issuer or token transformation.
681    pub fn is_reserved_federate_staging_credential(&self) -> bool {
682        self.is_reserved_federate_credential(FEDERATE_STAGING_HOST)
683    }
684
685    pub fn is_reserved_federate_credential(&self, configured_host: &str) -> bool {
686        self.iss == configured_host && self.client_id.as_deref() == Some(FEDERATE_STAGING_CLIENT)
687    }
688
689    /// Any signed Federate-only marker takes the deferred, fail-closed path;
690    /// stripping one marker cannot reinterpret the remaining token as generic.
691    ///
692    /// The TUI-consumer markers (`hs_tui_*`, W1.3) are deliberately NOT in
693    /// this set: a TUI-class credential authenticates through normal JWT
694    /// verification (with `cnf.jwk` holder binding), never through the
695    /// deferred federate-session dispatch branch. A TUI credential carrying
696    /// any www marker below still trips this check and is rejected in that
697    /// branch (it is not the reserved staging class); a www credential
698    /// carrying any TUI marker is rejected by the www proof consumer.
699    pub fn has_federate_profile_marker(&self) -> bool {
700        self.hs_session_authority_generation.is_some()
701            || self.hs_profile.is_some()
702            || self.hs_signer_suite_v1.is_some()
703            || self.hs_signer_pq_key_v1.is_some()
704            || self.hs_signer_inventory_v1.is_some()
705            || self.hs_source_issuer_v1.is_some()
706            || self.hs_source_subject_v1.is_some()
707    }
708
709    /// Any signed TUI-consumer marker. Used by the TUI profile consumer to
710    /// reject www-class credentials that smuggle TUI markers (mixed-marker
711    /// defense) and to require the complete TUI marker set.
712    pub fn has_federate_tui_profile_marker(&self) -> bool {
713        self.hs_tui_profile.is_some()
714            || self.hs_tui_signer_pq_key_v1.is_some()
715            || self.hs_tui_source_issuer_v1.is_some()
716            || self.hs_tui_source_subject_v1.is_some()
717    }
718
719    /// The COMPLETE TUI-consumer marker set. The mint stamps all four
720    /// unconditionally, so a classified credential with any marker missing
721    /// is never legitimate.
722    pub fn has_complete_federate_tui_profile(&self) -> bool {
723        self.hs_tui_profile.is_some()
724            && self.hs_tui_signer_pq_key_v1.is_some()
725            && self.hs_tui_source_issuer_v1.is_some()
726            && self.hs_tui_source_subject_v1.is_some()
727    }
728
729    /// Whether this credential is of the Federate TUI client class (W1.3):
730    /// it carries any TUI marker, OR it names the deployment-configured TUI
731    /// client id at a local issuer — the authority-owned, marker-independent
732    /// class pin, mirroring the www reserved (iss, client_id) predicate so a
733    /// class-shaped credential with every marker stripped still cannot fall
734    /// through to generic handling.
735    pub fn is_federate_tui_class(&self, local_issuers: &[&str]) -> bool {
736        self.has_federate_tui_profile_marker()
737            || (crate::auth::is_local_iss(&self.iss, local_issuers)
738                && federate_tui_class_client()
739                    .is_some_and(|client| self.client_id.as_deref() == Some(client)))
740    }
741
742    /// Stamp the TUI-consumer Federate profile marker set. Every claim is
743    /// TUI-namespaced and disjoint from the www `federate-session-v1`
744    /// suite/inventory markers, so the credential never enters the deferred
745    /// federate dispatch branch; the marker alone is never authority.
746    pub fn with_federate_tui_markers(
747        mut self,
748        pq_key_b64url: String,
749        source_issuer: String,
750        source_subject: String,
751    ) -> Self {
752        self.hs_tui_profile = Some("federate-tui-v1".to_owned());
753        self.hs_tui_signer_pq_key_v1 = Some(pq_key_b64url);
754        self.hs_tui_source_issuer_v1 = Some(source_issuer);
755        self.hs_tui_source_subject_v1 = Some(source_subject);
756        self
757    }
758
759    /// Stamp the exact Federate profile and its ordered hybrid-suite digest.
760    /// This marker alone is never authority; the reserved path also verifies
761    /// the signed source binding, holder proof, replay admission and live Policy.
762    pub fn with_federate_signer_suite(mut self, thumbprint_b64url: String) -> Self {
763        self.hs_profile = Some("federate-session-v1".to_owned());
764        self.hs_signer_suite_v1 = Some(thumbprint_b64url);
765        self
766    }
767
768    /// Set the workload credential family session ID
769    /// (`workload_session_id` claim) — enrolled workload families only.
770    pub fn with_workload_session_id(mut self, id: impl Into<String>) -> Self {
771        self.workload_session_id = Some(id.into());
772        self
773    }
774
775    /// The credential's session binding under exact-one parsing (v16 §3.3):
776    /// a credential carries AT MOST ONE session identifier, in a disjoint
777    /// namespace — OIDC `sid` (interactive) or `workload_session_id`
778    /// (enrolled workload family). Both-present is ambiguous and rejects;
779    /// a present-but-empty identifier is malformed and rejects. Neither is
780    /// `Ok(None)` (standalone credential, no session).
781    ///
782    /// Every authorization and cache-insertion path MUST use this parser —
783    /// never an `sid.or_else(workload_session_id)` chain, which would let an
784    /// active OIDC session mask a revoked or unknown workload session.
785    pub fn session_key(
786        &self,
787    ) -> std::result::Result<Option<super::credential::SessionKey>, SessionClaimError> {
788        let sid = self.sid.as_deref();
789        let wsid = self.workload_session_id.as_deref();
790        if sid.is_some() && wsid.is_some() {
791            return Err(SessionClaimError::AmbiguousSessionClaims);
792        }
793        if sid.is_some_and(|v| v.trim().is_empty()) || wsid.is_some_and(|v| v.trim().is_empty()) {
794            return Err(SessionClaimError::EmptySessionIdentifier);
795        }
796        Ok(match (sid, wsid) {
797            (Some(sid), None) => Some(super::credential::SessionKey::oidc(&self.iss, sid)),
798            (None, Some(id)) => Some(super::credential::SessionKey::workload(&self.iss, id)),
799            (None, None) => None,
800            (Some(_), Some(_)) => unreachable!("both-present rejected above"),
801        })
802    }
803
804    /// Set the issuer URL (RFC 7519 `iss` claim).
805    /// Should be the OAuth issuer URL of the hyprstream node that issued this token.
806    pub fn with_issuer(mut self, issuer: String) -> Self {
807        self.iss = issuer;
808        self
809    }
810
811    /// Set the authority-asserted tenant used as the Casbin request domain.
812    pub fn with_tenant(mut self, tenant: String) -> Self {
813        self.tenant = Some(tenant);
814        self
815    }
816
817    /// Create new claims with an audience (RFC 8707 resource indicator).
818    pub fn with_audience(mut self, audience: Option<String>) -> Self {
819        self.aud = audience;
820        self
821    }
822
823    /// Set the RFC 9068 §2.2.1 `client_id` claim (the OAuth client the access
824    /// token was issued to). An empty/whitespace value is treated as absent so
825    /// a caller cannot satisfy the profile's non-empty requirement with a blank.
826    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
827        let value = client_id.into();
828        self.client_id = (!value.trim().is_empty()).then_some(value);
829        self
830    }
831
832    /// Set the OAuth 2.0 granted scope claim.
833    pub fn with_scope(mut self, scope: Option<String>) -> Self {
834        self.scope = scope.filter(|value| !value.trim().is_empty());
835        self
836    }
837
838    /// Iterate over the exact scopes granted to this token.
839    ///
840    /// An absent claim yields an empty iterator, keeping scope-based consumers
841    /// fail closed for legacy and non-OAuth tokens.
842    pub fn granted_scopes(&self) -> impl Iterator<Item = &str> {
843        self.scope
844            .as_deref()
845            .into_iter()
846            .flat_map(str::split_whitespace)
847    }
848
849    /// Return whether this token's signed grant contains `required` exactly.
850    pub fn has_scope(&self, required: &str) -> bool {
851        self.granted_scopes().any(|granted| granted == required)
852    }
853
854    /// Attach original JWT token for e2e verification by downstream services.
855    pub fn with_token(mut self, token: String) -> Self {
856        self.token = Some(token);
857        self
858    }
859
860    /// Set the RFC 8705 `cnf.jwk` confirmation claim (WIMSE WIT key binding).
861    ///
862    /// `key_bytes` is the raw 32-byte Ed25519 public key. Produces a standard
863    /// OKP JWK object with `kty: "OKP"`, `crv: "Ed25519"`, `x: <base64url>`.
864    pub fn with_cnf_jwk(mut self, key_bytes: &[u8; 32]) -> Self {
865        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
866        // Merge, never replace: a previously-stamped `hs_signer_suite` (or
867        // `jkt`) survives adding the legacy `jwk` binding, and vice versa.
868        let mut cnf = self.cnf.take().unwrap_or_default();
869        cnf.jwk = Some(CnfJwk {
870            kty: "OKP".to_owned(),
871            crv: "Ed25519".to_owned(),
872            x: URL_SAFE_NO_PAD.encode(key_bytes),
873        });
874        self.cnf = Some(cnf);
875        self
876    }
877
878    /// Set the v16 `cnf.hs_signer_suite` confirmation (frozen WS-A profile
879    /// §1.1/§5): the base64url signer-suite content thumbprint. Merged into any
880    /// existing `cnf` so a legacy `jwk`/`jkt` binding is preserved alongside it.
881    /// Compute `thumbprint_b64url` from [`crate::auth::signer_suite_thumbprint`].
882    pub fn with_cnf_hs_signer_suite(mut self, thumbprint_b64url: String) -> Self {
883        let mut cnf = self.cnf.take().unwrap_or_default();
884        cnf.hs_signer_suite = Some(thumbprint_b64url);
885        self.cnf = Some(cnf);
886        self
887    }
888
889    /// Set the RFC 9449 `cnf.jkt` confirmation claim (DPoP JWK thumbprint).
890    ///
891    /// `key_bytes` is the raw 32-byte Ed25519 public key. The thumbprint is
892    /// computed per RFC 7638: SHA-256 of the lexicographic canonical JWK JSON,
893    /// base64url-encoded.
894    pub fn with_cnf_jkt(mut self, key_bytes: &[u8; 32]) -> Self {
895        let mut cnf = self.cnf.take().unwrap_or_default();
896        cnf.jkt = Some(compute_jkt(key_bytes));
897        self.cnf = Some(cnf);
898        self
899    }
900
901    /// Set the RFC 9449 `cnf.jkt` from a PRE-COMPUTED thumbprint string (e.g. a
902    /// verified DPoP proof's `jkt`). Merged into any existing `cnf`.
903    pub fn with_cnf_jkt_thumbprint(mut self, jkt: String) -> Self {
904        let mut cnf = self.cnf.take().unwrap_or_default();
905        cnf.jkt = Some(jkt);
906        self.cnf = Some(cnf);
907        self
908    }
909
910    /// Set the MAC clearance claim (S8/#574). The authority-asserted clearance
911    /// the issuing node grants this subject (level + compartments). The
912    /// resulting JWT carries this under its (hybrid) signature, so it is itself
913    /// PQ-forgery-resistant; the assurance axis is NOT carried here — it is
914    /// derived from the verified key material at enforcement time.
915    pub fn with_clearance(mut self, clearance: crate::auth::mac::SecurityLabel) -> Self {
916        // Project to the two-axis wire form (level + compartments); the
917        // assurance axis is dropped — it is never issuer-asserted (v16 §11).
918        self.clearance = Some(crate::auth::mac::CredentialClearance::from_label(clearance));
919        self
920    }
921
922    /// Set the MAC clearance claim from its two-axis wire projection directly.
923    /// Used when FORWARDING an already-projected clearance (e.g. re-stamping a
924    /// verified source credential's clearance onto a derived ticket) — the
925    /// value is copied through unchanged. Prefer [`Self::with_clearance`] when
926    /// starting from a full `SecurityLabel`.
927    pub fn with_credential_clearance(
928        mut self,
929        clearance: crate::auth::mac::CredentialClearance,
930    ) -> Self {
931        self.clearance = Some(clearance);
932        self
933    }
934
935    /// Set the RFC 8693 delegation actor (`act`, #680/#681). Marks this as a
936    /// delegated (on-behalf-of) token: [`Self::sub`] stays the delegator; `actor`
937    /// is the principal that will sign the downstream envelope. The MAC PDP
938    /// derives clearance as `meet(sub, act)` and assurance from the verified
939    /// signer. See [`ActClaim`].
940    pub fn with_act(mut self, actor: ActClaim) -> Self {
941        self.act = Some(actor);
942        self
943    }
944
945    /// Set the attenuated capability subset (`cap`, ZSP Fu1/#677) the minted
946    /// token encodes, in `ability@resource` form. See [`Self::cap`].
947    pub fn with_cap(mut self, cap: String) -> Self {
948        self.cap = Some(cap);
949        self
950    }
951
952    /// Extract the raw 32-byte Ed25519 public key from `cnf.jwk.x`, if present.
953    pub fn cnf_key_bytes(&self) -> Option<[u8; 32]> {
954        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
955        let x = self.cnf.as_ref()?.jwk.as_ref()?.x.as_str();
956        let bytes = URL_SAFE_NO_PAD.decode(x).ok()?;
957        bytes.try_into().ok()
958    }
959
960    /// Return the `cnf.jkt` thumbprint string, if present.
961    pub fn cnf_jkt(&self) -> Option<&str> {
962        self.cnf.as_ref()?.jkt.as_deref()
963    }
964
965    /// Independently verify the embedded JWT token.
966    ///
967    /// Returns the verified claims if the token is present and valid.
968    /// Returns None if no token is embedded.
969    /// Returns Err if token is present but verification fails (MUST reject request).
970    ///
971    /// Note: `jwt::decode()` validates both signature and `exp` (via `is_expired()`).
972    pub fn verify_token(
973        &self,
974        verifying_key: &ed25519_dalek::VerifyingKey,
975        expected_aud: Option<&str>,
976    ) -> std::result::Result<Option<Claims>, super::jwt::JwtError> {
977        match &self.token {
978            Some(token) => {
979                let verified = super::jwt::decode(token, verifying_key, expected_aud)?;
980                Ok(Some(verified))
981            }
982            None => Ok(None),
983        }
984    }
985
986    /// Check if token is expired (with 5-second leeway for clock skew).
987    pub fn is_expired(&self) -> bool {
988        chrono::Utc::now().timestamp() > self.exp.saturating_add(5)
989    }
990
991    /// True if this token was issued by a local node.
992    ///
993    /// Delegates to [`is_local_iss`] using this token's `iss` field.
994    pub fn is_local_to(&self, local_issuers: &[&str]) -> bool {
995        is_local_iss(&self.iss, local_issuers)
996    }
997
998    /// Strip the authority-asserted MAC `clearance` when this token's issuer is
999    /// NOT a local issuer (Fu5/#677).
1000    ///
1001    /// `clearance` is authority-asserted: the issuing node signs the JWT, so a
1002    /// local issuer (this node, or a configured local cluster issuer) is trusted
1003    /// to grant MAC clearance. An external OIDC issuer trusted **for identity**
1004    /// is NOT thereby trusted to assert MAC clearance on this node — honoring it
1005    /// would let any trusted-for-identity federated IdP mint MAC clearance.
1006    /// Federated-path decode therefore drops the claim before the MAC PDP can
1007    /// read it ([`crate::auth::mac::SubjectContextClaims::credential_clearance`]
1008    /// returns `None` ⇒ unlabeled ⇒ deny). Local-issuer tokens are unaffected.
1009    pub fn strip_federated_clearance(&mut self, local_issuers: &[&str]) {
1010        if !self.is_local_to(local_issuers) {
1011            self.clearance = None;
1012        }
1013    }
1014
1015    /// Strip the authority-asserted tenant when this token's issuer is not
1016    /// local.
1017    ///
1018    /// A federated issuer trusted for identity is not trusted to select a local
1019    /// Casbin tenant domain. Clearing the claim makes downstream domain
1020    /// resolution fail closed, while preserving tenant bindings minted by local
1021    /// issuers.
1022    pub fn strip_federated_tenant(&mut self, local_issuers: &[&str]) {
1023        if !self.is_local_to(local_issuers) {
1024            self.tenant = None;
1025        }
1026    }
1027
1028    /// Derive the Casbin authorization subject from these claims.
1029    ///
1030    /// Local tokens (issued by this node) produce bare subjects (`"alice"`)
1031    /// matching existing Casbin rules.  Federated tokens produce namespaced
1032    /// subjects (`"https://other.node:alice"`) to prevent cross-node spoofing.
1033    ///
1034    /// [`UNAUTHENTICATED_DID_SENTINEL`] is credential absence, not a principal.
1035    /// Even a verified token carrying it therefore resolves to the
1036    /// unauthenticated floor and can never authenticate as the sentinel.
1037    pub fn subject(&self, local_issuers: &[&str]) -> crate::envelope::Subject {
1038        if self.sub.is_empty() || self.sub == UNAUTHENTICATED_DID_SENTINEL {
1039            return crate::envelope::Subject::anonymous();
1040        }
1041        if self.is_local_to(local_issuers) {
1042            crate::envelope::Subject::new(self.sub.clone())
1043        } else {
1044            crate::envelope::Subject::federated(&self.iss, &self.sub)
1045        }
1046    }
1047}
1048
1049// ── MAC subject-context seam (S8/#574, S1/#548) ─────────────────────────────
1050//
1051// `Claims` is the authority-asserted carrier for a subject's clearance. The S1
1052// `SubjectContextClaims` trait is the typed contract the MAC PDP / S6 grant path
1053// program against; this impl lights it up for real verified JWT claims. The
1054// two-input `security_context(key_material)` combines:
1055//   1. the authority-asserted clearance (this `clearance` field — the JWT is
1056//      signed by the issuing node, so this is authority-asserted, not self-
1057//      asserted), and
1058//   2. the assurance derived from the *verified key material* (threaded in from
1059//      the envelope signature-verification layer — NEVER trusted from a claim).
1060// `SecurityContext::from_clearance` clamps the assurance axis DOWN to what the
1061// crypto supports, so a classical key carrying a PqHybrid clearance floors to
1062// Classical — the load-bearing #548 invariant: assurance is a property of the
1063// verified identity, not a grant.
1064impl crate::auth::mac::SubjectContextClaims for Claims {
1065    fn credential_clearance(&self) -> Option<crate::auth::mac::CredentialClearance> {
1066        self.clearance
1067    }
1068}
1069
1070#[cfg(test)]
1071#[allow(clippy::unwrap_used, clippy::expect_used)]
1072mod tests {
1073    use super::*;
1074
1075    #[test]
1076    fn federate_host_requires_exact_canonical_https_origin() {
1077        for host in [
1078            FEDERATE_STAGING_HOST,
1079            "https://vm-a.example",
1080            "https://vm-b.example:8443",
1081        ] {
1082            let configured = FederateHost::new(host).unwrap();
1083            assert_eq!(configured.as_str(), host);
1084            assert_eq!(configured.token_endpoint(), format!("{host}/oauth/token"));
1085        }
1086        for host in [
1087            "http://vm.example",
1088            "https://vm.example/",
1089            "https://VM.example",
1090            "https://vm.example:443",
1091            "https://user@vm.example",
1092            "https://vm.example/path",
1093            "https://vm.example?",
1094            "https://vm.example#",
1095            " https://vm.example",
1096            "https://vm.example\\evil",
1097        ] {
1098            assert!(FederateHost::new(host).is_err(), "{host}");
1099        }
1100    }
1101
1102    #[test]
1103    fn oauth_scope_claim_is_exact_and_absence_fails_closed() {
1104        let plain = Claims::new("alice".to_owned(), 1000, 2000);
1105        assert!(!plain.has_scope("atproto"));
1106        assert!(!serde_json::to_string(&plain).unwrap().contains("\"scope\""));
1107
1108        let scoped = plain.with_scope(Some("atproto transition:generic".to_owned()));
1109        assert!(scoped.has_scope("atproto"));
1110        assert!(scoped.has_scope("transition:generic"));
1111        assert!(!scoped.has_scope("transition"));
1112        assert_eq!(
1113            scoped.granted_scopes().collect::<Vec<_>>(),
1114            vec!["atproto", "transition:generic"]
1115        );
1116    }
1117
1118    #[test]
1119    fn oauth_scope_survives_capnp_envelope_roundtrip() -> anyhow::Result<()> {
1120        let claims = Claims::new("alice".to_owned(), 1000, 2000)
1121            .with_scope(Some("atproto transition:generic".to_owned()));
1122        let mut message = capnp::message::Builder::new_default();
1123        let mut builder = message.init_root::<common_capnp::claims::Builder>();
1124        claims.write_to(&mut builder);
1125
1126        let decoded = Claims::read_from(builder.into_reader())?;
1127        assert_eq!(decoded.scope, claims.scope);
1128        assert!(decoded.has_scope("atproto"));
1129        assert!(decoded.has_scope("transition:generic"));
1130        Ok(())
1131    }
1132
1133    #[test]
1134    fn federate_profile_has_one_cnf_key_and_top_level_hybrid_commitment() {
1135        let ed = [0x01; 32];
1136        let claims = Claims::new("alice".to_owned(), 1000, 1300)
1137            .with_cnf_jwk(&ed)
1138            .with_federate_signer_suite("n47qkIMqPn-EuRo0YmrWkGFyyCY0UmVhKE19Bxbtt0U".to_owned());
1139        let json = serde_json::to_value(&claims).unwrap();
1140        assert_eq!(json["hs_profile"], "federate-session-v1");
1141        assert_eq!(
1142            json["hs_signer_suite_v1"],
1143            "n47qkIMqPn-EuRo0YmrWkGFyyCY0UmVhKE19Bxbtt0U"
1144        );
1145        assert_eq!(json["cnf"].as_object().unwrap().len(), 1);
1146        assert_eq!(json["cnf"]["jwk"]["kty"], "OKP");
1147        assert_eq!(json["cnf"]["jwk"]["crv"], "Ed25519");
1148        assert_eq!(
1149            json["cnf"]["jwk"]["x"],
1150            "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE"
1151        );
1152        assert!(json["cnf"].get("hs_signer_suite").is_none());
1153        assert!(json["cnf"].get("jkt").is_none());
1154        let decoded: Claims = serde_json::from_value(json).unwrap();
1155        assert!(decoded.has_federate_profile_marker());
1156    }
1157
1158    #[test]
1159    fn test_act_claim_serde_roundtrip_and_default_none() {
1160        // Non-delegated token: `act` absent, and (skip_serializing_if) omitted
1161        // from the JSON entirely — no empty `act` on the wire.
1162        let plain = Claims::new("alice".to_owned(), 1000, 2000);
1163        assert!(plain.act.is_none());
1164        let json = serde_json::to_string(&plain).unwrap();
1165        assert!(
1166            !json.contains("\"act\""),
1167            "plain token must not carry act: {json}"
1168        );
1169
1170        // Delegated token: sub = delegator (user), act = actor (service:mcp),
1171        // with a nested hop to exercise RFC 8693 §4.1 multi-hop.
1172        let actor = ActClaim {
1173            sub: "service:mcp".to_owned(),
1174            clearance: None,
1175            act: Some(Box::new(ActClaim {
1176                sub: "service:gateway".to_owned(),
1177                clearance: None,
1178                act: None,
1179            })),
1180        };
1181        let delegated = Claims::new("alice".to_owned(), 1000, 2000)
1182            .with_act(actor.clone())
1183            .with_cap("infer@mac://model/qwen-7b".to_owned());
1184        let json = serde_json::to_string(&delegated).unwrap();
1185        let back: Claims = serde_json::from_str(&json).unwrap();
1186        assert_eq!(back.sub, "alice", "sub stays the delegator");
1187        assert_eq!(
1188            back.act,
1189            Some(actor),
1190            "act round-trips including the nested hop"
1191        );
1192        assert_eq!(
1193            back.cap.as_deref(),
1194            Some("infer@mac://model/qwen-7b"),
1195            "attenuated capability subset rides the token (Fu1/#677)"
1196        );
1197        assert!(plain.cap.is_none(), "plain token carries no cap");
1198        assert_eq!(
1199            back.act.as_ref().unwrap().act.as_ref().unwrap().sub,
1200            "service:gateway"
1201        );
1202    }
1203
1204    #[test]
1205    fn test_debug_shows_act_but_redacts_token() {
1206        let claims = Claims::new("alice".to_owned(), 1000, 2000).with_act(ActClaim {
1207            sub: "service:mcp".to_owned(),
1208            clearance: None,
1209            act: None,
1210        });
1211        let dbg = format!("{claims:?}");
1212        assert!(
1213            dbg.contains("service:mcp"),
1214            "act is not secret, must be visible"
1215        );
1216        assert!(dbg.contains("act:"));
1217    }
1218
1219    #[test]
1220    fn test_claims_new() {
1221        let claims = Claims::new("alice".to_owned(), 1000, 2000);
1222        assert_eq!(claims.sub, "alice");
1223        assert_eq!(claims.iat, 1000);
1224        assert_eq!(claims.exp, 2000);
1225        assert_eq!(claims.iss, "");
1226        assert!(claims.aud.is_none());
1227        assert!(claims.token.is_none());
1228    }
1229
1230    #[test]
1231    fn expiry_check_handles_i64_max_without_wrapping() {
1232        let claims = Claims::new("alice".to_owned(), 0, i64::MAX);
1233        assert!(
1234            !claims.is_expired(),
1235            "an i64::MAX expiry must not wrap into an expired timestamp"
1236        );
1237    }
1238
1239    #[test]
1240    fn test_claims_with_issuer() {
1241        let claims = Claims::new("alice".to_owned(), 1000, 2000)
1242            .with_issuer("https://a.example.com".to_owned());
1243        assert_eq!(claims.iss, "https://a.example.com");
1244    }
1245
1246    // ── Fu5/#677: clearance honored only from local-issuer tokens ───────────
1247
1248    use crate::auth::mac::{
1249        Assurance, CompartmentSet, Level, SecurityLabel, SubjectContextClaims as _,
1250    };
1251
1252    fn fu5_clearance() -> SecurityLabel {
1253        SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY)
1254    }
1255
1256    /// A federated token (issuer not in `local_issuers`) carrying a `clearance`
1257    /// claim MUST have it stripped — an external OIDC issuer trusted for
1258    /// identity is not trusted to assert MAC clearance on this node. After the
1259    /// strip the MAC PDP reads `None` (⇒ unlabeled ⇒ deny).
1260    #[test]
1261    fn fu5_federated_clearance_is_stripped() {
1262        let federated = "https://idp.example.com";
1263        let mut claims = Claims::new("alice".to_owned(), 1000, 2000)
1264            .with_issuer(federated.to_owned())
1265            .with_clearance(fu5_clearance());
1266        assert!(
1267            claims.clearance.is_some(),
1268            "precondition: federated token carries a clearance"
1269        );
1270
1271        // Local issuers do NOT include the federated IdP.
1272        claims.strip_federated_clearance(&["https://this.node"]);
1273
1274        assert!(
1275            claims.clearance.is_none(),
1276            "a federated token's clearance MUST be ignored (Fu5/#677)"
1277        );
1278        assert!(
1279            claims.credential_clearance().is_none(),
1280            "the MAC PDP reads None ⇒ unlabeled ⇒ deny"
1281        );
1282    }
1283
1284    /// A local-issuer token's clearance is authority-asserted by this node and
1285    /// MUST be preserved — `strip_federated_clearance` is a no-op for it.
1286    #[test]
1287    fn fu5_local_clearance_is_preserved() {
1288        let local_iss = "https://this.node";
1289        let mut claims = Claims::new("alice".to_owned(), 1000, 2000)
1290            .with_issuer(local_iss.to_owned())
1291            .with_clearance(fu5_clearance());
1292
1293        claims.strip_federated_clearance(&[local_iss]);
1294
1295        let kept = claims
1296            .clearance
1297            .expect("a local-issuer token keeps its authority-asserted clearance");
1298        assert_eq!(kept.level, Level::Secret);
1299    }
1300
1301    /// An unconfigured node (empty `local_issuers`) treats every non-empty iss
1302    /// as federated (see [`is_local_iss`]) — so any clearance is stripped.
1303    #[test]
1304    fn fu5_unconfigured_node_strips_all_clearance() {
1305        let mut claims = Claims::new("alice".to_owned(), 1000, 2000)
1306            .with_issuer("https://some.idp".to_owned())
1307            .with_clearance(fu5_clearance());
1308
1309        claims.strip_federated_clearance(&[]);
1310
1311        assert!(
1312            claims.clearance.is_none(),
1313            "an unconfigured node honors no clearance (deny-by-default)"
1314        );
1315    }
1316
1317    /// Exact-one session parsing (v16 §3.3): a credential carries AT MOST ONE
1318    /// session identifier in a disjoint namespace. Both-present is ambiguous
1319    /// and rejects (an active OIDC `sid` must never mask a revoked/unknown
1320    /// `workload_session_id`); a present-but-empty identifier is malformed and
1321    /// rejects; neither is `Ok(None)`. This is the single parser every
1322    /// authorization and cache-insertion path uses — never `sid.or(wsid)`.
1323    #[test]
1324    fn session_key_is_exact_one_never_or_else() {
1325        use crate::auth::credential::SessionIdentifier;
1326        let base =
1327            || Claims::new("alice".to_owned(), 0, 100).with_issuer("https://iss.test".to_owned());
1328
1329        // Neither → no session.
1330        assert_eq!(base().session_key(), Ok(None));
1331
1332        // sid only → the OIDC namespace, issuer-scoped.
1333        let oidc = base().with_sid("s1").session_key().unwrap().unwrap();
1334        assert_eq!(oidc.issuer, "https://iss.test");
1335        assert!(matches!(oidc.id, SessionIdentifier::OidcSid(ref v) if v == "s1"));
1336
1337        // workload id only → the disjoint workload namespace.
1338        let wl = base()
1339            .with_workload_session_id("w1")
1340            .session_key()
1341            .unwrap()
1342            .unwrap();
1343        assert!(matches!(wl.id, SessionIdentifier::WorkloadSessionId(ref v) if v == "w1"));
1344
1345        // Both present → ambiguous, rejected (no masking).
1346        assert_eq!(
1347            base()
1348                .with_sid("s1")
1349                .with_workload_session_id("w1")
1350                .session_key(),
1351            Err(SessionClaimError::AmbiguousSessionClaims)
1352        );
1353
1354        // Present-but-empty (or whitespace) identifier → malformed, rejected.
1355        assert_eq!(
1356            base().with_sid("").session_key(),
1357            Err(SessionClaimError::EmptySessionIdentifier)
1358        );
1359        assert_eq!(
1360            base().with_sid("   ").session_key(),
1361            Err(SessionClaimError::EmptySessionIdentifier)
1362        );
1363        assert_eq!(
1364            base().with_workload_session_id("").session_key(),
1365            Err(SessionClaimError::EmptySessionIdentifier)
1366        );
1367    }
1368
1369    #[test]
1370    fn test_claims_with_audience() {
1371        let claims = Claims::new("alice".to_owned(), 1000, 2000)
1372            .with_audience(Some("https://api.example.com".to_owned()));
1373        assert_eq!(claims.aud, Some("https://api.example.com".to_owned()));
1374    }
1375
1376    #[test]
1377    fn test_claims_with_token() {
1378        let claims =
1379            Claims::new("alice".to_owned(), 1000, 2000).with_token("eyJ.test.token".to_owned());
1380        assert_eq!(claims.token, Some("eyJ.test.token".to_owned()));
1381    }
1382
1383    #[test]
1384    fn test_claims_token_not_in_json() {
1385        let claims =
1386            Claims::new("alice".to_owned(), 1000, 2000).with_token("eyJ.secret.token".to_owned());
1387        let json = serde_json::to_string(&claims).unwrap();
1388        assert!(!json.contains("secret"));
1389        assert!(!json.contains("token"));
1390    }
1391
1392    #[test]
1393    fn test_claims_debug_redacts_token() {
1394        let claims =
1395            Claims::new("alice".to_owned(), 1000, 2000).with_token("eyJ.secret.token".to_owned());
1396        let debug = format!("{:?}", claims);
1397        assert!(debug.contains("[REDACTED]"));
1398        assert!(!debug.contains("secret"));
1399    }
1400
1401    #[test]
1402    fn test_claims_subject() {
1403        use crate::envelope::Subject;
1404        let claims = Claims::new("alice".to_owned(), 1000, 2000);
1405        assert_eq!(Subject::from(&claims), Subject::new("alice"));
1406
1407        let sentinel = Claims::new(UNAUTHENTICATED_DID_SENTINEL.to_owned(), 1000, 2000);
1408        assert_eq!(Subject::from(&sentinel), Subject::anonymous());
1409    }
1410
1411    #[test]
1412    fn test_claims_is_local_to() {
1413        let local = Claims::new("alice".to_owned(), 0, 9999)
1414            .with_issuer("https://local.example.com".to_owned());
1415        let federated = Claims::new("bob".to_owned(), 0, 9999)
1416            .with_issuer("https://other.example.com".to_owned());
1417        let legacy = Claims::new("carol".to_owned(), 0, 9999); // empty iss
1418
1419        assert!(local.is_local_to(&["https://local.example.com"]));
1420        assert!(!local.is_local_to(&["https://other.example.com"]));
1421        assert!(!federated.is_local_to(&["https://local.example.com"]));
1422        // Empty iss is always local — cluster-internal tokens have no issuer claim
1423        assert!(legacy.is_local_to(&[]));
1424        assert!(legacy.is_local_to(&["https://local.example.com"]));
1425    }
1426
1427    #[test]
1428    fn test_claims_subject_method() {
1429        use crate::envelope::Subject;
1430
1431        let local = Claims::new("alice".to_owned(), 0, 9999)
1432            .with_issuer("https://node.example.com".to_owned());
1433        let federated = Claims::new("bob".to_owned(), 0, 9999)
1434            .with_issuer("https://other.example.com".to_owned());
1435        let no_sub = Claims::new(String::new(), 0, 9999);
1436        let sentinel = Claims::new(UNAUTHENTICATED_DID_SENTINEL.to_owned(), 0, 9999)
1437            .with_issuer("https://node.example.com".to_owned());
1438
1439        assert_eq!(
1440            local.subject(&["https://node.example.com"]),
1441            Subject::new("alice")
1442        );
1443        assert_eq!(
1444            federated.subject(&["https://node.example.com"]),
1445            Subject::federated("https://other.example.com", "bob")
1446        );
1447        assert_eq!(no_sub.subject(&[]), Subject::anonymous());
1448        assert_eq!(
1449            sentinel.subject(&["https://node.example.com"]),
1450            Subject::anonymous()
1451        );
1452    }
1453
1454    #[test]
1455    fn test_claims_roundtrip_with_iss() {
1456        use super::super::jwt;
1457        use ed25519_dalek::SigningKey;
1458
1459        let signing_key = SigningKey::from_bytes(&[42u8; 32]);
1460        let verifying_key = signing_key.verifying_key();
1461
1462        let claims = Claims::new("alice".to_owned(), 0, 9_999_999_999)
1463            .with_issuer("https://a.example.com".to_owned());
1464
1465        let token = jwt::encode(&claims, &signing_key);
1466        let decoded = jwt::decode(&token, &verifying_key, None).expect("decode failed");
1467
1468        assert_eq!(decoded.iss, "https://a.example.com");
1469        assert_eq!(decoded.sub, "alice");
1470        assert_eq!(decoded.exp, 9_999_999_999);
1471    }
1472
1473    #[test]
1474    fn test_claims_iss_absent_defaults_to_empty() {
1475        // Simulate an old token without the `iss` field.
1476        // `#[serde(default)]` must ensure deserialization succeeds with iss = "".
1477        let json = r#"{"sub":"bob","exp":9999999999,"iat":0}"#;
1478        let claims: Claims = serde_json::from_str(json)
1479            .expect("old token without iss should deserialize successfully");
1480        assert_eq!(claims.iss, "");
1481        assert_eq!(claims.sub, "bob");
1482    }
1483
1484    #[test]
1485    fn test_claims_iss_not_in_json_when_empty() {
1486        // Empty iss is serialized as `"iss":""` (no skip_serializing_if),
1487        // but we do NOT skip it — that is intentional per the field design.
1488        // This test just confirms iss is present in JSON output.
1489        let claims = Claims::new("alice".to_owned(), 0, 9_999_999_999)
1490            .with_issuer("https://cloud.example.com".to_owned());
1491        let json = serde_json::to_string(&claims).unwrap();
1492        assert!(json.contains("\"iss\":\"https://cloud.example.com\""));
1493    }
1494}
1495
1496// ─── OIDC ID Token Claims ──────────────────────────────────────────────────
1497
1498/// A value that serializes as either a single string or an array of strings.
1499///
1500/// OIDC Core Section 2 says `aud` is a JSON string or array. Many RPs break
1501/// if they receive an unexpected format, so we serialize as a string when there
1502/// is exactly one value and as an array otherwise.
1503#[derive(Clone, Debug, PartialEq, Eq)]
1504pub enum OneOrMany {
1505    /// Single value — serialized as a JSON string.
1506    One(String),
1507    /// Multiple values — serialized as a JSON array.
1508    Many(Vec<String>),
1509}
1510
1511impl OneOrMany {
1512    /// Create from a single value.
1513    pub fn one(value: impl Into<String>) -> Self {
1514        Self::One(value.into())
1515    }
1516
1517    /// Create from a list. Collapses to `One` when the list has a single element.
1518    pub fn from_vec(mut values: Vec<String>) -> Self {
1519        if values.len() == 1 {
1520            Self::One(values.swap_remove(0))
1521        } else {
1522            Self::Many(values)
1523        }
1524    }
1525
1526    /// Get the values as a slice-like iterator.
1527    pub fn as_slice(&self) -> &[String] {
1528        match self {
1529            Self::One(v) => std::slice::from_ref(v),
1530            Self::Many(v) => v,
1531        }
1532    }
1533}
1534
1535impl Serialize for OneOrMany {
1536    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1537        match self {
1538            Self::One(v) => serializer.serialize_str(v),
1539            Self::Many(v) => v.serialize(serializer),
1540        }
1541    }
1542}
1543
1544impl<'de> Deserialize<'de> for OneOrMany {
1545    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
1546        let value = serde_json::Value::deserialize(deserializer)?;
1547        match value {
1548            serde_json::Value::String(s) => Ok(Self::One(s)),
1549            serde_json::Value::Array(arr) => {
1550                let strings: std::result::Result<Vec<String>, _> = arr
1551                    .into_iter()
1552                    .map(|v| {
1553                        v.as_str().map(String::from).ok_or_else(|| {
1554                            serde::de::Error::custom("aud array must contain strings")
1555                        })
1556                    })
1557                    .collect();
1558                Ok(Self::from_vec(strings?))
1559            }
1560            _ => Err(serde::de::Error::custom("aud must be a string or array")),
1561        }
1562    }
1563}
1564
1565/// OIDC ID Token claims (OpenID Connect Core 1.0, Section 2).
1566///
1567/// Separate from [`Claims`] because:
1568/// - `aud` is the `client_id` (not the resource indicator)
1569/// - Includes user profile claims (name, email)
1570/// - Only issued by the OAuth token endpoint, not used in the RPC layer
1571/// - Different `typ` header (`"JWT"` vs `"at+jwt"` for access tokens)
1572#[derive(Clone, Debug, Serialize, Deserialize)]
1573pub struct IdTokenClaims {
1574    // ── Required (OIDC Core Section 2) ──────────────────────────────────
1575    /// Issuer URL.
1576    pub iss: String,
1577    /// Subject identifier — a stable UUID, not a username.
1578    pub sub: String,
1579    /// Audience — the client_id. Supports single string or array.
1580    pub aud: OneOrMany,
1581    /// Expiration time (Unix timestamp).
1582    pub exp: i64,
1583    /// Issued at (Unix timestamp).
1584    pub iat: i64,
1585
1586    // ── Conditional ─────────────────────────────────────────────────────
1587    /// OIDC nonce echoed from the authorization request.
1588    #[serde(skip_serializing_if = "Option::is_none")]
1589    pub nonce: Option<String>,
1590    /// Time of user authentication (Unix timestamp).
1591    #[serde(skip_serializing_if = "Option::is_none")]
1592    pub auth_time: Option<i64>,
1593    /// Authorized party (REQUIRED when aud has multiple values).
1594    #[serde(skip_serializing_if = "Option::is_none")]
1595    pub azp: Option<String>,
1596    /// Authority-verified hosted-account tenant for local token exchange.
1597    #[serde(skip_serializing_if = "Option::is_none")]
1598    pub tenant: Option<String>,
1599
1600    // ── Profile claims (included based on requested scopes) ─────────────
1601    /// Full name.
1602    #[serde(skip_serializing_if = "Option::is_none")]
1603    pub name: Option<String>,
1604    /// Email address.
1605    #[serde(skip_serializing_if = "Option::is_none")]
1606    pub email: Option<String>,
1607    /// Whether the email is verified.
1608    #[serde(skip_serializing_if = "Option::is_none")]
1609    pub email_verified: Option<bool>,
1610    /// Preferred display username.
1611    #[serde(skip_serializing_if = "Option::is_none")]
1612    pub preferred_username: Option<String>,
1613}
1614
1615impl IdTokenClaims {
1616    /// Create minimal id_token claims (required fields only).
1617    pub fn new(iss: String, sub: String, aud: String, iat: i64, exp: i64) -> Self {
1618        Self {
1619            iss,
1620            sub,
1621            aud: OneOrMany::one(aud),
1622            exp,
1623            iat,
1624            nonce: None,
1625            auth_time: None,
1626            azp: None,
1627            tenant: None,
1628            name: None,
1629            email: None,
1630            email_verified: None,
1631            preferred_username: None,
1632        }
1633    }
1634
1635    /// Set the OIDC nonce (echoed from the authorization request).
1636    pub fn with_nonce(mut self, nonce: Option<String>) -> Self {
1637        self.nonce = nonce;
1638        self
1639    }
1640
1641    /// Set the authentication time.
1642    pub fn with_auth_time(mut self, auth_time: i64) -> Self {
1643        self.auth_time = Some(auth_time);
1644        self
1645    }
1646
1647    /// Bind this local ID token to the user's hosted-account tenant.
1648    pub fn with_tenant(mut self, tenant: String) -> Self {
1649        self.tenant = Some(tenant);
1650        self
1651    }
1652
1653    /// Set profile claims from a user profile.
1654    pub fn with_profile(
1655        mut self,
1656        name: Option<String>,
1657        email: Option<String>,
1658        email_verified: Option<bool>,
1659        preferred_username: Option<String>,
1660    ) -> Self {
1661        self.name = name;
1662        self.email = email;
1663        self.email_verified = email_verified;
1664        self.preferred_username = preferred_username;
1665        self
1666    }
1667}
1668
1669#[cfg(test)]
1670#[allow(clippy::unwrap_used, clippy::expect_used)]
1671mod id_token_tests {
1672    use super::*;
1673
1674    #[test]
1675    fn test_id_token_claims_serialization() {
1676        let claims = IdTokenClaims::new(
1677            "https://example.com".into(),
1678            "f47ac10b-58cc-4372-a567-0e02b2c3d479".into(),
1679            "my-client".into(),
1680            1000,
1681            2000,
1682        );
1683        let json = serde_json::to_string(&claims).unwrap();
1684        // aud should be a single string, not array
1685        assert!(json.contains("\"aud\":\"my-client\""));
1686        assert!(json.contains("\"sub\":\"f47ac10b-"));
1687        // Optional fields should not appear
1688        assert!(!json.contains("nonce"));
1689        assert!(!json.contains("name"));
1690        assert!(!json.contains("email"));
1691    }
1692
1693    #[test]
1694    fn test_id_token_claims_with_profile() {
1695        let claims = IdTokenClaims::new(
1696            "https://example.com".into(),
1697            "uuid-123".into(),
1698            "client-1".into(),
1699            1000,
1700            2000,
1701        )
1702        .with_nonce(Some("abc123".into()))
1703        .with_auth_time(999)
1704        .with_profile(
1705            Some("Alice".into()),
1706            Some("alice@example.com".into()),
1707            Some(true),
1708            Some("alice".into()),
1709        );
1710        let json = serde_json::to_string(&claims).unwrap();
1711        assert!(json.contains("\"nonce\":\"abc123\""));
1712        assert!(json.contains("\"auth_time\":999"));
1713        assert!(json.contains("\"name\":\"Alice\""));
1714        assert!(json.contains("\"email\":\"alice@example.com\""));
1715        assert!(json.contains("\"email_verified\":true"));
1716        assert!(json.contains("\"preferred_username\":\"alice\""));
1717    }
1718
1719    #[test]
1720    fn test_one_or_many_single() {
1721        let aud = OneOrMany::one("client-1");
1722        let json = serde_json::to_string(&aud).unwrap();
1723        assert_eq!(json, "\"client-1\"");
1724    }
1725
1726    #[test]
1727    fn test_one_or_many_multiple() {
1728        let aud = OneOrMany::from_vec(vec!["a".into(), "b".into()]);
1729        let json = serde_json::to_string(&aud).unwrap();
1730        assert_eq!(json, "[\"a\",\"b\"]");
1731    }
1732
1733    #[test]
1734    fn test_one_or_many_deserialize_string() {
1735        let aud: OneOrMany = serde_json::from_str("\"client-1\"").unwrap();
1736        assert_eq!(aud, OneOrMany::One("client-1".into()));
1737    }
1738
1739    #[test]
1740    fn test_one_or_many_deserialize_array() {
1741        let aud: OneOrMany = serde_json::from_str("[\"a\",\"b\"]").unwrap();
1742        assert_eq!(aud, OneOrMany::Many(vec!["a".into(), "b".into()]));
1743    }
1744
1745    #[test]
1746    fn test_one_or_many_collapse_single_element() {
1747        let aud = OneOrMany::from_vec(vec!["only-one".into()]);
1748        assert_eq!(aud, OneOrMany::One("only-one".into()));
1749    }
1750
1751    // ── Delegation actor chain (RFC 8693 `act`) ─────────────────────────
1752
1753    /// `terminal_actor()` resolves the deepest hop of the delegation chain.
1754    /// (v16 credentials are Reusable-only; the one-shot credential-use profile
1755    /// was cut from scope — see the module comment.)
1756    #[test]
1757    fn terminal_actor_resolves_the_deepest_delegation_hop() {
1758        let inner = ActClaim {
1759            sub: "service:worker".into(),
1760            clearance: None,
1761            act: None,
1762        };
1763        let outer = ActClaim {
1764            sub: "service:mcp".into(),
1765            clearance: None,
1766            act: Some(Box::new(inner)),
1767        };
1768        let c = Claims::new("user:alice".into(), 1000, 1030).with_actor(Some(outer));
1769        assert_eq!(c.terminal_actor(), Some("service:worker"));
1770
1771        // No delegation chain resolves to no terminal actor.
1772        let plain = Claims::new("user:alice".into(), 1000, 1030);
1773        assert_eq!(plain.terminal_actor(), None);
1774    }
1775
1776    #[test]
1777    fn federate_generation_is_signed_jwt_only_and_canonical() {
1778        let original = [0x42; 32];
1779        let claims = Claims::new("alice".into(), 1, 2).with_session_authority_generation(original);
1780        assert_eq!(
1781            claims.session_authority_generation().unwrap(),
1782            Some(original)
1783        );
1784        let json = serde_json::to_vec(&claims).unwrap();
1785        let decoded: Claims = serde_json::from_slice(&json).unwrap();
1786        assert_eq!(
1787            decoded.session_authority_generation().unwrap(),
1788            Some(original)
1789        );
1790        let mut malformed = decoded.clone();
1791        for bad in [
1792            "",
1793            "A",
1794            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
1795            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+",
1796        ] {
1797            malformed.hs_session_authority_generation = Some(bad.into());
1798            assert!(
1799                malformed.session_authority_generation().is_err(),
1800                "accepted {bad:?}"
1801            );
1802        }
1803        assert!(Claims::new("alice".into(), 1, 2)
1804            .session_authority_generation()
1805            .unwrap()
1806            .is_none());
1807    }
1808
1809    #[test]
1810    fn federate_signer_inventory_is_signed_jwt_only_and_canonical() {
1811        let original = [0x24; 32];
1812        let claims = Claims::new("alice".into(), 1, 2).with_federate_signer_inventory(original);
1813        assert_eq!(claims.federate_signer_inventory().unwrap(), Some(original));
1814        let json = serde_json::to_vec(&claims).unwrap();
1815        let decoded: Claims = serde_json::from_slice(&json).unwrap();
1816        assert_eq!(decoded.federate_signer_inventory().unwrap(), Some(original));
1817        let mut malformed = decoded.clone();
1818        for bad in [
1819            "",
1820            "A",
1821            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
1822            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+",
1823        ] {
1824            malformed.hs_signer_inventory_v1 = Some(bad.into());
1825            assert!(
1826                malformed.federate_signer_inventory().is_err(),
1827                "accepted {bad:?}"
1828            );
1829        }
1830        assert!(Claims::new("alice".into(), 1, 2)
1831            .federate_signer_inventory()
1832            .unwrap()
1833            .is_none());
1834    }
1835}