Skip to main content

hyprstream_rpc/auth/
jti_blocklist.rs

1//! Issuer-scoped credential-revocation store.
2//!
3//! Revoked credential IDs `(iss, jti/cti)` are stored until their `exp` time
4//! passes, at which point natural JWT/CWT expiry rejects them anyway. The
5//! store is keyed by [`CredentialId`], not bare `jti`, so that two issuers
6//! producing the same `jti` value cannot cross-revoke each other's tokens.
7//!
8//! CWT `cti` byte strings are kept as bytes (via [`CredentialValue::Cwt`])
9//! and never stringified into the JWT `jti` text namespace.
10//!
11//! # One canonical store, owned by the policy service
12//!
13//! There is exactly one canonical revocation store per deployment, owned by
14//! the policy service process and backed by a durable local file
15//! ([`FileBackedCredentialRevocationStore`]). Every other service process
16//! publishes the process-global handle below with a policy-authority RPC
17//! client store (see `services::revocation` in the `hyprstream` crate) that
18//! checks and publishes revocations through the policy service over the RPC
19//! bus. Startup, checks, and publication are all fail-closed: no reachable
20//! authority means no JTI-bearing token is admitted and no revocation
21//! silently no-ops.
22//!
23//! Renamed from `JtiBlocklist` / `InMemoryJtiBlocklist` (bare `jti` key) to
24//! `CredentialRevocationStore` / `InMemoryCredentialRevocationStore`
25//! (issuer-scoped `(iss, jti/cti)` key).
26
27use std::collections::HashMap;
28use std::sync::{Arc, OnceLock};
29
30use super::credential::{CredentialId, CredentialValue};
31
32// ── Global store ──────────────────────────────────────────────────────────
33
34/// Process-global credential-revocation store. Set once at startup so every
35/// `RequestService` implementation shares exactly one store: the durable
36/// authority store in the policy process, or a policy-authority RPC client
37/// store everywhere else. Before it is set, verification fails closed — no
38/// token with a jti can be admitted until the store is published.
39static GLOBAL_STORE: OnceLock<Arc<dyn CredentialRevocationStore>> = OnceLock::new();
40
41/// Publish the process-global credential-revocation store. Called once at
42/// startup; a second call returns an error so the caller can detect a
43/// publication race (two services trying to set different stores). The
44/// caller MUST propagate this error — ignoring it allows two divergent
45/// stores, breaking the one-store invariant.
46pub fn set_global_credential_revocation_store(
47    store: Arc<dyn CredentialRevocationStore>,
48) -> Result<(), GlobalStoreAlreadySet> {
49    GLOBAL_STORE.set(store).map_err(|_| GlobalStoreAlreadySet)
50}
51
52/// Error returned when the global store was already published with a
53/// different instance.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct GlobalStoreAlreadySet;
56
57impl std::fmt::Display for GlobalStoreAlreadySet {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        write!(
60            f,
61            "global credential-revocation store already published (one-store invariant)"
62        )
63    }
64}
65
66impl std::error::Error for GlobalStoreAlreadySet {}
67
68/// Access the process-global credential-revocation store, if published.
69pub fn global_credential_revocation_store() -> Option<&'static Arc<dyn CredentialRevocationStore>> {
70    GLOBAL_STORE.get()
71}
72
73/// The revocation authority did not durably accept a revocation publication.
74///
75/// Publication failure must never look like success: callers (e.g. the RFC
76/// 7009 endpoint) surface this as an error response instead of proceeding as
77/// though the credential were revoked.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct RevocationPublishError {
80    message: String,
81}
82
83impl RevocationPublishError {
84    /// Construct from a human-readable cause.
85    pub fn new(message: impl Into<String>) -> Self {
86        Self {
87            message: message.into(),
88        }
89    }
90}
91
92impl std::fmt::Display for RevocationPublishError {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(f, "revocation publication failed: {}", self.message)
95    }
96}
97
98impl std::error::Error for RevocationPublishError {}
99
100/// Trait for a credential-revocation store keyed by issuer-scoped
101/// [`CredentialId`].
102///
103/// The [`Self::revoke_credential`] method encodes the mandatory
104/// publication-before-eviction ordering (v16 §3.3): the credential is
105/// published to the blocklist FIRST, so new verifications fail, and only
106/// THEN are derived handles evicted. Callers cannot reverse this order
107/// because publication and eviction are a single method call.
108///
109/// The methods are async because the canonical store is remote for every
110/// process except the policy service: checks and publications cross the RPC
111/// bus to the revocation authority.
112#[async_trait::async_trait]
113pub trait CredentialRevocationStore: Send + Sync {
114    /// Returns `true` if the given issuer-scoped credential has been revoked.
115    ///
116    /// An invalid credential ID (empty issuer or value) returns `true`
117    /// (fail-closed): per v16 §3.1, malformed identifiers deny.
118    async fn is_revoked(&self, id: &CredentialId) -> bool {
119        if !id.is_valid() {
120            return true;
121        }
122        self.is_revoked_checked(id).await
123    }
124
125    /// Revoke a credential. `expires_at` is the token's `exp` — the entry
126    /// can be garbage-collected after this time.
127    ///
128    /// Ordering: the credential is published (durable, for the authority
129    /// store) BEFORE derived handles are evicted. This ensures new
130    /// verifications fail the blocklist check while cached contexts derived
131    /// from the revoked token are being removed.
132    ///
133    /// Returns [`RevocationPublishError`] if the revocation authority did not
134    /// durably accept the publication; on error no in-memory state changes
135    /// and no handles are evicted.
136    async fn revoke_credential(
137        &self,
138        id: CredentialId,
139        expires_at: i64,
140    ) -> Result<(), RevocationPublishError>;
141
142    /// The checked revocation lookup — called by `is_revoked` after
143    /// validation. Implementations provide the actual store lookup.
144    /// Implementations fail closed: any lookup error returns `true`.
145    async fn is_revoked_checked(&self, id: &CredentialId) -> bool;
146}
147
148/// In-memory credential-revocation store with periodic cleanup.
149pub struct InMemoryCredentialRevocationStore {
150    #[cfg(not(target_arch = "wasm32"))]
151    revoked: parking_lot::RwLock<HashMap<CredentialId, i64>>,
152    #[cfg(target_arch = "wasm32")]
153    revoked: std::sync::RwLock<HashMap<CredentialId, i64>>,
154}
155
156impl Default for InMemoryCredentialRevocationStore {
157    fn default() -> Self {
158        Self::new()
159    }
160}
161
162impl InMemoryCredentialRevocationStore {
163    pub fn new() -> Self {
164        Self {
165            revoked: Default::default(),
166        }
167    }
168
169    fn cleanup(&self, now: i64) {
170        #[cfg(not(target_arch = "wasm32"))]
171        {
172            let mut map = self.revoked.write();
173            map.retain(|_, exp| *exp > now);
174        }
175        #[cfg(target_arch = "wasm32")]
176        {
177            let mut map = self
178                .revoked
179                .write()
180                .expect("revocation store lock poisoned");
181            map.retain(|_, exp| *exp > now);
182        }
183    }
184
185    /// Insert an already-published entry (durable-store load at startup):
186    /// memory insert only — no eviction, no re-publication.
187    #[cfg(not(target_arch = "wasm32"))]
188    fn insert_loaded(&self, id: CredentialId, expires_at: i64) {
189        self.revoked.write().insert(id, expires_at);
190    }
191
192    /// The stored expiry for an exact credential ID, if present. Sync
193    /// read-only probe for the durable store's writer-lock dedup.
194    #[cfg(not(target_arch = "wasm32"))]
195    fn existing_expiry(&self, id: &CredentialId) -> Option<i64> {
196        self.revoked.read().get(id).copied()
197    }
198}
199
200#[async_trait::async_trait]
201impl CredentialRevocationStore for InMemoryCredentialRevocationStore {
202    async fn is_revoked_checked(&self, id: &CredentialId) -> bool {
203        #[cfg(not(target_arch = "wasm32"))]
204        {
205            self.revoked.read().contains_key(id)
206        }
207        #[cfg(target_arch = "wasm32")]
208        {
209            self.revoked
210                .read()
211                .expect("revocation store lock poisoned")
212                .contains_key(id)
213        }
214    }
215
216    async fn revoke_credential(
217        &self,
218        id: CredentialId,
219        expires_at: i64,
220    ) -> Result<(), RevocationPublishError> {
221        let now = chrono::Utc::now().timestamp();
222
223        // Phase 1 — PUBLISH: insert into the blocklist so that any new
224        // verification encountering this credential ID rejects immediately.
225        // In-memory publication cannot fail, so this store always returns Ok.
226        #[cfg(not(target_arch = "wasm32"))]
227        {
228            let mut map = self.revoked.write();
229            map.insert(id.clone(), expires_at);
230            let cleanup = map.len() > 10_000;
231            drop(map);
232            if cleanup {
233                self.cleanup(now);
234            }
235        }
236        #[cfg(target_arch = "wasm32")]
237        {
238            let mut map = self
239                .revoked
240                .write()
241                .expect("revocation store lock poisoned");
242            map.insert(id.clone(), expires_at);
243            if map.len() > 10_000 {
244                drop(map);
245                self.cleanup(now);
246            }
247        }
248
249        // Phase 2 — EVICT: flush cached subject contexts derived from the
250        // revoked credential. This runs strictly AFTER the blocklist insert,
251        // so the window in which a new verification could pass while a stale
252        // handle survives is closed from both sides. The typed CredentialId
253        // ensures only entries derived from the exact `(iss, jti/cti)` pair
254        // are evicted — no cross-issuer or JWT/CWT ambiguity.
255        #[cfg(not(target_arch = "wasm32"))]
256        {
257            crate::auth::mac::revoke_verified_subject_credential(&id);
258        }
259        Ok(())
260    }
261}
262
263// ── Durable (file-backed) store — the policy process's canonical store ────
264
265/// One JSONL record: `{"iss":…,"jwt":…,"exp":…}` for a JWT `jti`, or
266/// `{"iss":…,"cwt":"<base64>","exp":…}` for a CWT `cti`. The `jwt`/`cwt`
267/// split preserves the disjoint typed namespaces on disk.
268#[cfg(not(target_arch = "wasm32"))]
269#[derive(serde::Serialize, serde::Deserialize)]
270struct RevocationRecord {
271    iss: String,
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    jwt: Option<String>,
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    cwt: Option<String>,
276    exp: i64,
277}
278
279#[cfg(not(target_arch = "wasm32"))]
280impl RevocationRecord {
281    fn new(id: &CredentialId, expires_at: i64) -> Self {
282        match &id.value {
283            CredentialValue::Jwt(jti) => Self {
284                iss: id.issuer.clone(),
285                jwt: Some(jti.clone()),
286                cwt: None,
287                exp: expires_at,
288            },
289            CredentialValue::Cwt(cti) => Self {
290                iss: id.issuer.clone(),
291                jwt: None,
292                cwt: Some(base64::Engine::encode(
293                    &base64::engine::general_purpose::STANDARD,
294                    cti,
295                )),
296                exp: expires_at,
297            },
298        }
299    }
300
301    /// Decode back to a validated [`CredentialId`]. `None` = corrupt record
302    /// (both/neither namespace present, bad base64, or empty issuer/value).
303    fn credential_id(&self) -> Option<CredentialId> {
304        let id = match (&self.jwt, &self.cwt) {
305            (Some(jti), None) => CredentialId::jwt(self.iss.clone(), jti.clone()),
306            (None, Some(cti)) => {
307                let bytes =
308                    base64::Engine::decode(&base64::engine::general_purpose::STANDARD, cti).ok()?;
309                CredentialId::cwt(self.iss.clone(), bytes)
310            }
311            _ => return None,
312        };
313        id.is_valid().then_some(id)
314    }
315}
316
317/// Durable credential-revocation store: an in-memory index in front of a
318/// JSONL append file. This is the canonical store form owned by the policy
319/// process — a revocation becomes visible to checks only after it has been
320/// appended AND fsync'd, so a crash never resurrects a revoked credential.
321#[cfg(not(target_arch = "wasm32"))]
322pub struct FileBackedCredentialRevocationStore {
323    /// Live `(iss, jti/cti) → exp` index, loaded from the file at open.
324    inner: InMemoryCredentialRevocationStore,
325    /// Append handle for the JSONL log; the mutex serializes writers.
326    file: parking_lot::Mutex<std::fs::File>,
327}
328
329#[cfg(not(target_arch = "wasm32"))]
330impl FileBackedCredentialRevocationStore {
331    /// Open (creating if absent) the durable store at `path` and load every
332    /// non-expired entry into memory. Expired entries are dropped on load —
333    /// natural token expiry rejects them anyway.
334    ///
335    /// Uses blocking file IO: called once at startup, before the process
336    /// serves traffic.
337    ///
338    /// Corruption policy: a malformed COMPLETE line (newline-terminated) is a
339    /// hard error — genuine corruption fails closed. A malformed or
340    /// newline-less FINAL fragment is a torn tail left by a crash mid-append
341    /// (the writer appends `record + '\n'`, so a newline-terminated line is
342    /// always complete): the file is truncated to just after the last
343    /// complete newline, the recovery is logged loudly, and a fragment that
344    /// still parses as a valid record is re-appended through the normal
345    /// write path so the revocation is not lost.
346    ///
347    /// A newly created file fsyncs its containing directory so the create
348    /// itself is durable; creating a fresh empty store where one should
349    /// pre-exist is logged as a loud warning (all prior revocations lost).
350    pub fn open(path: &std::path::Path) -> std::io::Result<Self> {
351        use std::io::Write as _;
352
353        let pre_existed = path.exists();
354        let file = std::fs::OpenOptions::new()
355            .read(true)
356            .append(true)
357            .create(true)
358            .open(path)?;
359        if !pre_existed {
360            // The create must survive a crash too: fsync the directory.
361            if let Some(parent) = path.parent() {
362                std::fs::File::open(parent)?.sync_all()?;
363            }
364        }
365        let now = chrono::Utc::now().timestamp();
366        let store = Self {
367            inner: InMemoryCredentialRevocationStore::new(),
368            file: parking_lot::Mutex::new(file.try_clone()?),
369        };
370
371        let content = std::fs::read(path)?;
372        // The complete portion ends just after the last newline; anything
373        // beyond it is a torn fragment from a crash mid-append.
374        let complete_len = content
375            .iter()
376            .rposition(|&b| b == b'\n')
377            .map_or(0, |i| i + 1);
378        let mut loaded = 0usize;
379        for line in content[..complete_len].split(|&b| b == b'\n') {
380            if line.iter().all(u8::is_ascii_whitespace) {
381                continue;
382            }
383            let record: RevocationRecord = serde_json::from_slice(line).map_err(|e| {
384                std::io::Error::new(
385                    std::io::ErrorKind::InvalidData,
386                    format!("corrupt revocation record: {e}"),
387                )
388            })?;
389            let id = record.credential_id().ok_or_else(|| {
390                std::io::Error::new(
391                    std::io::ErrorKind::InvalidData,
392                    "corrupt revocation record: invalid credential id",
393                )
394            })?;
395            if record.exp > now {
396                store.inner.insert_loaded(id, record.exp);
397                loaded += 1;
398            }
399        }
400
401        let tail = &content[complete_len..];
402        if !tail.is_empty() {
403            // Salvage before truncating: a fragment that still parses as a
404            // valid record carries a revocation that must not be lost.
405            let salvage = serde_json::from_slice::<RevocationRecord>(tail)
406                .ok()
407                .and_then(|record| record.credential_id().map(|id| (record, id)))
408                .filter(|(record, _)| record.exp > now);
409            let salvaged = salvage.is_some();
410            {
411                let mut file = store.file.lock();
412                file.set_len(complete_len as u64)?;
413                if let Some((record, id)) = salvage {
414                    let mut line = serde_json::to_string(&record).map_err(|e| {
415                        std::io::Error::new(
416                            std::io::ErrorKind::InvalidData,
417                            format!("torn-tail salvage serialization failed: {e}"),
418                        )
419                    })?;
420                    line.push('\n');
421                    file.write_all(line.as_bytes())?;
422                    store.inner.insert_loaded(id, record.exp);
423                    loaded += 1;
424                }
425                file.sync_all()?;
426            }
427            tracing::warn!(
428                path = %path.display(),
429                salvaged,
430                "torn revocation-log tail recovered: truncated to the last complete record"
431            );
432        }
433
434        if pre_existed {
435            tracing::info!(path = %path.display(), loaded, "credential-revocation store loaded");
436        } else {
437            tracing::warn!(
438                path = %path.display(),
439                "credential-revocation store did not exist — created a fresh EMPTY store; \
440                 on a non-fresh deployment every prior revocation is lost"
441            );
442        }
443        Ok(store)
444    }
445}
446
447#[cfg(not(target_arch = "wasm32"))]
448#[async_trait::async_trait]
449impl CredentialRevocationStore for FileBackedCredentialRevocationStore {
450    async fn is_revoked_checked(&self, id: &CredentialId) -> bool {
451        self.inner.is_revoked_checked(id).await
452    }
453
454    async fn revoke_credential(
455        &self,
456        id: CredentialId,
457        expires_at: i64,
458    ) -> Result<(), RevocationPublishError> {
459        use std::io::Write as _;
460
461        // Phase 1 — PUBLISH (durable): append + fsync FIRST, under the
462        // writer lock. On IO failure the in-memory index and the handle
463        // cache stay untouched — a revocation that is not durable must not
464        // pretend to exist.
465        //
466        // Dedup under the same lock: when an entry for this exact credential
467        // with an equal-or-longer retention is already durable, the
468        // revocation is already published (and its handles were evicted by
469        // the first publication), so a repeated revocation appends nothing —
470        // a replayed revocation request cannot grow the log or force an
471        // fsync per request.
472        let mut line =
473            serde_json::to_string(&RevocationRecord::new(&id, expires_at)).map_err(|e| {
474                RevocationPublishError::new(format!("record serialization failed: {e}"))
475            })?;
476        line.push('\n');
477        {
478            let mut file = self.file.lock();
479            if self
480                .inner
481                .existing_expiry(&id)
482                .is_some_and(|existing| existing >= expires_at)
483            {
484                return Ok(());
485            }
486            file.write_all(line.as_bytes())
487                .and_then(|()| file.sync_all())
488                .map_err(|e| RevocationPublishError::new(format!("durable append failed: {e}")))?;
489            // Publish to memory under the same lock so the dedup check and
490            // the visible insert are atomic against concurrent writers.
491            self.inner.insert_loaded(id.clone(), expires_at);
492        }
493
494        // Phase 2 — EVICT handles, strictly after publication (same
495        // publication-before-eviction ordering as the in-memory store).
496        crate::auth::mac::revoke_verified_subject_credential(&id);
497        Ok(())
498    }
499}
500
501// ── Removed: InMemoryJtiBlocklist alias ──────────────────────────────────
502//
503// The old names (`JtiBlocklist`, `InMemoryJtiBlocklist`) are deleted
504// entirely — no deprecated alias. All callers have been migrated to
505// `CredentialRevocationStore` / `InMemoryCredentialRevocationStore`.
506
507#[cfg(test)]
508#[allow(clippy::unwrap_used, clippy::expect_used)]
509mod tests {
510    use super::*;
511    use crate::auth::credential::{CredentialId, CredentialValue, SessionKey};
512
513    // ── Issuer scoping: same jti, two issuers, no cross-eviction ──────────
514
515    /// Revoking `(issuerA, "tok-1")` must not affect `(issuerB, "tok-1")`.
516    /// The whole point of issuer scoping: two issuers can independently
517    /// produce the same jti without cross-revoking each other's tokens.
518    #[tokio::test]
519    async fn issuer_scoping_prevents_cross_revoke() {
520        let store = InMemoryCredentialRevocationStore::new();
521        let id_a = CredentialId::jwt("https://a.example", "tok-1");
522        let id_b = CredentialId::jwt("https://b.example", "tok-1");
523
524        store
525            .revoke_credential(id_a.clone(), 9_999_999_999)
526            .await
527            .unwrap();
528
529        assert!(store.is_revoked(&id_a).await, "issuer A's token is revoked");
530        assert!(
531            !store.is_revoked(&id_b).await,
532            "issuer B's same-jti token is NOT revoked"
533        );
534    }
535
536    /// Revoking by CWT cti bytes does not collide with the same bytes as a
537    /// JWT jti string. The two are disjoint namespaces by type.
538    #[tokio::test]
539    async fn cwt_cti_does_not_collide_with_jwt_jti() {
540        let store = InMemoryCredentialRevocationStore::new();
541        let bytes = b"same-identifier-bytes".to_vec();
542
543        // Revoke the CWT credential with those bytes as cti.
544        let cwt_id = CredentialId {
545            issuer: "https://issuer.example".to_owned(),
546            value: CredentialValue::Cwt(bytes.clone()),
547        };
548        store
549            .revoke_credential(cwt_id.clone(), 9_999_999_999)
550            .await
551            .unwrap();
552
553        // A JWT credential with the same bytes-as-UTF-8 as jti is NOT revoked.
554        let jwt_id = CredentialId {
555            issuer: "https://issuer.example".to_owned(),
556            value: CredentialValue::Jwt(String::from_utf8(bytes).unwrap()),
557        };
558        assert!(
559            store.is_revoked(&cwt_id).await,
560            "CWT cti credential is revoked"
561        );
562        assert!(
563            !store.is_revoked(&jwt_id).await,
564            "JWT jti credential with the same text is NOT revoked"
565        );
566    }
567
568    /// Empty issuer and empty jti values are rejected as malformed (v16 §3.1).
569    /// `is_revoked` returns `true` (fail-closed) for invalid IDs — they can
570    /// never pass a revocation check.
571    #[tokio::test]
572    async fn empty_issuer_and_jti_are_rejected() {
573        let store = InMemoryCredentialRevocationStore::new();
574        let empty_iss = CredentialId::jwt("", "tok-1");
575        let empty_jti = CredentialId::jwt("https://a.example", "");
576        let empty_cti = CredentialId {
577            issuer: "https://a.example".to_owned(),
578            value: CredentialValue::Cwt(vec![]),
579        };
580
581        assert!(!empty_iss.is_valid(), "empty issuer is invalid");
582        assert!(!empty_jti.is_valid(), "empty jti is invalid");
583        assert!(!empty_cti.is_valid(), "empty cti is invalid");
584
585        // Fail-closed: invalid IDs report as revoked even though nothing was
586        // explicitly revoked.
587        assert!(
588            store.is_revoked(&empty_iss).await,
589            "empty issuer → fail-closed"
590        );
591        assert!(
592            store.is_revoked(&empty_jti).await,
593            "empty jti → fail-closed"
594        );
595        assert!(
596            store.is_revoked(&empty_cti).await,
597            "empty cti → fail-closed"
598        );
599    }
600
601    /// TTL cleanup evicts expired entries but keeps live ones.
602    #[tokio::test]
603    async fn cleanup_evicts_expired_entries() {
604        let store = InMemoryCredentialRevocationStore::new();
605        let live = CredentialId::jwt("https://a.example", "live");
606        let expired = CredentialId::jwt("https://a.example", "expired");
607
608        store
609            .revoke_credential(live.clone(), 9_999_999_999)
610            .await
611            .unwrap();
612        store.revoke_credential(expired.clone(), 1).await.unwrap(); // expired at time 1
613
614        // Both entries are present before cleanup.
615        assert!(store.is_revoked(&live).await);
616        assert!(store.is_revoked(&expired).await);
617
618        // Clean at a point past `expired`'s exp but before `live`'s.
619        store.cleanup(1_000_000);
620
621        assert!(store.is_revoked(&live).await, "live entry kept");
622        assert!(!store.is_revoked(&expired).await, "expired entry evicted");
623    }
624
625    // ── Revocation-before-eviction ordering ───────────────────────────────
626
627    /// `revoke_credential` publishes to the blocklist and evicts derived
628    /// handles in one call. We verify both effects: the credential is
629    /// published (blocklist reports revoked) AND the verified-subject cache
630    /// entry derived from that credential is evicted. Publication and
631    /// eviction are a single method call, so a caller cannot observe an
632    /// intermediate state where eviction happened but publication didn't.
633    // await_holding_lock: CACHE_TEST_LOCK serializes cache-mutating tests; the
634    // in-memory store futures complete without ever suspending.
635    #[cfg(not(target_arch = "wasm32"))]
636    #[tokio::test]
637    #[allow(clippy::await_holding_lock)]
638    async fn revoke_credential_publishes_then_evicts_subject() {
639        use crate::auth::mac::{
640            flush_verified_subject_cache_generation, remember_verified_claims,
641            revoke_verified_subject_credential, VerifiedKeyMaterial,
642        };
643
644        // Start from a clean cache.
645        let _cache_guard = crate::auth::mac::activation::CACHE_TEST_LOCK.lock();
646        flush_verified_subject_cache_generation();
647
648        let now = chrono::Utc::now().timestamp();
649        let issuer = "https://ordering.example";
650        let jti = "ordering-test";
651
652        // Remember a verified subject for this credential.
653        let mut claims = crate::auth::Claims::new("alice".to_owned(), now, now + 300)
654            .with_issuer(issuer.to_owned())
655            .with_clearance(crate::auth::mac::SecurityLabel::new(
656                crate::auth::mac::Level::Secret,
657                crate::auth::mac::Assurance::Classical,
658                crate::auth::mac::CompartmentSet::EMPTY,
659            ));
660        claims.jti = Some(jti.to_owned());
661        let subject = crate::envelope::Subject::new("alice");
662        remember_verified_claims(&subject, &claims, VerifiedKeyMaterial::Classical, None);
663
664        // Revoke the credential: publish then evict.
665        let store = InMemoryCredentialRevocationStore::new();
666        let id = CredentialId::jwt(issuer, jti);
667        store
668            .revoke_credential(id.clone(), now + 300)
669            .await
670            .unwrap();
671
672        // Publication: the blocklist reports revoked.
673        assert!(store.is_revoked(&id).await, "credential must be published");
674
675        // Eviction: the verified-subject cache entry derived from this
676        // credential is gone. We check the eviction function directly
677        // (subject_context goes through the activation control which may
678        // return the anonymous floor regardless of cache state).
679        // A second call to evict the same ID returns 0 (already evicted).
680        let evicted = revoke_verified_subject_credential(&id);
681        assert_eq!(evicted, 0, "entry was already evicted by revoke_credential");
682
683        // Cross-issuer: a subject from a DIFFERENT issuer with the same jti
684        // must survive — typed eviction does not cross-evict.
685        flush_verified_subject_cache_generation();
686        let mut claims_b = crate::auth::Claims::new("bob".to_owned(), now, now + 300)
687            .with_issuer("https://other.example".to_owned())
688            .with_clearance(crate::auth::mac::SecurityLabel::new(
689                crate::auth::mac::Level::Secret,
690                crate::auth::mac::Assurance::Classical,
691                crate::auth::mac::CompartmentSet::EMPTY,
692            ));
693        claims_b.jti = Some(jti.to_owned());
694        let subject_b = crate::envelope::Subject::new("bob");
695        remember_verified_claims(&subject_b, &claims_b, VerifiedKeyMaterial::Classical, None);
696
697        // Directly evict issuer-A's ID — must NOT evict issuer-B's subject.
698        let cross_evicted = revoke_verified_subject_credential(&id);
699        assert_eq!(
700            cross_evicted, 0,
701            "cross-issuer same-jti subject must NOT be evicted by issuer-A's credential ID"
702        );
703    }
704
705    /// The `CredentialRevocationStore` trait provides no separate eviction
706    /// method — the only way to trigger eviction is through
707    /// `revoke_credential`, which publishes first.
708    #[test]
709    fn trait_surface_has_no_bare_eviction() {
710        // The trait has is_revoked (with default validation), is_revoked_checked,
711        // and revoke_credential. There is no separate "evict" method.
712        fn assert_trait_shape<S: CredentialRevocationStore>() {}
713        assert_trait_shape::<InMemoryCredentialRevocationStore>();
714    }
715
716    // ── CWT typed eviction: insertion via typed boundary, revoke, evict ───
717
718    /// A CWT credential (cti bytes) inserted via the checked boundary is
719    /// evicted when that exact `(iss, cti)` credential is revoked. JWT
720    /// credentials with the same text value survive — disjoint namespaces.
721    // await_holding_lock: see revoke_credential_publishes_then_evicts_subject.
722    #[cfg(not(target_arch = "wasm32"))]
723    #[tokio::test]
724    #[allow(clippy::await_holding_lock)]
725    async fn cwt_credential_is_evicted_by_typed_revoke() {
726        use crate::auth::mac::{
727            flush_verified_subject_cache_generation, remember_verified_claims_with_credential,
728            revoke_verified_subject_credential, VerifiedKeyMaterial,
729        };
730
731        let _cache_guard = crate::auth::mac::activation::CACHE_TEST_LOCK.lock();
732        flush_verified_subject_cache_generation();
733
734        let issuer = "https://cwt.example";
735        let now = chrono::Utc::now().timestamp();
736        let shared_bytes = b"same-id".to_vec();
737
738        let cwt_id = CredentialId {
739            issuer: issuer.to_owned(),
740            value: CredentialValue::Cwt(shared_bytes.clone()),
741        };
742        let jwt_id = CredentialId {
743            issuer: issuer.to_owned(),
744            value: CredentialValue::Jwt(String::from_utf8(shared_bytes).unwrap()),
745        };
746
747        // Build verified Claims for the CWT-backed subject.
748        let cwt_claims = crate::auth::Claims::new("cwt-subject".to_owned(), now, now + 300)
749            .with_issuer(issuer.to_owned())
750            .with_clearance(crate::auth::mac::SecurityLabel::new(
751                crate::auth::mac::Level::Secret,
752                crate::auth::mac::Assurance::Classical,
753                crate::auth::mac::CompartmentSet::EMPTY,
754            ));
755        let cwt_subject = crate::envelope::Subject::new("cwt-subject");
756        remember_verified_claims_with_credential(
757            &cwt_subject,
758            &cwt_claims,
759            VerifiedKeyMaterial::Classical,
760            None,
761            cwt_id.clone(),
762        );
763
764        // Build verified Claims for the JWT-backed subject.
765        let jwt_claims = crate::auth::Claims::new("jwt-subject".to_owned(), now, now + 300)
766            .with_issuer(issuer.to_owned())
767            .with_clearance(crate::auth::mac::SecurityLabel::new(
768                crate::auth::mac::Level::Secret,
769                crate::auth::mac::Assurance::Classical,
770                crate::auth::mac::CompartmentSet::EMPTY,
771            ));
772        let jwt_subject = crate::envelope::Subject::new("jwt-subject");
773        remember_verified_claims_with_credential(
774            &jwt_subject,
775            &jwt_claims,
776            VerifiedKeyMaterial::Classical,
777            None,
778            jwt_id.clone(),
779        );
780
781        // Revoke via the store's canonical API (publish then evict).
782        let store = InMemoryCredentialRevocationStore::new();
783        store
784            .revoke_credential(cwt_id.clone(), now + 300)
785            .await
786            .unwrap();
787
788        // Publication: the store reports revoked.
789        assert!(
790            store.is_revoked(&cwt_id).await,
791            "CWT credential must be published"
792        );
793
794        // Eviction probe: the CWT entry is gone (already evicted by
795        // revoke_credential's internal hook). Returns 0 because the
796        // entry was already removed during the store's eviction phase.
797        let evicted = revoke_verified_subject_credential(&cwt_id);
798        assert_eq!(
799            evicted, 0,
800            "CWT entry already evicted by store.revoke_credential"
801        );
802
803        // The JWT entry survives — different namespace.
804        let jwt_evicted = revoke_verified_subject_credential(&jwt_id);
805        assert_eq!(
806            jwt_evicted, 1,
807            "JWT credential entry must still exist (different namespace from CWT)"
808        );
809
810        // Re-probing CWT still returns 0 (already gone).
811        let re_evicted = revoke_verified_subject_credential(&cwt_id);
812        assert_eq!(re_evicted, 0, "CWT entry already evicted");
813    }
814
815    // ── Session revocation evicts all carrying credentials ───────────────
816
817    /// Session revocation evicts all carrying handles. After `revoke_session`:
818    /// the session status is Revoked AND the verified-subject cache generation
819    /// is flushed, removing every cached handle.
820    #[cfg(not(target_arch = "wasm32"))]
821    #[tokio::test]
822    #[allow(clippy::await_holding_lock)]
823    async fn session_revocation_evicts_cached_handles() {
824        use crate::auth::credential::{
825            ActiveOrRevoked, InMemorySessionRegistry, SessionKind, SessionRegistry, SessionState,
826        };
827        use crate::auth::mac::{
828            flush_verified_subject_cache_generation, remember_verified_claims,
829            revoke_verified_subject_credential, VerifiedKeyMaterial,
830        };
831
832        // Start clean.
833        let _cache_guard = crate::auth::mac::activation::CACHE_TEST_LOCK.lock();
834        flush_verified_subject_cache_generation();
835
836        let now = chrono::Utc::now().timestamp();
837        let issuer = "https://session.example";
838        let jti = "ses-cred-1";
839
840        // Remember a verified subject derived from a credential that carries
841        // the session being revoked.
842        let mut claims = crate::auth::Claims::new("alice".to_owned(), now, now + 300)
843            .with_issuer(issuer.to_owned())
844            .with_clearance(crate::auth::mac::SecurityLabel::new(
845                crate::auth::mac::Level::Secret,
846                crate::auth::mac::Assurance::Classical,
847                crate::auth::mac::CompartmentSet::EMPTY,
848            ));
849        claims.jti = Some(jti.to_owned());
850        let subject = crate::envelope::Subject::new("alice");
851        remember_verified_claims(&subject, &claims, VerifiedKeyMaterial::Classical, None);
852
853        // Probe: the subject IS cached (evicting its credential returns 1).
854        let cred_id = CredentialId::jwt(issuer, jti);
855        let evicted_before = revoke_verified_subject_credential(&cred_id);
856        assert_eq!(
857            evicted_before, 1,
858            "subject must be cached before session revocation"
859        );
860
861        // Re-insert (the probe evicted it).
862        remember_verified_claims(&subject, &claims, VerifiedKeyMaterial::Classical, None);
863
864        // Register a session and revoke it.
865        let reg = InMemorySessionRegistry::new();
866        let key = SessionKey::oidc(issuer, "ses-1");
867        reg.register_session(
868            key.clone(),
869            SessionState {
870                subject: "alice".to_owned(),
871                tenant: "default".to_owned(),
872                kind: SessionKind::Interactive,
873                created_at: now,
874                expires_at: now + 300,
875                status: ActiveOrRevoked::Active,
876                clearance_epoch: 0,
877            },
878        )
879        .await
880        .unwrap();
881
882        // Publication: session is active before revocation.
883        assert!(
884            !reg.is_revoked(&key).await,
885            "session must be active before revoke"
886        );
887
888        // Revoke the session — this publishes (marks revoked) then evicts
889        // (flushes the generation, removing all cached handles).
890        reg.revoke_session(&key).await.unwrap();
891
892        // Publication: session is now revoked.
893        assert!(reg.is_revoked(&key).await, "session must be revoked");
894
895        // Eviction: the verified-subject cache entry is gone (the generation
896        // flush removed it). Trying to evict the credential returns 0 because
897        // it was already removed by the session revocation's generation flush.
898        let evicted_after = revoke_verified_subject_credential(&cred_id);
899        assert_eq!(
900            evicted_after, 0,
901            "subject must be evicted by session revocation's generation flush"
902        );
903    }
904
905    /// A session registry marks a session revoked and subsequent
906    /// `is_revoked` checks return true.
907    #[tokio::test]
908    async fn session_revocation_marks_session_revoked() {
909        use crate::auth::credential::{
910            ActiveOrRevoked, InMemorySessionRegistry, SessionRegistry, SessionState,
911        };
912
913        let reg = InMemorySessionRegistry::new();
914        let key = SessionKey::oidc("https://a.example", "ses-1");
915        let state = SessionState {
916            subject: "alice".to_owned(),
917            tenant: "default".to_owned(),
918            kind: crate::auth::credential::SessionKind::Interactive,
919            created_at: 0,
920            expires_at: 9_999_999_999,
921            status: ActiveOrRevoked::Active,
922            clearance_epoch: 0,
923        };
924        reg.register_session(key.clone(), state).await.unwrap();
925        assert!(!reg.is_revoked(&key).await, "session is active");
926
927        reg.revoke_session(&key).await.unwrap();
928        assert!(reg.is_revoked(&key).await, "session is now revoked");
929        assert_eq!(
930            reg.session_state(&key).await.unwrap().status,
931            ActiveOrRevoked::Revoked
932        );
933    }
934
935    /// An expired session reports as revoked even if its status bit is Active.
936    #[tokio::test]
937    async fn expired_session_is_revoked() {
938        use crate::auth::credential::{
939            ActiveOrRevoked, InMemorySessionRegistry, SessionKind, SessionRegistry, SessionState,
940        };
941
942        let reg = InMemorySessionRegistry::new();
943        let key = SessionKey::oidc("https://a.example", "ses-expired");
944        let state = SessionState {
945            subject: "alice".to_owned(),
946            tenant: "default".to_owned(),
947            kind: SessionKind::Interactive,
948            created_at: 0,
949            expires_at: 1, // expired at time 1
950            status: ActiveOrRevoked::Active,
951            clearance_epoch: 0,
952        };
953        reg.register_session(key.clone(), state).await.unwrap();
954        assert!(
955            reg.is_revoked(&key).await,
956            "expired session must report as revoked"
957        );
958    }
959
960    /// A revoked session key cannot be re-registered (no reactivation).
961    #[tokio::test]
962    async fn revoked_session_cannot_be_reactivated() {
963        use crate::auth::credential::{
964            ActiveOrRevoked, InMemorySessionRegistry, SessionKind, SessionRegistry, SessionState,
965        };
966
967        let reg = InMemorySessionRegistry::new();
968        let key = SessionKey::oidc("https://a.example", "ses-no-react");
969        let state = SessionState {
970            subject: "alice".to_owned(),
971            tenant: "default".to_owned(),
972            kind: SessionKind::Interactive,
973            created_at: 0,
974            expires_at: 9_999_999_999,
975            status: ActiveOrRevoked::Active,
976            clearance_epoch: 0,
977        };
978        reg.register_session(key.clone(), state.clone())
979            .await
980            .unwrap();
981        reg.revoke_session(&key).await.unwrap();
982
983        // Re-registration must fail — revoked sessions are never reassigned.
984        let result = reg.register_session(key.clone(), state).await;
985        assert!(
986            result.is_err(),
987            "a revoked session key must not be reactivated"
988        );
989    }
990
991    /// An unknown session key fails closed (is_revoked returns true).
992    #[tokio::test]
993    async fn unknown_session_fails_closed() {
994        use crate::auth::credential::{InMemorySessionRegistry, SessionRegistry};
995
996        let reg = InMemorySessionRegistry::new();
997        let key = SessionKey::oidc("https://a.example", "unknown");
998        assert!(
999            reg.is_revoked(&key).await,
1000            "unknown session must be treated as revoked (fail-closed)"
1001        );
1002    }
1003
1004    /// OIDC `sid` and `workload_session_id` are disjoint: revoking one does
1005    /// not affect the other even for the same issuer and value string.
1006    #[tokio::test]
1007    async fn session_namespaces_are_disjoint() {
1008        use crate::auth::credential::{
1009            ActiveOrRevoked, InMemorySessionRegistry, SessionKind, SessionRegistry, SessionState,
1010        };
1011
1012        let reg = InMemorySessionRegistry::new();
1013        let oidc_key = SessionKey::oidc("https://a.example", "ses-shared");
1014        let wl_key = SessionKey::workload("https://a.example", "ses-shared");
1015
1016        let oidc_state = SessionState {
1017            subject: "alice".to_owned(),
1018            tenant: "default".to_owned(),
1019            kind: SessionKind::Interactive,
1020            created_at: 0,
1021            expires_at: 9_999_999_999,
1022            status: ActiveOrRevoked::Active,
1023            clearance_epoch: 0,
1024        };
1025        let wl_state = SessionState {
1026            subject: "service:model".to_owned(),
1027            tenant: "default".to_owned(),
1028            kind: SessionKind::Workload,
1029            created_at: 0,
1030            expires_at: 9_999_999_999,
1031            status: ActiveOrRevoked::Active,
1032            clearance_epoch: 0,
1033        };
1034
1035        reg.register_session(oidc_key.clone(), oidc_state)
1036            .await
1037            .unwrap();
1038        reg.register_session(wl_key.clone(), wl_state)
1039            .await
1040            .unwrap();
1041
1042        // Revoke the OIDC session.
1043        reg.revoke_session(&oidc_key).await.unwrap();
1044        assert!(reg.is_revoked(&oidc_key).await, "OIDC session is revoked");
1045        assert!(
1046            !reg.is_revoked(&wl_key).await,
1047            "workload session with the same value string is NOT revoked"
1048        );
1049    }
1050}