Skip to main content

hyprstream_core/auth/
service_jwt.rs

1//! Shared helper for service JWT issuance with load-or-renew semantics.
2//!
3//! Both the wizard and bootstrap manager use this function to avoid
4//! duplicating the "load existing JWT, renew if within 7 days of expiry"
5//! logic.
6
7use std::path::Path;
8
9use anyhow::Result;
10use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
11use ed25519_dalek::{SigningKey, VerifyingKey};
12
13const NEW_EXPIRY_TTL: i64 = 30 * 86_400;
14const RENEW_THRESHOLD: i64 = 7 * 86_400;
15
16/// Load an existing service JWT from disk, or sign a new one if absent,
17/// within `RENEW_THRESHOLD` seconds of expiry, not binding the local issuer
18/// URL in BOTH `iss` and `aud`, or carrying a classical (non-PQ-covering)
19/// header alg — the last two are backfills that re-mint tokens older
20/// bootstraps (or older renewal paths, which stamped `iss` but not `aud`)
21/// produced in shapes the composite dispatch verification now rejects.
22///
23/// Does NOT write to disk — callers are responsible for persisting the
24/// returned JWT via `identity_store::write_service_jwt`.
25pub fn issue_or_load_service_jwt(
26    credentials_dir: &Path,
27    service_name: &str,
28    ca_jwt_key: &SigningKey,
29    bootstrap: &super::identity_store::BootstrapPubkey,
30    local_issuer_url: &str,
31    now: i64,
32    target_clearance: Option<&hyprstream_rpc::auth::mac::SecurityLabel>,
33) -> Result<String> {
34    let service_vk = &bootstrap.ed25519;
35    // v16 confirmation (frozen A §1.1/§5): the service credential's
36    // `cnf.hs_signer_suite` is the content thumbprint over the SERVICE's own
37    // enrolled primary signer group — Ed25519 plus, when the identity is
38    // hybrid, ML-DSA-65 — taken directly from the authoritative BootstrapPubkey
39    // (never re-derived from the public Ed key or hidden global state).
40    let ml_dsa_bytes = bootstrap
41        .ml_dsa_65
42        .as_ref()
43        .map(hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes);
44    let expected_hs = hyprstream_rpc::auth::service_signer_suite_b64(
45        &service_vk.to_bytes(),
46        ml_dsa_bytes.as_deref(),
47    );
48    let existing = super::identity_store::load_service_jwt(credentials_dir, service_name)?;
49    let needs_issue = match existing {
50        None => true,
51        Some(ref jwt) => {
52            let exp = decode_jwt_exp(jwt).unwrap_or(0);
53            // Re-issue if near expiry OR if the persisted token does not bind
54            // the local issuer URL in BOTH `iss` and `aud` (older bootstraps
55            // minted empty-issuer service JWTs, which the #328 gate rejects
56            // on the IPC/AnySigner plane — see below — and older renewal
57            // paths stamped `iss` without `aud`, which strict composite
58            // audience validation rejects on every dispatch) OR if the
59            // persisted token's header alg is not PQ-covering (older
60            // bootstraps minted classical EdDSA service JWTs, which the
61            // mandatory Hybrid dispatch policy rejects at registration — the
62            // same backfill shape).
63            (exp - now) <= RENEW_THRESHOLD
64                || !claims_bind_local_issuer(jwt, local_issuer_url)
65                || !header_alg_covers_pq(jwt)
66                // Full binding validation before reuse: a corrupted or
67                // foreign persisted token must force reissue here, not a
68                // later boot failure — verify the CA composite signature,
69                // exact subject, cnf key binding, and required jti.
70                || !persisted_token_binds(jwt, ca_jwt_key, service_name, service_vk, &expected_hs)
71                // The persisted token's clearance must equal the enrollment
72                // target's WIRE PROJECTION (level + compartments; assurance is
73                // never on the wire): a clearance-less or stale-clearance token
74                // is re-minted, never reused (v16 §11 — renewal cannot preserve
75                // authority the enrollment no longer grants, and an enrolled
76                // credential never goes clearance-less).
77                || decode_jwt_clearance(jwt)
78                    != target_clearance
79                        .map(|c| hyprstream_rpc::auth::mac::CredentialClearance::from_label(*c))
80        }
81    };
82
83    if !needs_issue {
84        if let Some(jwt) = existing {
85            return Ok(jwt);
86        }
87    }
88
89    let expiry = now + NEW_EXPIRY_TTL;
90    // Set `iss` to the local issuer URL — NOT empty.
91    //
92    // Service JWTs are presented service->service over the local IPC (UDS)
93    // plane, which the dispatch core verifies as `AnySigner`. The #328 gate
94    // rejects an EMPTY `iss` from any `AnySigner` (non-`is_local_caller`)
95    // caller, so an empty-issuer service JWT is rejected on exactly the plane
96    // it is meant for, and (with #441's fail-closed registration) the service
97    // refuses to start. Stamping the local issuer URL makes the token pass
98    // `ClusterKeySource::is_trusted` (issuer == local_issuer_url -> CA key)
99    // WITHOUT weakening #328: a networked peer still cannot present an
100    // empty-`iss` token, and a non-local issuer is still rejected.
101    let mut claims =
102        hyprstream_rpc::auth::Claims::new(format!("service:{service_name}"), now, expiry)
103            // v16 confirmation (the authoritative signer-suite thumbprint) stamped
104            // alongside the legacy single-key `cnf.jwk` (never replacing it).
105            .with_cnf_jwk(service_vk.as_bytes())
106            .with_cnf_hs_signer_suite(expected_hs.clone());
107    if !local_issuer_url.is_empty() {
108        // Stamp `aud` alongside `iss`: composite verification is strict about
109        // the audience (an absent `aud` is rejected when the verifier expects
110        // one), and every service's expected audience is this same issuer URL.
111        claims = claims
112            .with_issuer(local_issuer_url.to_owned())
113            .with_audience(Some(local_issuer_url.to_owned()));
114    }
115    // Stamp the enrollment target clearance (v16 §11): the bootstrap/wizard
116    // mint is clearance-bearing when the deployment has an enrollment
117    // manifest. `None` (legacy, no manifest) mints without the claim.
118    if let Some(clearance) = target_clearance {
119        claims = claims.with_clearance(*clearance);
120    }
121
122    // Mint the mandatory hybrid (ML-DSA-65-Ed25519) form: the dispatch plane
123    // enforces a Hybrid crypto policy with no bypass, so a classical EdDSA
124    // service JWT would be rejected at the very first registration and a
125    // clean deployment could never start. The post-quantum half is derived
126    // deterministically from the CA JWT signing key — the same self-contained
127    // derivation `BootstrapPubkey::for_service_key` uses for service
128    // identities — so nothing new is persisted, protected, or rotated.
129    let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(ca_jwt_key);
130    let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
131    Ok(hyprstream_rpc::auth::jwt::encode_service_jwt_hybrid(
132        &claims, ca_jwt_key, &ca_pq, &ca_pq_vk,
133    ))
134}
135
136/// Whether the persisted token binds the local issuer URL in BOTH `iss` and
137/// `aud` — the shape a fresh mint produces. An empty `iss` always forces a
138/// re-issue (the #328 gate rejects it); when a local issuer URL is
139/// configured, a mismatched `iss` or a missing/mismatched `aud` (older
140/// renewal paths stamped `iss` without `aud`) forces one too, because strict
141/// composite audience validation rejects such tokens on every dispatch.
142fn claims_bind_local_issuer(jwt: &str, local_issuer_url: &str) -> bool {
143    let iss = decode_jwt_iss(jwt);
144    if iss.as_deref().is_none_or(str::is_empty) {
145        return false;
146    }
147    if local_issuer_url.is_empty() {
148        return true;
149    }
150    iss.as_deref() == Some(local_issuer_url)
151        && decode_jwt_aud(jwt).as_deref() == Some(local_issuer_url)
152}
153
154/// Whether the persisted token's header `alg` carries a post-quantum
155/// component. Classical (`EdDSA`) tokens fail the mandatory Hybrid dispatch
156/// policy and must be re-minted.
157fn header_alg_covers_pq(jwt: &str) -> bool {
158    matches!(
159        hyprstream_rpc::auth::jwt::header_alg(jwt)
160            .ok()
161            .flatten()
162            .as_deref(),
163        Some("ML-DSA-65" | "ML-DSA-65-Ed25519")
164    )
165}
166
167/// Full binding validation of a persisted service JWT before reuse: verify
168/// the CA's composite signature and require the exact subject, the cnf key
169/// binding to this service's verifying key, and a present `jti`. Any parse,
170/// signature, or binding failure returns false (forcing reissue) — reuse
171/// decides from VERIFIED fields, never unsigned decodes alone.
172fn persisted_token_binds(
173    jwt: &str,
174    ca_jwt_key: &SigningKey,
175    service_name: &str,
176    service_vk: &VerifyingKey,
177    expected_hs: &str,
178) -> bool {
179    let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(ca_jwt_key);
180    let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
181    let Ok(dispatch) = hyprstream_rpc::auth::jwt::parse_composite_dispatch(jwt, &["wit+jwt"])
182    else {
183        return false;
184    };
185    let Ok(claims) = hyprstream_rpc::auth::jwt::decode_composite(
186        jwt,
187        &ca_pq_vk,
188        &ca_jwt_key.verifying_key(),
189        None,
190        &dispatch,
191    ) else {
192        return false;
193    };
194    // A legacy persisted token bound only by `cnf.jwk` (no v16
195    // `cnf.hs_signer_suite`, or a stale one) is NOT reused — it reissues with
196    // the authoritative confirmation, so the service credential C admits is a
197    // v16 credential, never a legacy-only one.
198    let hs_binds = claims
199        .cnf
200        .as_ref()
201        .and_then(|c| c.hs_signer_suite.as_deref())
202        == Some(expected_hs);
203    claims.sub == format!("service:{service_name}")
204        && claims.cnf_key_bytes() == Some(service_vk.to_bytes())
205        && claims.jti.is_some()
206        && hs_binds
207}
208
209/// Decode the two-axis `clearance` claim (`[level, [compartments]]`) without
210/// verifying the signature — the reuse predicate's enrollment-currency check (a
211/// mismatched or missing clearance forces re-issue). Returns `None` when the
212/// token carries no clearance or the claim is not a well-formed two-axis wire
213/// value. The assurance axis is never on the wire; comparison is against the
214/// enrollment target's wire projection (level + compartments).
215fn decode_jwt_clearance(jwt: &str) -> Option<hyprstream_rpc::auth::mac::CredentialClearance> {
216    let payload_b64 = jwt.split('.').nth(1)?;
217    let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
218    let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
219    serde_json::from_value(value.get("clearance")?.clone()).ok()
220}
221
222fn decode_jwt_exp(jwt: &str) -> Option<i64> {
223    let payload_b64 = jwt.split('.').nth(1)?;
224    let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
225    let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
226    value.get("exp")?.as_i64()
227}
228
229/// Decode the `iss` claim without verifying the signature. Used only to detect
230/// legacy empty-issuer service JWTs that must be re-minted (see the #328 note
231/// in `issue_or_load_service_jwt`). Returns `None` if the token is malformed or
232/// carries no `iss` claim.
233fn decode_jwt_iss(jwt: &str) -> Option<String> {
234    let payload_b64 = jwt.split('.').nth(1)?;
235    let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
236    let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
237    value.get("iss")?.as_str().map(ToOwned::to_owned)
238}
239
240/// Decode the `aud` claim without verifying the signature — the `iss` twin
241/// used by the aud-backfill check in `issue_or_load_service_jwt`.
242fn decode_jwt_aud(jwt: &str) -> Option<String> {
243    let payload_b64 = jwt.split('.').nth(1)?;
244    let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
245    let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
246    value.get("aud")?.as_str().map(ToOwned::to_owned)
247}
248
249#[cfg(test)]
250#[allow(clippy::unwrap_used, clippy::expect_used)]
251mod tests {
252    use super::super::identity_store::BootstrapPubkey;
253    use super::*;
254    use ed25519_dalek::SigningKey;
255
256    /// Classical (single Ed25519) BootstrapPubkey for the service-JWT tests.
257    fn bp(vk: ed25519_dalek::VerifyingKey) -> BootstrapPubkey {
258        BootstrapPubkey {
259            ed25519: vk,
260            ml_dsa_65: None,
261        }
262    }
263
264    /// A freshly issued service JWT carries the local issuer URL (NOT empty).
265    /// Empty `iss` is rejected on the IPC/AnySigner plane by the #328 gate, so
266    /// stamping the local issuer is what lets service-to-service registration
267    /// succeed fail-closed (with #441).
268    #[test]
269    fn issued_service_jwt_carries_local_issuer() {
270        let dir = tempfile::tempdir().unwrap();
271        let ca = SigningKey::from_bytes(&[3u8; 32]);
272        let svc = SigningKey::from_bytes(&[4u8; 32]);
273        let issuer = "http://localhost:6791";
274
275        let jwt = issue_or_load_service_jwt(
276            dir.path(),
277            "model",
278            &ca,
279            &bp(svc.verifying_key()),
280            issuer,
281            1_000_000,
282            None,
283        )
284        .unwrap();
285
286        assert_eq!(decode_jwt_iss(&jwt).as_deref(), Some(issuer));
287    }
288
289    /// PolicyService gets a `service:policy` JWT just like every other service
290    /// (#448). Bootstrap no longer skips it: it mints a CA-signed JWT whose
291    /// `cnf` binds the root/CA verifying key — the same key recorded in
292    /// `bootstrap_pubkeys["policy"]` and the key PolicyService actually signs
293    /// RPC responses with. This test encodes that invariant directly so the
294    /// "skip policy" regression cannot silently return: trust-store key ==
295    /// JWT `cnf` == actual signer, all three equal to `root_key`'s verifying
296    /// key.
297    #[test]
298    fn policy_service_jwt_is_symmetric_and_binds_root_key() {
299        let dir = tempfile::tempdir().unwrap();
300        // The CA: PolicyService's identity IS the root/CA key.
301        let root_key = SigningKey::from_bytes(&[7u8; 32]);
302        // The CA JWT signing key is purpose-derived from the root key, exactly
303        // as `do_bootstrap` derives it before signing any service JWT.
304        let ca_jwt_key =
305            hyprstream_rpc::node_identity::derive_purpose_key(&root_key, "hyprstream-jwt-v1");
306        let issuer = "http://localhost:6791";
307
308        // Reproduce the policy branch of the bootstrap loop: service_key ==
309        // root_key (NOT an independent per-service key), then issue + persist.
310        let policy_key = root_key.clone();
311        let policy_vk = policy_key.verifying_key();
312        let jwt = issue_or_load_service_jwt(
313            dir.path(),
314            "policy",
315            &ca_jwt_key,
316            &bp(policy_vk),
317            issuer,
318            1_000_000,
319            None,
320        )
321        .unwrap();
322        super::super::identity_store::write_service_jwt(dir.path(), "policy", &jwt).unwrap();
323
324        // The JWT is persisted at policy/service-jwt (not skipped).
325        let loaded = super::super::identity_store::load_service_jwt(dir.path(), "policy").unwrap();
326        assert_eq!(loaded.as_deref(), Some(jwt.as_str()));
327
328        // Subject is service:policy.
329        let payload_b64 = jwt.split('.').nth(1).unwrap();
330        let payload = URL_SAFE_NO_PAD.decode(payload_b64).unwrap();
331        let value: serde_json::Value = serde_json::from_slice(&payload).unwrap();
332        assert_eq!(
333            value.get("sub").and_then(|v| v.as_str()),
334            Some("service:policy")
335        );
336
337        // cnf.jwk binds the root verifying key — what the trust store records
338        // for "policy" and what PolicyService signs with.
339        let cnf = value.get("cnf").and_then(|v| v.get("jwk"));
340        assert!(cnf.is_some(), "policy service JWT must carry a cnf.jwk");
341        // The JWK thumbprint representation here is the raw 32-byte verifying
342        // key (x); compare against root_key.verifying_key() bytes.
343        let x = cnf
344            .and_then(|v| v.get("x"))
345            .and_then(|v| v.as_str())
346            .unwrap();
347        let x_bytes = URL_SAFE_NO_PAD.decode(x).unwrap();
348        assert_eq!(
349            x_bytes.as_slice(),
350            root_key.verifying_key().as_bytes(),
351            "cnf.jwk must bind root_key.verifying_key(), the key bootstrap registers for policy"
352        );
353
354        // And that equals what bootstrap would register in bootstrap_pubkeys.
355        assert_eq!(root_key.verifying_key().as_bytes(), policy_vk.as_bytes());
356    }
357
358    /// A persisted classical (EdDSA) service JWT is re-minted as hybrid on
359    /// load, even when far from expiry and carrying an issuer — classical
360    /// tokens fail the mandatory Hybrid dispatch policy at registration, so
361    /// an upgrade heals them the same way the empty-`iss` backfill does.
362    #[test]
363    fn classical_persisted_jwt_is_reissued_hybrid() {
364        let dir = tempfile::tempdir().unwrap();
365        let ca = SigningKey::from_bytes(&[3u8; 32]);
366        let svc = SigningKey::from_bytes(&[4u8; 32]);
367        let issuer = "http://localhost:6791";
368        // Real wall-clock time: the re-minted token is verified through
369        // decode_composite below, which enforces iat/exp against the clock.
370        let now = chrono::Utc::now().timestamp();
371
372        // A classical token with issuer + far-future expiry, persisted.
373        let legacy_claims =
374            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 30 * 86_400)
375                .with_issuer(issuer.to_owned())
376                .with_cnf_jwk(svc.verifying_key().as_bytes());
377        let legacy = hyprstream_rpc::auth::jwt::encode_service_jwt(&legacy_claims, &ca);
378        super::super::identity_store::write_service_jwt(dir.path(), "model", &legacy).unwrap();
379
380        let jwt = issue_or_load_service_jwt(
381            dir.path(),
382            "model",
383            &ca,
384            &bp(svc.verifying_key()),
385            issuer,
386            now,
387            None,
388        )
389        .unwrap();
390        assert_ne!(jwt, legacy, "classical token must not be returned as-is");
391        assert_eq!(
392            hyprstream_rpc::auth::jwt::header_alg(&jwt)
393                .unwrap()
394                .as_deref(),
395            Some("ML-DSA-65-Ed25519"),
396        );
397
398        // The re-minted token verifies against the exact derived pair, via the
399        // real composite dispatch path.
400        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca);
401        let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
402        let dispatch =
403            hyprstream_rpc::auth::jwt::parse_composite_dispatch(&jwt, &["wit+jwt"]).unwrap();
404        let verified = hyprstream_rpc::auth::jwt::decode_composite(
405            &jwt,
406            &ca_pq_vk,
407            &ca.verifying_key(),
408            None,
409            &dispatch,
410        )
411        .unwrap();
412        assert_eq!(verified.sub, "service:model");
413        assert_eq!(verified.iss, issuer);
414    }
415
416    /// A persisted hybrid token that carries `iss` but NO `aud` (the shape an
417    /// older renewal path produced) is re-issued with both bound to the local
418    /// issuer URL — strict composite audience validation rejects an aud-less
419    /// token on every dispatch, so it must not be treated as current.
420    #[test]
421    fn audless_persisted_hybrid_jwt_is_reissued_with_audience() {
422        let dir = tempfile::tempdir().unwrap();
423        let ca = SigningKey::from_bytes(&[3u8; 32]);
424        let svc = SigningKey::from_bytes(&[4u8; 32]);
425        let issuer = "http://localhost:6791";
426        let now = chrono::Utc::now().timestamp();
427
428        // Hybrid, far from expiry, correct issuer — but no aud.
429        let legacy_claims =
430            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 30 * 86_400)
431                .with_issuer(issuer.to_owned())
432                .with_cnf_jwk(svc.verifying_key().as_bytes());
433        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca);
434        let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
435        let legacy = hyprstream_rpc::auth::jwt::encode_service_jwt_hybrid(
436            &legacy_claims,
437            &ca,
438            &ca_pq,
439            &ca_pq_vk,
440        );
441        assert!(decode_jwt_aud(&legacy).is_none());
442        super::super::identity_store::write_service_jwt(dir.path(), "model", &legacy).unwrap();
443
444        let jwt = issue_or_load_service_jwt(
445            dir.path(),
446            "model",
447            &ca,
448            &bp(svc.verifying_key()),
449            issuer,
450            now,
451            None,
452        )
453        .unwrap();
454        assert_ne!(jwt, legacy, "aud-less token must not be returned as-is");
455        assert_eq!(decode_jwt_iss(&jwt).as_deref(), Some(issuer));
456        assert_eq!(decode_jwt_aud(&jwt).as_deref(), Some(issuer));
457
458        // The re-minted token passes strict composite audience validation.
459        let dispatch =
460            hyprstream_rpc::auth::jwt::parse_composite_dispatch(&jwt, &["wit+jwt"]).unwrap();
461        hyprstream_rpc::auth::jwt::decode_composite(
462            &jwt,
463            &ca_pq_vk,
464            &ca.verifying_key(),
465            Some(issuer),
466            &dispatch,
467        )
468        .unwrap();
469    }
470
471    /// A persisted hybrid token far from expiry (with issuer) is returned
472    /// as-is — the alg backfill fires only for classical tokens.
473    #[test]
474    fn hybrid_persisted_jwt_is_returned_unchanged() {
475        let dir = tempfile::tempdir().unwrap();
476        let ca = SigningKey::from_bytes(&[3u8; 32]);
477        let svc = SigningKey::from_bytes(&[4u8; 32]);
478        let issuer = "http://localhost:6791";
479        // Real wall-clock time: reuse validation verifies the persisted
480        // token's composite signature, which enforces iat/exp against now.
481        let now = chrono::Utc::now().timestamp();
482
483        let first = issue_or_load_service_jwt(
484            dir.path(),
485            "model",
486            &ca,
487            &bp(svc.verifying_key()),
488            issuer,
489            now,
490            None,
491        )
492        .unwrap();
493        super::super::identity_store::write_service_jwt(dir.path(), "model", &first).unwrap();
494
495        let second = issue_or_load_service_jwt(
496            dir.path(),
497            "model",
498            &ca,
499            &bp(svc.verifying_key()),
500            issuer,
501            now,
502            None,
503        )
504        .unwrap();
505        assert_eq!(first, second);
506    }
507
508    /// A persisted legacy empty-issuer token is re-minted with the issuer set,
509    /// rather than being returned as-is — so an upgrade heals the #328 mismatch
510    /// on the next wizard/bootstrap run without manual intervention.
511    #[test]
512    fn empty_issuer_legacy_jwt_is_reissued_with_issuer() {
513        let dir = tempfile::tempdir().unwrap();
514        let ca = SigningKey::from_bytes(&[3u8; 32]);
515        let svc = SigningKey::from_bytes(&[4u8; 32]);
516
517        // Mint a legacy token with NO issuer and a far-future expiry, persist it.
518        let now = 1_000_000;
519        let legacy_claims =
520            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 30 * 86_400)
521                .with_cnf_jwk(svc.verifying_key().as_bytes());
522        let legacy = hyprstream_rpc::auth::jwt::encode_service_jwt(&legacy_claims, &ca);
523        assert!(decode_jwt_iss(&legacy).is_none_or(|s| s.is_empty()));
524        super::super::identity_store::write_service_jwt(dir.path(), "model", &legacy).unwrap();
525
526        // Even though it is far from expiry, the empty-iss legacy token forces a
527        // re-issue carrying the issuer.
528        let jwt = issue_or_load_service_jwt(
529            dir.path(),
530            "model",
531            &ca,
532            &bp(svc.verifying_key()),
533            "http://localhost:6791",
534            now,
535            None,
536        )
537        .unwrap();
538        assert_eq!(
539            decode_jwt_iss(&jwt).as_deref(),
540            Some("http://localhost:6791")
541        );
542    }
543
544    fn enrollment_label() -> hyprstream_rpc::auth::mac::SecurityLabel {
545        hyprstream_rpc::auth::mac::SecurityLabel::new(
546            hyprstream_rpc::auth::mac::Level::Internal,
547            hyprstream_rpc::auth::mac::Assurance::Classical,
548            hyprstream_rpc::auth::mac::CompartmentSet::EMPTY,
549        )
550    }
551
552    /// A manifest-backed mint stamps the enrollment target clearance, and a
553    /// persisted token whose clearance is MISSING or STALE is re-minted, not
554    /// reused — renewal never preserves authority the enrollment no longer
555    /// grants, and an enrolled credential never goes clearance-less.
556    #[test]
557    fn clearance_is_stamped_and_stale_or_missing_clearance_reissued() {
558        let dir = tempfile::tempdir().unwrap();
559        let ca = SigningKey::from_bytes(&[3u8; 32]);
560        let svc = SigningKey::from_bytes(&[4u8; 32]);
561        let issuer = "http://localhost:6791";
562        // Real wall-clock time: reuse validation verifies the persisted token's
563        // composite signature (`persisted_token_binds`), which enforces
564        // iat/exp against `now` — a fixed epoch would leave every persisted
565        // token expired and force a reissue on the same-target reuse path.
566        let now = chrono::Utc::now().timestamp();
567        let target = enrollment_label();
568
569        // Fresh mint carries the target clearance.
570        let jwt = issue_or_load_service_jwt(
571            dir.path(),
572            "model",
573            &ca,
574            &bp(svc.verifying_key()),
575            issuer,
576            now,
577            Some(&target),
578        )
579        .unwrap();
580        assert_eq!(
581            decode_jwt_clearance(&jwt),
582            Some(hyprstream_rpc::auth::mac::CredentialClearance::from_label(
583                target
584            ))
585        );
586        super::super::identity_store::write_service_jwt(dir.path(), "model", &jwt).unwrap();
587
588        // Same target: reused unchanged.
589        let second = issue_or_load_service_jwt(
590            dir.path(),
591            "model",
592            &ca,
593            &bp(svc.verifying_key()),
594            issuer,
595            now,
596            Some(&target),
597        )
598        .unwrap();
599        assert_eq!(jwt, second);
600
601        // Enrollment NARROWED (compartment added): the persisted token is
602        // stale and must be re-minted.
603        let narrowed = hyprstream_rpc::auth::mac::SecurityLabel::new(
604            hyprstream_rpc::auth::mac::Level::Secret,
605            hyprstream_rpc::auth::mac::Assurance::Classical,
606            hyprstream_rpc::auth::mac::CompartmentSet::EMPTY,
607        );
608        let reminted = issue_or_load_service_jwt(
609            dir.path(),
610            "model",
611            &ca,
612            &bp(svc.verifying_key()),
613            issuer,
614            now,
615            Some(&narrowed),
616        )
617        .unwrap();
618        assert_ne!(reminted, jwt, "stale-clearance token must not be reused");
619        assert_eq!(
620            decode_jwt_clearance(&reminted),
621            Some(hyprstream_rpc::auth::mac::CredentialClearance::from_label(
622                narrowed
623            ))
624        );
625
626        // A clearance-less legacy token under an enrollment target is
627        // re-minted with the clearance.
628        let legacy_claims =
629            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 30 * 86_400)
630                .with_issuer(issuer.to_owned())
631                .with_audience(Some(issuer.to_owned()))
632                .with_cnf_jwk(svc.verifying_key().as_bytes());
633        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca);
634        let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
635        let legacy = hyprstream_rpc::auth::jwt::encode_service_jwt_hybrid(
636            &legacy_claims,
637            &ca,
638            &ca_pq,
639            &ca_pq_vk,
640        );
641        super::super::identity_store::write_service_jwt(dir.path(), "model", &legacy).unwrap();
642        let healed = issue_or_load_service_jwt(
643            dir.path(),
644            "model",
645            &ca,
646            &bp(svc.verifying_key()),
647            issuer,
648            now,
649            Some(&target),
650        )
651        .unwrap();
652        assert_ne!(healed, legacy, "clearance-less token must not be reused");
653        assert_eq!(
654            decode_jwt_clearance(&healed),
655            Some(hyprstream_rpc::auth::mac::CredentialClearance::from_label(
656                target
657            ))
658        );
659    }
660
661    /// Reuse validates the persisted token's binding, not just its unsigned
662    /// fields: a tampered signature, a foreign cnf key, or a foreign subject
663    /// all force reissue.
664    #[test]
665    fn persisted_token_with_broken_binding_is_reissued() {
666        let dir = tempfile::tempdir().unwrap();
667        let ca = SigningKey::from_bytes(&[3u8; 32]);
668        let svc = SigningKey::from_bytes(&[4u8; 32]);
669        let issuer = "http://localhost:6791";
670        let now = chrono::Utc::now().timestamp();
671
672        let good = issue_or_load_service_jwt(
673            dir.path(),
674            "model",
675            &ca,
676            &bp(svc.verifying_key()),
677            issuer,
678            now,
679            None,
680        )
681        .unwrap();
682        super::super::identity_store::write_service_jwt(dir.path(), "model", &good).unwrap();
683
684        // Sanity: the good token is reused.
685        let reused = issue_or_load_service_jwt(
686            dir.path(),
687            "model",
688            &ca,
689            &bp(svc.verifying_key()),
690            issuer,
691            now,
692            None,
693        )
694        .unwrap();
695        assert_eq!(good, reused);
696
697        // Tampered signature (payload untouched, signature flipped) → the
698        // composite verification fails and the token is reissued.
699        let parts: Vec<&str> = good.split('.').collect();
700        let mut sig = URL_SAFE_NO_PAD.decode(parts[2]).unwrap();
701        sig[0] ^= 0x01;
702        let tampered = format!("{}.{}.{}", parts[0], parts[1], URL_SAFE_NO_PAD.encode(sig));
703        super::super::identity_store::write_service_jwt(dir.path(), "model", &tampered).unwrap();
704        let reissued = issue_or_load_service_jwt(
705            dir.path(),
706            "model",
707            &ca,
708            &bp(svc.verifying_key()),
709            issuer,
710            now,
711            None,
712        )
713        .unwrap();
714        assert_ne!(
715            reissued, tampered,
716            "tampered-signature token must be reissued"
717        );
718
719        // Foreign cnf (signed by the CA but bound to a DIFFERENT service key)
720        // → reissue.
721        let other_svc = SigningKey::from_bytes(&[9u8; 32]);
722        let foreign_claims =
723            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 30 * 86_400)
724                .with_issuer(issuer.to_owned())
725                .with_audience(Some(issuer.to_owned()))
726                .with_cnf_jwk(other_svc.verifying_key().as_bytes());
727        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca);
728        let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
729        let foreign = hyprstream_rpc::auth::jwt::encode_service_jwt_hybrid(
730            &foreign_claims,
731            &ca,
732            &ca_pq,
733            &ca_pq_vk,
734        );
735        super::super::identity_store::write_service_jwt(dir.path(), "model", &foreign).unwrap();
736        let reissued = issue_or_load_service_jwt(
737            dir.path(),
738            "model",
739            &ca,
740            &bp(svc.verifying_key()),
741            issuer,
742            now,
743            None,
744        )
745        .unwrap();
746        assert_ne!(reissued, foreign, "foreign-cnf token must be reissued");
747        // And the reissue binds the correct service key.
748        let dispatch =
749            hyprstream_rpc::auth::jwt::parse_composite_dispatch(&reissued, &["wit+jwt"]).unwrap();
750        let verified = hyprstream_rpc::auth::jwt::decode_composite(
751            &reissued,
752            &ca_pq_vk,
753            &ca.verifying_key(),
754            None,
755            &dispatch,
756        )
757        .unwrap();
758        assert_eq!(
759            verified.cnf_key_bytes(),
760            Some(svc.verifying_key().to_bytes())
761        );
762    }
763
764    /// Decode the raw `cnf` object from a JWT payload (unsigned) for assertions.
765    fn decode_cnf(jwt: &str) -> Option<serde_json::Value> {
766        let payload_b64 = jwt.split('.').nth(1)?;
767        let payload = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
768        let value: serde_json::Value = serde_json::from_slice(&payload).ok()?;
769        value.get("cnf").cloned()
770    }
771
772    /// A fresh HYBRID-enrolled service JWT stamps `cnf.hs_signer_suite` equal to
773    /// the authoritative signer-suite thumbprint over the service's own enrolled
774    /// Ed25519 + ML-DSA-65 keys, and preserves the legacy `cnf.jwk` alongside it.
775    #[test]
776    fn fresh_hybrid_service_jwt_stamps_authoritative_signer_suite() {
777        let dir = tempfile::tempdir().unwrap();
778        let ca = SigningKey::from_bytes(&[3u8; 32]);
779        let svc = SigningKey::from_bytes(&[4u8; 32]);
780        let (_svc_pq, svc_pq_vk) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
781        let issuer = "http://localhost:6791";
782        let now = chrono::Utc::now().timestamp();
783
784        let bootstrap = BootstrapPubkey {
785            ed25519: svc.verifying_key(),
786            ml_dsa_65: Some(svc_pq_vk.clone()),
787        };
788        let jwt =
789            issue_or_load_service_jwt(dir.path(), "model", &ca, &bootstrap, issuer, now, None)
790                .unwrap();
791
792        let expected = hyprstream_rpc::auth::service_signer_suite_b64(
793            &svc.verifying_key().to_bytes(),
794            Some(&hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(&svc_pq_vk)),
795        );
796        let cnf = decode_cnf(&jwt).expect("minted JWT carries cnf");
797        assert_eq!(
798            cnf.get("hs_signer_suite").and_then(|v| v.as_str()),
799            Some(expected.as_str()),
800            "cnf.hs_signer_suite must equal the authoritative hybrid signer suite"
801        );
802        // The legacy single-key jwk binding is preserved alongside it.
803        assert!(
804            cnf.get("jwk").and_then(|v| v.get("x")).is_some(),
805            "cnf.jwk must be preserved alongside hs_signer_suite"
806        );
807    }
808
809    /// Build an otherwise-current, correctly CA-signed hybrid persisted token
810    /// whose only defect is its `cnf.hs_signer_suite` (supplied via `hs`): `None`
811    /// omits it, `Some(x)` stamps `x`. Every OTHER reuse predicate
812    /// (iss/aud/sub/jti/cnf.jwk/clearance/expiry/alg) is satisfied, so the hs
813    /// gate is the ONLY predicate that can fire.
814    fn write_persisted_token_with_hs(
815        dir: &Path,
816        ca: &SigningKey,
817        svc: &SigningKey,
818        issuer: &str,
819        now: i64,
820        hs: Option<&str>,
821    ) {
822        let mut claims =
823            hyprstream_rpc::auth::Claims::new("service:model".to_owned(), now, now + 30 * 86_400)
824                .with_issuer(issuer.to_owned())
825                .with_audience(Some(issuer.to_owned()))
826                .with_cnf_jwk(svc.verifying_key().as_bytes())
827                .with_jti();
828        if let Some(hs) = hs {
829            claims = claims.with_cnf_hs_signer_suite(hs.to_owned());
830        }
831        let ca_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(ca);
832        let ca_pq_vk = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
833        let jwt =
834            hyprstream_rpc::auth::jwt::encode_service_jwt_hybrid(&claims, ca, &ca_pq, &ca_pq_vk);
835        super::super::identity_store::write_service_jwt(dir, "model", &jwt).unwrap();
836    }
837
838    /// An otherwise-current, correctly-signed hybrid persisted token that is
839    /// MISSING `cnf.hs_signer_suite` is reissued (never reused): the new v16 gate
840    /// fires even though every legacy predicate passes.
841    #[test]
842    fn persisted_token_missing_hs_signer_suite_is_reissued() {
843        let dir = tempfile::tempdir().unwrap();
844        let ca = SigningKey::from_bytes(&[3u8; 32]);
845        let svc = SigningKey::from_bytes(&[4u8; 32]);
846        let issuer = "http://localhost:6791";
847        let now = chrono::Utc::now().timestamp();
848
849        write_persisted_token_with_hs(dir.path(), &ca, &svc, issuer, now, None);
850        let existing = super::super::identity_store::load_service_jwt(dir.path(), "model")
851            .unwrap()
852            .unwrap();
853
854        let reissued = issue_or_load_service_jwt(
855            dir.path(),
856            "model",
857            &ca,
858            &bp(svc.verifying_key()),
859            issuer,
860            now,
861            None,
862        )
863        .unwrap();
864        assert_ne!(
865            reissued, existing,
866            "a legacy-only (no hs) token must be reissued"
867        );
868        // The reissue carries the authoritative hs.
869        let expected =
870            hyprstream_rpc::auth::service_signer_suite_b64(&svc.verifying_key().to_bytes(), None);
871        let cnf = decode_cnf(&reissued).unwrap();
872        assert_eq!(
873            cnf.get("hs_signer_suite").and_then(|v| v.as_str()),
874            Some(expected.as_str())
875        );
876    }
877
878    /// An otherwise-current persisted token carrying a STALE/WRONG
879    /// `cnf.hs_signer_suite` (a suite over a different key) is reissued.
880    #[test]
881    fn persisted_token_stale_hs_signer_suite_is_reissued() {
882        let dir = tempfile::tempdir().unwrap();
883        let ca = SigningKey::from_bytes(&[3u8; 32]);
884        let svc = SigningKey::from_bytes(&[4u8; 32]);
885        let other = SigningKey::from_bytes(&[9u8; 32]);
886        let issuer = "http://localhost:6791";
887        let now = chrono::Utc::now().timestamp();
888
889        // Wrong hs: the classical suite over a DIFFERENT key.
890        let wrong_hs =
891            hyprstream_rpc::auth::service_signer_suite_b64(&other.verifying_key().to_bytes(), None);
892        write_persisted_token_with_hs(dir.path(), &ca, &svc, issuer, now, Some(&wrong_hs));
893        let existing = super::super::identity_store::load_service_jwt(dir.path(), "model")
894            .unwrap()
895            .unwrap();
896
897        let reissued = issue_or_load_service_jwt(
898            dir.path(),
899            "model",
900            &ca,
901            &bp(svc.verifying_key()),
902            issuer,
903            now,
904            None,
905        )
906        .unwrap();
907        assert_ne!(reissued, existing, "a stale-hs token must be reissued");
908
909        // Control: a token carrying the CORRECT hs (and nothing else wrong) IS
910        // reused — proving the reissue above is driven by the hs mismatch, not
911        // another predicate.
912        let correct_hs =
913            hyprstream_rpc::auth::service_signer_suite_b64(&svc.verifying_key().to_bytes(), None);
914        write_persisted_token_with_hs(dir.path(), &ca, &svc, issuer, now, Some(&correct_hs));
915        let current = super::super::identity_store::load_service_jwt(dir.path(), "model")
916            .unwrap()
917            .unwrap();
918        let reused = issue_or_load_service_jwt(
919            dir.path(),
920            "model",
921            &ca,
922            &bp(svc.verifying_key()),
923            issuer,
924            now,
925            None,
926        )
927        .unwrap();
928        assert_eq!(reused, current, "a correct-hs current token must be reused");
929    }
930}