Skip to main content

hyprstream_rpc/auth/
credential.rs

1//! Issuer-scoped credential and session identity types.
2//!
3//! Per the v16 credential/session profile: credential identifiers are scoped
4//! by issuer `(iss, jti/cti)` and session identifiers are scoped by issuer
5//! `(iss, sid/workload_session_id)`. The credential and session namespaces
6//! are disjoint by construction — they have separate types, separate stores,
7//! and never share a key.
8//!
9//! CWT `cti` is a byte string. It is kept as bytes here and never stringified
10//! into the JWT `jti` text namespace, which would create an ambiguous collision
11//! domain. The [`CredentialValue`] enum preserves the encoding distinction.
12
13use std::collections::HashMap;
14use std::fmt;
15use std::sync::{Arc, OnceLock};
16
17// ── Credential identity ───────────────────────────────────────────────────
18
19/// A credential identifier value — the JWT `jti` (text) or CWT `cti` (bytes).
20///
21/// The two variants are disjoint by type: a CWT `cti` byte string is never
22/// stringified into the JWT `jti` text namespace. This prevents a CWT binary
23/// `cti` that happens to decode as valid UTF-8 from colliding with a JWT text
24/// `jti` from a different issuer's token.
25#[derive(Clone, Debug, PartialEq, Eq, Hash)]
26pub enum CredentialValue {
27    /// JWT `jti` claim (RFC 7519) — a case-sensitive text string.
28    Jwt(String),
29    /// CWT `cti` claim (RFC 8392) — a binary byte string, kept as raw bytes.
30    Cwt(Vec<u8>),
31}
32
33impl CredentialValue {
34    /// Construct a JWT `jti` credential value from a text string.
35    pub fn jwt(s: impl Into<String>) -> Self {
36        Self::Jwt(s.into())
37    }
38
39    /// Construct a CWT `cti` credential value from raw bytes.
40    pub fn cwt(b: impl Into<Vec<u8>>) -> Self {
41        Self::Cwt(b.into())
42    }
43
44    /// Whether this value is empty (zero-length string or bytes).
45    pub fn is_empty(&self) -> bool {
46        match self {
47            Self::Jwt(s) => s.is_empty(),
48            Self::Cwt(b) => b.is_empty(),
49        }
50    }
51}
52
53impl fmt::Display for CredentialValue {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::Jwt(s) => write!(f, "jti:{s}"),
57            Self::Cwt(b) => {
58                write!(f, "cti:{}", hex_compact(b))
59            }
60        }
61    }
62}
63
64/// Issuer-scoped credential identifier: `(iss, jti/cti)`.
65///
66/// Verifier stores namespace credential IDs by issuer as defense in depth:
67/// even if two issuers produce the same `jti`/`cti` value, only the
68/// `(issuer, value)` pair identifies one credential.
69#[derive(Clone, Debug, PartialEq, Eq, Hash)]
70pub struct CredentialId {
71    /// The `iss` claim identifying the credential issuer.
72    pub issuer: String,
73    /// The `jti` (JWT) or `cti` (CWT) token-unique identifier.
74    pub value: CredentialValue,
75}
76
77impl CredentialId {
78    /// Construct a JWT credential ID from an issuer URL and `jti` string.
79    pub fn jwt(issuer: impl Into<String>, jti: impl Into<String>) -> Self {
80        Self {
81            issuer: issuer.into(),
82            value: CredentialValue::jwt(jti),
83        }
84    }
85
86    /// Construct a CWT credential ID from an issuer URL and raw `cti` bytes.
87    pub fn cwt(issuer: impl Into<String>, cti: impl Into<Vec<u8>>) -> Self {
88        Self {
89            issuer: issuer.into(),
90            value: CredentialValue::cwt(cti),
91        }
92    }
93
94    /// Whether this credential ID is well-formed (non-empty issuer and value).
95    ///
96    /// Per v16 §3.1: empty issuer and malformed identifiers deny. Verification
97    /// boundaries MUST treat an invalid credential ID as fail-closed.
98    pub fn is_valid(&self) -> bool {
99        !self.issuer.is_empty() && !self.value.is_empty()
100    }
101}
102
103impl fmt::Display for CredentialId {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        write!(f, "({},{})", self.issuer, self.value)
106    }
107}
108
109// ── Session identity ──────────────────────────────────────────────────────
110
111/// A session identifier — disjoint OIDC `sid` vs workload session.
112///
113/// Per v16 §3.3: OIDC/user sessions carry the registered `sid` claim.
114/// Workload credential families use a separately typed identifier and do
115/// NOT overload OIDC `sid`. The two variants are disjoint types and wire
116/// namespaces; one cannot be substituted for the other.
117#[derive(Clone, Debug, PartialEq, Eq, Hash)]
118pub enum SessionIdentifier {
119    /// OIDC user-session ID (the registered `sid` claim). Unique within
120    /// an issuer; groups an interactive session whose access-token
121    /// rotations have distinct credential IDs.
122    OidcSid(String),
123    /// Workload credential family session ID (`workload_session_id`).
124    /// Used only when an issuer maintains a real revocable workload
125    /// credential family (e.g. bootstrap/renewal producing several WITs).
126    /// A standalone service credential with no such lifecycle omits it.
127    WorkloadSessionId(String),
128}
129
130impl SessionIdentifier {
131    /// Whether this identifier is empty.
132    pub fn is_empty(&self) -> bool {
133        match self {
134            Self::OidcSid(s) | Self::WorkloadSessionId(s) => s.is_empty(),
135        }
136    }
137}
138
139impl fmt::Display for SessionIdentifier {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        match self {
142            Self::OidcSid(s) => write!(f, "sid:{s}"),
143            Self::WorkloadSessionId(s) => write!(f, "wlses:{s}"),
144        }
145    }
146}
147
148/// Issuer-scoped session key: `(iss, sid/workload_session_id)`.
149#[derive(Clone, Debug, PartialEq, Eq, Hash)]
150pub struct SessionKey {
151    /// The `iss` claim identifying the session authority.
152    pub issuer: String,
153    /// The session identifier (OIDC `sid` or `workload_session_id`).
154    pub id: SessionIdentifier,
155}
156
157impl SessionKey {
158    /// Construct an OIDC session key.
159    pub fn oidc(issuer: impl Into<String>, sid: impl Into<String>) -> Self {
160        Self {
161            issuer: issuer.into(),
162            id: SessionIdentifier::OidcSid(sid.into()),
163        }
164    }
165
166    /// Construct a workload session key.
167    pub fn workload(issuer: impl Into<String>, id: impl Into<String>) -> Self {
168        Self {
169            issuer: issuer.into(),
170            id: SessionIdentifier::WorkloadSessionId(id.into()),
171        }
172    }
173
174    /// Whether this session key is well-formed (non-empty issuer and identifier).
175    pub fn is_valid(&self) -> bool {
176        !self.issuer.is_empty() && !self.id.is_empty()
177    }
178}
179
180// ── Session state ─────────────────────────────────────────────────────────
181
182/// Whether a session is interactive (OIDC user login) or workload.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum SessionKind {
185    /// OIDC/user-agent interactive session.
186    Interactive,
187    /// Workload credential family (e.g. bootstrap/renewal WIT rotation).
188    Workload,
189}
190
191/// Active-or-revoked session status.
192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
193pub enum ActiveOrRevoked {
194    Active,
195    Revoked,
196}
197
198/// Session state record per v16 §3.3.
199///
200/// The authority stores at least this record for every active session.
201/// Revocation updates `status` to [`ActiveOrRevoked::Revoked`], which causes
202/// every credential carrying that session ID to be rejected.
203#[derive(Clone, Debug)]
204pub struct SessionState {
205    /// Subject identifier (`sub` claim).
206    pub subject: String,
207    /// Verified tenant/domain (required per v16 §3.3 — every session is
208    /// tenant-bound).
209    pub tenant: String,
210    /// Interactive or workload session kind. MUST match the [`SessionKey`]'s
211    /// identifier variant (OIDC sid → Interactive, workload → Workload).
212    pub kind: SessionKind,
213    /// Creation timestamp (Unix seconds).
214    pub created_at: i64,
215    /// Expiry timestamp (Unix seconds).
216    pub expires_at: i64,
217    /// Active or revoked.
218    pub status: ActiveOrRevoked,
219    /// Clearance epoch at which the session's clearance was established.
220    pub clearance_epoch: u64,
221}
222
223// ── Session registry trait + in-memory implementation ─────────────────────
224
225/// Session registry: tracks active sessions and their revocation state.
226///
227/// Per v16 §3.3: revoking a `SessionKey` rejects every credential and handle
228/// carrying that session ID. The canonical registry is owned by the policy
229/// service and reached over the RPC bus by every other process (mirroring
230/// the credential-revocation authority), so the methods are async.
231#[async_trait::async_trait]
232pub trait SessionRegistry: Send + Sync {
233    /// Look up the state of a session, if known. Fail-closed consumers treat
234    /// `None` (unknown, or authority unreachable for a remote registry) as
235    /// revoked.
236    async fn session_state(&self, key: &SessionKey) -> Option<SessionState>;
237
238    /// Register a new session. Returns `Err` if a session already exists at
239    /// the given key — session identifiers are never reassigned (v16 §3.3).
240    /// A revoked session CANNOT be reactivated by re-registration. Also
241    /// rejects a key/state kind mismatch (OIDC sid must pair with Interactive,
242    /// workload must pair with Workload).
243    async fn register_session(
244        &self,
245        key: SessionKey,
246        state: SessionState,
247    ) -> Result<(), SessionRegisterError>;
248
249    /// Revoke a session: mark it revoked, then evict every credential
250    /// derived from it.
251    ///
252    /// Ordering: the session's status is set to [`ActiveOrRevoked::Revoked`]
253    /// BEFORE credential/handle eviction runs, so a concurrent verification
254    /// checking session state fails the revocation check while cached
255    /// authority is being flushed.
256    ///
257    /// Returns [`SessionRevokeError`] if the revocation authority did not
258    /// durably accept the publication; on error no state changes and no
259    /// handles are evicted (never a best-effort write).
260    async fn revoke_session(&self, key: &SessionKey) -> Result<(), SessionRevokeError>;
261
262    /// Whether a session is currently revoked, expired, or unknown. Returns
263    /// `true` if the session is revoked, expired, OR not found (fail-closed
264    /// for unknown sessions).
265    async fn is_revoked(&self, key: &SessionKey) -> bool;
266}
267
268/// The session authority did not durably accept a session revocation.
269///
270/// Publication failure must never look like success: callers surface this
271/// as an error instead of proceeding as though the session were revoked.
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct SessionRevokeError {
274    message: String,
275}
276
277impl SessionRevokeError {
278    /// Construct from a human-readable cause.
279    pub fn new(message: impl Into<String>) -> Self {
280        Self {
281            message: message.into(),
282        }
283    }
284}
285
286impl std::fmt::Display for SessionRevokeError {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        write!(f, "session revocation failed: {}", self.message)
289    }
290}
291
292impl std::error::Error for SessionRevokeError {}
293
294// ── Global registry ───────────────────────────────────────────────────────
295
296/// Process-global session registry. Set once at startup: the durable
297/// authority registry in the policy process, or a policy-authority RPC
298/// client registry everywhere else. Before it is set, consumers fail
299/// closed — a credential carrying a session ID cannot be admitted until
300/// the registry is published.
301static GLOBAL_SESSION_REGISTRY: OnceLock<Arc<dyn SessionRegistry>> = OnceLock::new();
302
303/// Publish the process-global session registry. Called once at startup; a
304/// second call returns an error so the caller can detect a publication race.
305pub fn set_global_session_registry(
306    registry: Arc<dyn SessionRegistry>,
307) -> Result<(), GlobalSessionRegistryAlreadySet> {
308    GLOBAL_SESSION_REGISTRY
309        .set(registry)
310        .map_err(|_| GlobalSessionRegistryAlreadySet)
311}
312
313/// Error returned when the global session registry was already published.
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315pub struct GlobalSessionRegistryAlreadySet;
316
317impl std::fmt::Display for GlobalSessionRegistryAlreadySet {
318    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
319        write!(f, "global session registry already published")
320    }
321}
322
323impl std::error::Error for GlobalSessionRegistryAlreadySet {}
324
325/// Access the process-global session registry, if published.
326pub fn global_session_registry() -> Option<&'static Arc<dyn SessionRegistry>> {
327    GLOBAL_SESSION_REGISTRY.get()
328}
329
330/// Error returned when a session already exists at the given key.
331#[derive(Debug, Clone, PartialEq, Eq)]
332pub struct SessionExists;
333
334impl std::fmt::Display for SessionExists {
335    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336        write!(
337            f,
338            "session already exists (identifiers are never reassigned)"
339        )
340    }
341}
342
343impl std::error::Error for SessionExists {}
344
345/// Error returned when a session key's identifier variant disagrees with the
346/// session state's kind (v16 §3.3 coherence requirement).
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct SessionKindMismatch;
349
350impl std::fmt::Display for SessionKindMismatch {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        write!(f, "session key variant does not match session state kind")
353    }
354}
355
356impl std::error::Error for SessionKindMismatch {}
357
358/// Error returned when a session registration record is malformed: an empty
359/// issuer or session identifier in the key, or an empty subject/tenant in the
360/// state (v16 §3.1 malformed-identifier denial, §3.3 record shape).
361#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct InvalidSessionRecord;
363
364impl std::fmt::Display for InvalidSessionRecord {
365    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366        write!(
367            f,
368            "malformed session record (empty issuer, identifier, subject, or tenant)"
369        )
370    }
371}
372
373impl std::error::Error for InvalidSessionRecord {}
374
375/// Error returned when the session authority could not durably accept a
376/// registration (durable write / transport failure) — the session was NOT
377/// registered and callers must surface the failure, never proceed as though
378/// it succeeded.
379#[derive(Debug, Clone, PartialEq, Eq)]
380pub struct SessionPublicationFailed;
381
382impl std::fmt::Display for SessionPublicationFailed {
383    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384        write!(f, "session registration was not durably accepted")
385    }
386}
387
388impl std::error::Error for SessionPublicationFailed {}
389
390/// Error returned by [`SessionRegistry::register_session`].
391#[derive(Debug, Clone, PartialEq, Eq)]
392pub enum SessionRegisterError {
393    /// A session already exists at the given key.
394    Exists(SessionExists),
395    /// The key's identifier variant disagrees with the state's kind.
396    KindMismatch(SessionKindMismatch),
397    /// The key or state record is malformed (empty required field).
398    InvalidRecord(InvalidSessionRecord),
399    /// The authority did not durably accept the registration.
400    PublicationFailed(SessionPublicationFailed),
401}
402
403impl std::fmt::Display for SessionRegisterError {
404    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405        match self {
406            Self::Exists(e) => write!(f, "{e}"),
407            Self::KindMismatch(e) => write!(f, "{e}"),
408            Self::InvalidRecord(e) => write!(f, "{e}"),
409            Self::PublicationFailed(e) => write!(f, "{e}"),
410        }
411    }
412}
413
414impl std::error::Error for SessionRegisterError {}
415
416impl From<SessionExists> for SessionRegisterError {
417    fn from(e: SessionExists) -> Self {
418        Self::Exists(e)
419    }
420}
421
422impl From<SessionKindMismatch> for SessionRegisterError {
423    fn from(e: SessionKindMismatch) -> Self {
424        Self::KindMismatch(e)
425    }
426}
427
428impl From<InvalidSessionRecord> for SessionRegisterError {
429    fn from(e: InvalidSessionRecord) -> Self {
430        Self::InvalidRecord(e)
431    }
432}
433
434impl From<SessionPublicationFailed> for SessionRegisterError {
435    fn from(e: SessionPublicationFailed) -> Self {
436        Self::PublicationFailed(e)
437    }
438}
439
440/// Validate that a session key's identifier variant matches the session state
441/// kind (OIDC sid → Interactive, workload → Workload).
442pub(crate) fn validate_key_kind_coherence(
443    key: &SessionKey,
444    state: &SessionState,
445) -> Result<(), SessionKindMismatch> {
446    match (&key.id, state.kind) {
447        (SessionIdentifier::OidcSid(_), SessionKind::Interactive)
448        | (SessionIdentifier::WorkloadSessionId(_), SessionKind::Workload) => Ok(()),
449        _ => Err(SessionKindMismatch),
450    }
451}
452
453/// In-memory session registry with TTL cleanup.
454///
455/// This is the default process-local implementation. The trait allows a
456/// Valkey/Redis-backed registry to drop in for multi-node deployments.
457pub struct InMemorySessionRegistry {
458    #[cfg(not(target_arch = "wasm32"))]
459    sessions: parking_lot::RwLock<HashMap<SessionKey, SessionState>>,
460    #[cfg(target_arch = "wasm32")]
461    sessions: std::sync::RwLock<HashMap<SessionKey, SessionState>>,
462}
463
464impl Default for InMemorySessionRegistry {
465    fn default() -> Self {
466        Self::new()
467    }
468}
469
470impl InMemorySessionRegistry {
471    pub fn new() -> Self {
472        Self {
473            sessions: Default::default(),
474        }
475    }
476
477    /// Whether any record (active, expired, or revoked) exists at the key.
478    /// Sync read-only probe for the durable registry's writer-lock paths.
479    #[cfg(not(target_arch = "wasm32"))]
480    pub(super) fn has_key(&self, key: &SessionKey) -> bool {
481        self.sessions.read().contains_key(key)
482    }
483
484    /// Insert an already-published record (durable load at startup, or the
485    /// durable registry's post-append memory publish): memory insert only —
486    /// no validation, no log write.
487    #[cfg(not(target_arch = "wasm32"))]
488    pub(super) fn insert_loaded(&self, key: SessionKey, state: SessionState) {
489        self.sessions.write().insert(key, state);
490    }
491
492    /// Flip a loaded record to revoked (durable load/revoke path): memory
493    /// update only — no log write, no cache-generation flush.
494    #[cfg(not(target_arch = "wasm32"))]
495    pub(super) fn mark_revoked_loaded(&self, key: &SessionKey) {
496        if let Some(state) = self.sessions.write().get_mut(key) {
497            state.status = ActiveOrRevoked::Revoked;
498        }
499    }
500}
501
502#[async_trait::async_trait]
503impl SessionRegistry for InMemorySessionRegistry {
504    async fn session_state(&self, key: &SessionKey) -> Option<SessionState> {
505        #[cfg(not(target_arch = "wasm32"))]
506        {
507            self.sessions.read().get(key).cloned()
508        }
509        #[cfg(target_arch = "wasm32")]
510        {
511            self.sessions
512                .read()
513                .expect("session registry lock poisoned")
514                .get(key)
515                .cloned()
516        }
517    }
518
519    async fn register_session(
520        &self,
521        key: SessionKey,
522        state: SessionState,
523    ) -> Result<(), SessionRegisterError> {
524        // Reject malformed keys (empty issuer or session identifier).
525        if !key.is_valid() {
526            return Err(InvalidSessionRecord.into());
527        }
528        // Require nonempty subject and tenant (v16 §3.3 record shape).
529        if state.subject.is_empty() || state.tenant.is_empty() {
530            return Err(InvalidSessionRecord.into());
531        }
532        validate_key_kind_coherence(&key, &state)?;
533        #[cfg(not(target_arch = "wasm32"))]
534        {
535            let mut map = self.sessions.write();
536            if map.contains_key(&key) {
537                return Err(SessionExists.into());
538            }
539            map.insert(key, state);
540            Ok(())
541        }
542        #[cfg(target_arch = "wasm32")]
543        {
544            let mut map = self
545                .sessions
546                .write()
547                .expect("session registry lock poisoned");
548            if map.contains_key(&key) {
549                return Err(SessionExists.into());
550            }
551            map.insert(key, state);
552            Ok(())
553        }
554    }
555
556    async fn revoke_session(&self, key: &SessionKey) -> Result<(), SessionRevokeError> {
557        // Phase 1 — PUBLISH: mark the session as revoked. In-memory
558        // publication cannot fail, so this registry always returns Ok.
559        #[cfg(not(target_arch = "wasm32"))]
560        {
561            if let Some(state) = self.sessions.write().get_mut(key) {
562                state.status = ActiveOrRevoked::Revoked;
563            }
564        }
565        #[cfg(target_arch = "wasm32")]
566        {
567            if let Some(state) = self
568                .sessions
569                .write()
570                .expect("session registry lock poisoned")
571                .get_mut(key)
572            {
573                state.status = ActiveOrRevoked::Revoked;
574            }
575        }
576
577        // Phase 2 — EVICT: flush the verified-subject cache generation so
578        // cached handles derived from credentials carrying this session are
579        // invalidated. This is a conservative broad eviction: it flushes
580        // ALL cached handles, not just those for this session. The
581        // correctness guarantee holds (no stale authority survives), at
582        // the cost of re-verifying unrelated subjects on their next access.
583        #[cfg(not(target_arch = "wasm32"))]
584        {
585            crate::auth::mac::flush_verified_subject_cache_generation();
586        }
587        Ok(())
588    }
589
590    async fn is_revoked(&self, key: &SessionKey) -> bool {
591        match self.session_state(key).await {
592            Some(state) => {
593                state.status == ActiveOrRevoked::Revoked
594                    || state.expires_at <= chrono::Utc::now().timestamp()
595            }
596            None => true, // fail-closed for unknown sessions
597        }
598    }
599}
600
601// ── Helpers ───────────────────────────────────────────────────────────────
602
603/// Compact hex encoding for display (not for storage or comparison).
604fn hex_compact(bytes: &[u8]) -> String {
605    if bytes.len() <= 8 {
606        bytes.iter().map(|b| format!("{b:02x}")).collect()
607    } else {
608        format!(
609            "{}…{}",
610            bytes[..4]
611                .iter()
612                .map(|b| format!("{b:02x}"))
613                .collect::<String>(),
614            bytes[bytes.len() - 4..]
615                .iter()
616                .map(|b| format!("{b:02x}"))
617                .collect::<String>(),
618        )
619    }
620}
621
622#[cfg(test)]
623#[allow(clippy::unwrap_used)]
624mod tests {
625    use super::*;
626
627    #[test]
628    fn jwt_and_cwt_values_never_collide() {
629        // A CWT cti that happens to be valid UTF-8 must not equal a JWT jti
630        // with the same bytes-as-string — they are different variants.
631        let text = "abc-123";
632        let jwt_val = CredentialValue::jwt(text);
633        let cwt_val = CredentialValue::cwt(text.as_bytes());
634        assert_ne!(jwt_val, cwt_val);
635        assert_ne!(hash_of(&jwt_val), hash_of(&cwt_val));
636    }
637
638    #[test]
639    fn credential_id_is_issuer_scoped() {
640        let id_a = CredentialId::jwt("https://a.example", "token-1");
641        let id_b = CredentialId::jwt("https://b.example", "token-1");
642        assert_ne!(id_a, id_b, "same jti, different issuer → different ID");
643    }
644
645    #[test]
646    fn session_key_oidc_and_workload_are_disjoint() {
647        let oidc = SessionKey::oidc("https://a.example", "ses-1");
648        let wl = SessionKey::workload("https://a.example", "ses-1");
649        assert_ne!(oidc, wl, "OIDC sid and workload session must not collide");
650        assert_ne!(hash_of(&oidc), hash_of(&wl));
651    }
652
653    /// Malformed registrations (empty issuer/identifier/subject/tenant) are
654    /// rejected as [`InvalidSessionRecord`], NOT as a kind mismatch — a
655    /// malformed record is not a kind disagreement.
656    #[tokio::test]
657    async fn malformed_registration_is_invalid_record_not_kind_mismatch() {
658        let reg = InMemorySessionRegistry::new();
659        let state = SessionState {
660            subject: "alice".to_owned(),
661            tenant: "default".to_owned(),
662            kind: SessionKind::Interactive,
663            created_at: 0,
664            expires_at: 9_999_999_999,
665            status: ActiveOrRevoked::Active,
666            clearance_epoch: 0,
667        };
668
669        let bad_key = reg
670            .register_session(SessionKey::oidc("", "ses-1"), state.clone())
671            .await;
672        assert!(
673            matches!(bad_key, Err(SessionRegisterError::InvalidRecord(_))),
674            "empty issuer key → InvalidRecord, got {bad_key:?}"
675        );
676
677        let mut empty_subject = state.clone();
678        empty_subject.subject = String::new();
679        let bad_state = reg
680            .register_session(
681                SessionKey::oidc("https://a.example", "ses-1"),
682                empty_subject,
683            )
684            .await;
685        assert!(
686            matches!(bad_state, Err(SessionRegisterError::InvalidRecord(_))),
687            "empty subject → InvalidRecord, got {bad_state:?}"
688        );
689
690        // A genuine kind mismatch still reports KindMismatch.
691        let mismatch = reg
692            .register_session(SessionKey::workload("https://a.example", "ses-2"), state)
693            .await;
694        assert!(
695            matches!(mismatch, Err(SessionRegisterError::KindMismatch(_))),
696            "workload key + interactive state → KindMismatch, got {mismatch:?}"
697        );
698    }
699
700    fn hash_of<T: std::hash::Hash>(v: &T) -> u64 {
701        use std::collections::hash_map::DefaultHasher;
702        use std::hash::Hasher;
703        let mut h = DefaultHasher::new();
704        v.hash(&mut h);
705        h.finish()
706    }
707}