Skip to main content

hyprstream_rpc/auth/mac/
activation.rs

1//! Coverage-gated MAC activation control and verified-subject context cache.
2//!
3//! The reference monitor is always present.  The process defaults to
4//! [`MacActivationMode::IdentityAware`] (standard IAM: the verified subject
5//! context from `Claims × VerifiedKeyMaterial`).  The operator can narrow to
6//! [`MacActivationMode::FloorOnly`] as a killswitch via
7//! [`MacActivationControl::narrow_to_floor`], and can re-widen with
8//! [`MacActivationControl::widen_identity_aware`] once the genesis report
9//! evidence is complete.
10
11use std::collections::{BTreeSet, HashMap};
12use std::sync::atomic::{AtomicU8, Ordering};
13use std::sync::OnceLock;
14
15use parking_lot::RwLock;
16
17use super::{
18    Assurance, CompartmentSet, GenesisReport, Level, SecurityContext, SecurityLabel,
19    VerifiedKeyMaterial,
20};
21use crate::envelope::Subject;
22use crate::service::EnvelopeContext;
23
24const FLOOR_ONLY: u8 = 0;
25const IDENTITY_AWARE: u8 = 1;
26
27/// The two allowed production enforcement states.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum MacActivationMode {
30    /// Mandatory monitor with the anonymous-floor subject context.
31    FloorOnly,
32    /// Mandatory monitor with verified identity-aware subject contexts.
33    IdentityAware,
34}
35
36/// Why an operator-requested widening was refused.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct MacActivationError {
39    pub unlabeled: usize,
40    pub ill_formed: usize,
41    pub missing_gates: Vec<&'static str>,
42    pub blocked_transports: Vec<&'static str>,
43}
44
45impl std::fmt::Display for MacActivationError {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(
48            f,
49            "MAC identity-aware widening refused: readiness evidence incomplete \
50             (unlabeled={}, ill_formed={}, missing_gates={:?}, blocked_transports={:?})",
51            self.unlabeled, self.ill_formed, self.missing_gates, self.blocked_transports
52        )
53    }
54}
55
56impl std::error::Error for MacActivationError {}
57
58/// Operator-supplied evidence for the epic's G1-G7 decision gate.
59///
60/// These are attestations, not automatically inferred health signals. The
61/// operator control plane must assemble them from the signed activation
62/// evidence described in the runbook. G3 is proven by this control's
63/// reversible narrow operation itself.
64pub struct MacActivationEvidence<'a> {
65    pub genesis: &'a GenesisReport,
66    pub mediation_integrity_g2: bool,
67    pub denial_handling_g4: bool,
68    pub observability_g5: bool,
69    pub runbook_signoff_g6: bool,
70    pub revocation_reload_g7: bool,
71}
72
73impl MacActivationEvidence<'_> {
74    fn missing_gates(&self) -> Vec<&'static str> {
75        let mut missing = Vec::new();
76        if !self.genesis.is_complete() {
77            missing.push("G1");
78        }
79        if !self.mediation_integrity_g2 {
80            missing.push("G2");
81        }
82        if !self.denial_handling_g4 {
83            missing.push("G4");
84        }
85        if !self.observability_g5 {
86            missing.push("G5");
87        }
88        if !self.runbook_signoff_g6 {
89            missing.push("G6");
90        }
91        if !self.revocation_reload_g7 {
92            missing.push("G7");
93        }
94        missing
95    }
96}
97
98/// Process-wide widen/narrow control.  It never removes a PEP.
99#[derive(Debug)]
100pub struct MacActivationControl {
101    mode: AtomicU8,
102    unverified_attach_transports: RwLock<BTreeSet<&'static str>>,
103}
104
105impl Default for MacActivationControl {
106    fn default() -> Self {
107        Self {
108            // Default to IdentityAware: the runtime boots with the verified
109            // subject context from the envelope (standard IAM). FloorOnly
110            // remains available as a deliberate killswitch via
111            // `narrow_to_floor()`.
112            mode: AtomicU8::new(IDENTITY_AWARE),
113            unverified_attach_transports: RwLock::new(BTreeSet::new()),
114        }
115    }
116}
117
118impl MacActivationControl {
119    /// Current subject-context selection.
120    #[must_use]
121    pub fn mode(&self) -> MacActivationMode {
122        if self.mode.load(Ordering::Acquire) == IDENTITY_AWARE {
123            MacActivationMode::IdentityAware
124        } else {
125            MacActivationMode::FloorOnly
126        }
127    }
128
129    /// Explicit operator widening.  Coverage must be complete at the instant of
130    /// the request; merely constructing or logging a report never flips state.
131    pub fn widen_identity_aware(
132        &self,
133        evidence: &MacActivationEvidence<'_>,
134    ) -> Result<(), MacActivationError> {
135        let blocked_transports = self.blocked_transports();
136        let mut missing_gates = evidence.missing_gates();
137        if !blocked_transports.is_empty() && !missing_gates.contains(&"G2") {
138            missing_gates.push("G2");
139        }
140        if !missing_gates.is_empty() {
141            return Err(MacActivationError {
142                unlabeled: evidence.genesis.unlabeled.len(),
143                ill_formed: evidence.genesis.ill_formed.len(),
144                missing_gates,
145                blocked_transports,
146            });
147        }
148        // A widening starts a new cache generation. No verified subject
149        // context from an earlier floor-only/reload epoch can survive it.
150        flush_verified_subject_cache_generation();
151        self.mode.store(IDENTITY_AWARE, Ordering::Release);
152        Ok(())
153    }
154
155    /// Kill-switch: narrow subject context back to the anonymous floor while
156    /// leaving every monitor installed and authoritative.
157    pub fn narrow_to_floor(&self) {
158        self.mode.store(FLOOR_ONLY, Ordering::Release);
159        flush_verified_subject_cache_generation();
160    }
161
162    /// Select the context a PEP must evaluate in the current mode.
163    #[must_use]
164    pub fn select_context(&self, verified: Option<SecurityContext>) -> Option<SecurityContext> {
165        match self.mode() {
166            MacActivationMode::FloorOnly => Some(anonymous_floor()),
167            MacActivationMode::IdentityAware => verified,
168        }
169    }
170
171    /// Permanently block identity-aware widening in this process while a live
172    /// 9P transport still has no verified attach-credential carrier.
173    ///
174    /// Registration also narrows an already-widened process immediately, so a
175    /// late worker constructor cannot turn UDS/vsock attaches into a deny-all
176    /// availability outage.
177    pub fn block_unverified_attach_transport(&self, transport: &'static str) {
178        self.unverified_attach_transports.write().insert(transport);
179        self.narrow_to_floor();
180    }
181
182    /// Runtime transport blockers that make G2 structurally incomplete.
183    #[must_use]
184    pub fn blocked_transports(&self) -> Vec<&'static str> {
185        self.unverified_attach_transports
186            .read()
187            .iter()
188            .copied()
189            .collect()
190    }
191}
192
193/// The process-global activation control.  It starts floor-only.
194#[must_use]
195pub fn global_mac_activation_control() -> &'static MacActivationControl {
196    static CONTROL: OnceLock<MacActivationControl> = OnceLock::new();
197    CONTROL.get_or_init(MacActivationControl::default)
198}
199
200/// Register a live production 9P transport that still uses a deny-only
201/// authenticator. Once registered, this process cannot widen identity-aware
202/// MAC until that constructor is replaced with a verified credential carrier
203/// in a fresh process.
204pub fn block_identity_widening_for_unverified_attach_transport(transport: &'static str) {
205    global_mac_activation_control().block_unverified_attach_transport(transport);
206}
207
208/// Canonical anonymous-floor context used by every PEP during narrowing.
209#[must_use]
210pub fn anonymous_floor() -> SecurityContext {
211    SecurityContext::from_clearance(
212        SecurityLabel::new(Level::Public, Assurance::Unverified, CompartmentSet::EMPTY),
213        VerifiedKeyMaterial::Unverified,
214    )
215}
216
217#[derive(Clone)]
218struct VerifiedSubjectEntry {
219    context: SecurityContext,
220    tenant: Option<String>,
221    expires_at: i64,
222    /// Issuer-scoped credential ID `(iss, jti/cti)` this entry was derived
223    /// from. Typed so eviction targets the exact credential without
224    /// cross-issuer or JWT/CWT ambiguity.
225    credential_id: Option<crate::auth::CredentialId>,
226    /// Issuer-scoped session ID `(iss, sid)` this entry was derived from, if
227    /// the credential carried one. Revalidated against the canonical session
228    /// registry on every read, exactly like the credential ID.
229    session_key: Option<crate::auth::SessionKey>,
230    generation: u64,
231}
232
233#[derive(Default)]
234struct VerifiedSubjectCache {
235    generation: u64,
236    subjects: HashMap<String, VerifiedSubjectEntry>,
237}
238
239fn verified_subjects() -> &'static RwLock<VerifiedSubjectCache> {
240    static SUBJECTS: OnceLock<RwLock<VerifiedSubjectCache>> = OnceLock::new();
241    SUBJECTS.get_or_init(|| RwLock::new(VerifiedSubjectCache::default()))
242}
243
244/// Revoke every cached subject context derived from the given credential.
245///
246/// The shared credential-revocation store calls this hook on every
247/// revocation, so VFS/CAS/MoQ lookups cannot continue using authority
248/// cached before the blocklist update. The typed `CredentialId` ensures
249/// only entries derived from the exact `(iss, jti/cti)` pair are evicted
250/// — no cross-issuer or JWT/CWT ambiguity.
251pub fn revoke_verified_subject_credential(id: &crate::auth::CredentialId) -> usize {
252    let mut cache = verified_subjects().write();
253    let before = cache.subjects.len();
254    cache
255        .subjects
256        .retain(|_, entry| entry.credential_id.as_ref() != Some(id));
257    before.saturating_sub(cache.subjects.len())
258}
259
260/// Advance the verified-subject cache generation and remove all prior entries.
261///
262/// Policy/resolver reload and revocation control planes call this G7 hook.
263/// Widening and narrowing also rotate the generation automatically.
264pub fn flush_verified_subject_cache_generation() -> u64 {
265    let mut cache = verified_subjects().write();
266    cache.generation = cache.generation.saturating_add(1);
267    cache.subjects.clear();
268    cache.generation
269}
270
271/// Cache the context of a request whose envelope and Claims have already been
272/// verified.  This is the bridge for in-process VFS/CAS/MoQ APIs that carry a
273/// verified [`Subject`] but not the full [`EnvelopeContext`].
274///
275/// The cache is never an authority source: insertion requires the same
276/// `Claims × VerifiedKeyMaterial` derivation used by the RPC PEP, entries expire
277/// with the signed Claims, and lookup still passes through the activation
278/// control.
279pub fn remember_verified_subject(ctx: &EnvelopeContext) {
280    let Some(claims) = ctx.claims() else {
281        return;
282    };
283    let subject = ctx.subject();
284    remember_verified_claims(
285        &subject,
286        claims,
287        ctx.verified_key_material(),
288        ctx.verified_tenant(),
289    );
290}
291
292/// Cache an already-verified Claims binding for a lower-level PEP boundary
293/// that does not carry an [`EnvelopeContext`] (notably unified 9P attach).
294///
295/// The caller must invoke this only after signature, expiry, local-issuer,
296/// tenant, and sender-binding verification. The two-input derivation is
297/// repeated here so a Claims value alone can never create a subject context.
298pub fn remember_verified_claims(
299    subject: &Subject,
300    claims: &crate::auth::Claims,
301    key_material: VerifiedKeyMaterial,
302    verified_tenant: Option<&str>,
303) {
304    use super::SubjectContextClaims as _;
305
306    let Some(name) = subject.name() else {
307        return;
308    };
309    if claims.exp <= chrono::Utc::now().timestamp() {
310        return;
311    }
312    if claims.sub != name {
313        return;
314    }
315    let Some(context) = claims.security_context(key_material) else {
316        return;
317    };
318    // Derive the JWT credential ID from `(iss, jti)`. CWT credential paths
319    // use [`remember_verified_claims_with_credential`] with an explicit CWT
320    // CredentialId so `cti` bytes are never stringified.
321    let credential_id = claims
322        .jti
323        .as_ref()
324        .map(|jti| crate::auth::CredentialId::jwt(&claims.iss, jti));
325    // Exact-one session parsing (v16 §3.3): a credential with ambiguous or
326    // malformed session claims is never cached — without a cache entry every
327    // PEP read misses and denies (fail-closed).
328    let Ok(session_key) = claims.session_key() else {
329        return;
330    };
331    insert_verified_subject_entry(
332        name,
333        context,
334        verified_tenant,
335        claims.exp,
336        credential_id,
337        session_key,
338    );
339}
340
341/// Cache a verified-Claims binding with an explicit [`CredentialId`],
342/// for credential encodings whose identifier is not derivable from
343/// `Claims::jti` (notably CWT `cti` byte strings).
344///
345/// This is the **only** insertion path for CWT credentials. It repeats
346/// every invariant check that [`remember_verified_claims`] enforces:
347/// `sub` must match `subject.name()`, `exp` must be in the future,
348/// `security_context` must be derivable from `Claims × VerifiedKeyMaterial`,
349/// and the credential ID's issuer must match `claims.iss`.
350/// The cache entry is keyed by the caller-supplied `credential_id`, so
351/// eviction targets the exact `(iss, jti/cti)` pair.
352///
353/// `credential_id.issuer` MUST equal `claims.iss`. This prevents a caller
354/// from attaching a credential ID from a different issuer to a cache
355/// entry, which would break issuer-scoped eviction.
356pub fn remember_verified_claims_with_credential(
357    subject: &Subject,
358    claims: &crate::auth::Claims,
359    key_material: VerifiedKeyMaterial,
360    verified_tenant: Option<&str>,
361    credential_id: crate::auth::CredentialId,
362) {
363    use super::SubjectContextClaims as _;
364
365    let Some(name) = subject.name() else {
366        return;
367    };
368    if claims.exp <= chrono::Utc::now().timestamp() {
369        return;
370    }
371    if claims.sub != name {
372        return;
373    }
374    let Some(context) = claims.security_context(key_material) else {
375        return;
376    };
377    // The credential ID's issuer must match the claims' issuer, so
378    // issuer-scoped eviction cannot be subverted by attaching a
379    // foreign-issuer credential ID.
380    if !credential_id.is_valid() || credential_id.issuer != claims.iss {
381        return;
382    }
383    // Exact-one session parsing (v16 §3.3): a credential with ambiguous or
384    // malformed session claims is never cached — without a cache entry every
385    // PEP read misses and denies (fail-closed).
386    let Ok(session_key) = claims.session_key() else {
387        return;
388    };
389    insert_verified_subject_entry(
390        name,
391        context,
392        verified_tenant,
393        claims.exp,
394        Some(credential_id),
395        session_key,
396    );
397}
398
399fn insert_verified_subject_entry(
400    name: &str,
401    context: SecurityContext,
402    verified_tenant: Option<&str>,
403    expires_at: i64,
404    credential_id: Option<crate::auth::CredentialId>,
405    session_key: Option<crate::auth::SessionKey>,
406) {
407    let mut cache = verified_subjects().write();
408    let generation = cache.generation;
409    cache.subjects.insert(
410        name.to_owned(),
411        VerifiedSubjectEntry {
412            context,
413            tenant: verified_tenant.map(str::to_owned),
414            expires_at,
415            credential_id,
416            session_key,
417            generation,
418        },
419    );
420}
421
422/// Resolve a VFS/CAS/MoQ subject through the verified-Claims cache and current
423/// activation mode.  Tenant mismatch is a hard miss.
424///
425/// Revocation revalidation: a cache hit whose entry carries a credential ID
426/// is revalidated against the process-global credential-revocation store on
427/// EVERY read — in non-policy processes that is one authority RPC per hit,
428/// which is deliberate strict observation, mirroring the per-request check in
429/// `verify_claims`. A revoked credential, an absent store, or an unreachable
430/// authority (the store's own fail-closed `true`) all evict the entry and
431/// deny. Entries without a credential ID keep the cache-only behavior.
432///
433/// Session revalidation: a hit whose entry carries a session ID is likewise
434/// revalidated against the process-global session registry on every read — a
435/// revoked, expired, or unknown session, an absent registry, or an
436/// unreachable authority all evict the entry and deny (v16 §3.3: session
437/// revocation rejects every carrying credential).
438pub async fn subject_context(
439    subject: &Subject,
440    verified_tenant: Option<&str>,
441) -> Option<SecurityContext> {
442    subject_context_with(
443        crate::auth::global_credential_revocation_store().map(std::convert::AsRef::as_ref),
444        crate::auth::global_session_registry().map(std::convert::AsRef::as_ref),
445        subject,
446        verified_tenant,
447    )
448    .await
449}
450
451/// [`subject_context`] against explicit authority handles instead of the
452/// process-global ones. `None` behaves exactly like an unpublished global:
453/// credential-bearing and session-bearing hits fail closed.
454pub async fn subject_context_with(
455    store: Option<&dyn crate::auth::CredentialRevocationStore>,
456    session_registry: Option<&dyn crate::auth::SessionRegistry>,
457    subject: &Subject,
458    verified_tenant: Option<&str>,
459) -> Option<SecurityContext> {
460    let verified = match subject.name() {
461        Some(name) => {
462            // Sync screening pass (unchanged rules): generation, expiry,
463            // tenant. A miss here never reaches the store.
464            let entry = {
465                let now = chrono::Utc::now().timestamp();
466                let mut cache = verified_subjects().write();
467                match cache.subjects.get(name) {
468                    Some(entry) => {
469                        let entry = entry.clone();
470                        if entry.generation != cache.generation || entry.expires_at <= now {
471                            cache.subjects.remove(name);
472                            None
473                        } else if let Some(expected) = verified_tenant {
474                            if entry.tenant.as_deref() != Some(expected) {
475                                None
476                            } else {
477                                Some(entry)
478                            }
479                        } else {
480                            Some(entry)
481                        }
482                    }
483                    None => None,
484                }
485            };
486            match entry {
487                Some(entry) => {
488                    // Revalidate the credential AND the session when both are
489                    // present — a revocation of either rejects the entry.
490                    if let Some(ref credential_id) = entry.credential_id {
491                        let revoked = match store {
492                            Some(store) => store.is_revoked(credential_id).await,
493                            // No authority handle published — fail closed.
494                            None => true,
495                        };
496                        if revoked {
497                            revoke_verified_subject_credential(credential_id);
498                            return global_mac_activation_control().select_context(None);
499                        }
500                    }
501                    if let Some(ref session_key) = entry.session_key {
502                        let session_revoked = match session_registry {
503                            Some(registry) => registry.is_revoked(session_key).await,
504                            // No session authority handle published — fail closed.
505                            None => true,
506                        };
507                        if session_revoked {
508                            let mut cache = verified_subjects().write();
509                            cache.subjects.remove(name);
510                            return global_mac_activation_control().select_context(None);
511                        }
512                    }
513                    Some(entry.context)
514                }
515                None => None,
516            }
517        }
518        None => None,
519    };
520    global_mac_activation_control().select_context(verified)
521}
522
523/// Test lock for tests that touch the global verified-subjects cache.
524/// All tests across modules that insert/evict/flush cache entries MUST
525/// acquire this lock to prevent parallel test interference.
526#[cfg(test)]
527pub(crate) static CACHE_TEST_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532
533    fn report(complete: bool) -> GenesisReport {
534        GenesisReport {
535            labeled: vec!["/".to_owned()],
536            unlabeled: if complete {
537                Vec::new()
538            } else {
539                vec!["/gap".to_owned()]
540            },
541            ill_formed: Vec::new(),
542        }
543    }
544
545    #[test]
546    fn widening_requires_complete_coverage_and_narrowing_is_always_available() {
547        let _guard = CACHE_TEST_LOCK.lock();
548        let control = MacActivationControl::default();
549        assert_eq!(control.mode(), MacActivationMode::IdentityAware);
550        control.narrow_to_floor();
551        let incomplete = report(false);
552        let mut evidence = MacActivationEvidence {
553            genesis: &incomplete,
554            mediation_integrity_g2: true,
555            denial_handling_g4: true,
556            observability_g5: true,
557            runbook_signoff_g6: true,
558            revocation_reload_g7: true,
559        };
560        assert!(control.widen_identity_aware(&evidence).is_err());
561        assert_eq!(control.mode(), MacActivationMode::FloorOnly);
562        let complete = report(true);
563        evidence.genesis = &complete;
564        assert!(control.widen_identity_aware(&evidence).is_ok());
565        assert_eq!(control.mode(), MacActivationMode::IdentityAware);
566        control.narrow_to_floor();
567        assert_eq!(control.mode(), MacActivationMode::FloorOnly);
568    }
569
570    #[test]
571    fn unverified_attach_transport_structurally_blocks_g2_widening() {
572        let _guard = CACHE_TEST_LOCK.lock();
573        let control = MacActivationControl::default();
574        control.narrow_to_floor();
575        control.block_unverified_attach_transport("worker-uds-vsock");
576
577        let complete = report(true);
578        let evidence = MacActivationEvidence {
579            genesis: &complete,
580            mediation_integrity_g2: true,
581            denial_handling_g4: true,
582            observability_g5: true,
583            runbook_signoff_g6: true,
584            revocation_reload_g7: true,
585        };
586        let Err(error) = control.widen_identity_aware(&evidence) else {
587            panic!("unverified worker transport must block identity-aware widening");
588        };
589        assert_eq!(control.mode(), MacActivationMode::FloorOnly);
590        assert!(error.missing_gates.contains(&"G2"));
591        assert_eq!(error.blocked_transports, vec!["worker-uds-vsock"]);
592    }
593
594    #[test]
595    fn jti_revocation_and_generation_rotation_evict_cached_subjects() {
596        let _guard = CACHE_TEST_LOCK.lock();
597        flush_verified_subject_cache_generation();
598
599        let now = chrono::Utc::now().timestamp();
600        let mut claims =
601            crate::auth::Claims::new("did:web:alice".to_owned(), now, now + 300).with_clearance(
602                SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY),
603            );
604        claims.iss = "https://local.example".to_owned();
605        claims.jti = Some("revocable-jti".to_owned());
606        let subject = Subject::new("did:web:alice");
607        remember_verified_claims(
608            &subject,
609            &claims,
610            VerifiedKeyMaterial::Classical,
611            Some("tenant-a"),
612        );
613
614        assert_eq!(verified_subjects().read().subjects.len(), 1);
615        let other_id = crate::auth::CredentialId::jwt("https://local.example", "other-jti");
616        let revocable_id = crate::auth::CredentialId::jwt("https://local.example", "revocable-jti");
617        let cross_issuer_id =
618            crate::auth::CredentialId::jwt("https://other.example", "revocable-jti");
619        assert_eq!(revoke_verified_subject_credential(&other_id), 0);
620        assert_eq!(
621            revoke_verified_subject_credential(&cross_issuer_id),
622            0,
623            "same jti from a different issuer must NOT evict"
624        );
625        assert_eq!(revoke_verified_subject_credential(&revocable_id), 1);
626        assert!(verified_subjects().read().subjects.is_empty());
627
628        remember_verified_claims(
629            &subject,
630            &claims,
631            VerifiedKeyMaterial::Classical,
632            Some("tenant-a"),
633        );
634        let old_generation = verified_subjects().read().generation;
635        let new_generation = flush_verified_subject_cache_generation();
636        assert!(new_generation >= old_generation);
637        assert!(verified_subjects().read().subjects.is_empty());
638    }
639
640    /// Exact-one session parsing at the CACHE-INSERTION boundary (v16 §3.3): a
641    /// credential carrying BOTH `sid` and `workload_session_id` is ambiguous
642    /// and is NEVER cached — without a cache entry every PEP read misses and
643    /// denies (fail-closed), so an active OIDC sid can never mask a revoked or
644    /// unknown workload session through a stale cached context.
645    #[test]
646    fn ambiguous_session_claims_are_never_cached() {
647        let _guard = CACHE_TEST_LOCK.lock();
648        flush_verified_subject_cache_generation();
649        assert!(verified_subjects().read().subjects.is_empty());
650
651        let now = chrono::Utc::now().timestamp();
652        let clearance =
653            SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY);
654        let mut ambiguous = crate::auth::Claims::new("did:web:alice".to_owned(), now, now + 300)
655            .with_clearance(clearance)
656            .with_sid("oidc-1")
657            .with_workload_session_id("wl-1");
658        ambiguous.iss = "https://local.example".to_owned();
659        ambiguous.jti = Some("ambiguous-jti".to_owned());
660        remember_verified_claims(
661            &Subject::new("did:web:alice"),
662            &ambiguous,
663            VerifiedKeyMaterial::Classical,
664            Some("tenant-a"),
665        );
666        assert!(
667            verified_subjects().read().subjects.is_empty(),
668            "a credential with ambiguous session claims must never be cached"
669        );
670
671        // Control: a well-formed single-session credential IS cached.
672        let mut ok = crate::auth::Claims::new("did:web:alice".to_owned(), now, now + 300)
673            .with_clearance(clearance)
674            .with_sid("oidc-1");
675        ok.iss = "https://local.example".to_owned();
676        ok.jti = Some("ok-jti".to_owned());
677        remember_verified_claims(
678            &Subject::new("did:web:alice"),
679            &ok,
680            VerifiedKeyMaterial::Classical,
681            Some("tenant-a"),
682        );
683        assert_eq!(verified_subjects().read().subjects.len(), 1);
684        flush_verified_subject_cache_generation();
685    }
686}