1use std::collections::HashMap;
14use std::fmt;
15use std::sync::{Arc, OnceLock};
16
17#[derive(Clone, Debug, PartialEq, Eq, Hash)]
26pub enum CredentialValue {
27 Jwt(String),
29 Cwt(Vec<u8>),
31}
32
33impl CredentialValue {
34 pub fn jwt(s: impl Into<String>) -> Self {
36 Self::Jwt(s.into())
37 }
38
39 pub fn cwt(b: impl Into<Vec<u8>>) -> Self {
41 Self::Cwt(b.into())
42 }
43
44 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
70pub struct CredentialId {
71 pub issuer: String,
73 pub value: CredentialValue,
75}
76
77impl CredentialId {
78 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 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 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
118pub enum SessionIdentifier {
119 OidcSid(String),
123 WorkloadSessionId(String),
128}
129
130impl SessionIdentifier {
131 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
150pub struct SessionKey {
151 pub issuer: String,
153 pub id: SessionIdentifier,
155}
156
157impl SessionKey {
158 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 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 pub fn is_valid(&self) -> bool {
176 !self.issuer.is_empty() && !self.id.is_empty()
177 }
178}
179
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum SessionKind {
185 Interactive,
187 Workload,
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
193pub enum ActiveOrRevoked {
194 Active,
195 Revoked,
196}
197
198#[derive(Clone, Debug)]
204pub struct SessionState {
205 pub subject: String,
207 pub tenant: String,
210 pub kind: SessionKind,
213 pub created_at: i64,
215 pub expires_at: i64,
217 pub status: ActiveOrRevoked,
219 pub clearance_epoch: u64,
221}
222
223#[async_trait::async_trait]
232pub trait SessionRegistry: Send + Sync {
233 async fn session_state(&self, key: &SessionKey) -> Option<SessionState>;
237
238 async fn register_session(
244 &self,
245 key: SessionKey,
246 state: SessionState,
247 ) -> Result<(), SessionRegisterError>;
248
249 async fn revoke_session(&self, key: &SessionKey) -> Result<(), SessionRevokeError>;
261
262 async fn is_revoked(&self, key: &SessionKey) -> bool;
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct SessionRevokeError {
274 message: String,
275}
276
277impl SessionRevokeError {
278 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
294static GLOBAL_SESSION_REGISTRY: OnceLock<Arc<dyn SessionRegistry>> = OnceLock::new();
302
303pub 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#[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
325pub fn global_session_registry() -> Option<&'static Arc<dyn SessionRegistry>> {
327 GLOBAL_SESSION_REGISTRY.get()
328}
329
330#[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#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
392pub enum SessionRegisterError {
393 Exists(SessionExists),
395 KindMismatch(SessionKindMismatch),
397 InvalidRecord(InvalidSessionRecord),
399 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
440pub(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
453pub 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 #[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 #[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 #[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 if !key.is_valid() {
526 return Err(InvalidSessionRecord.into());
527 }
528 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 #[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 #[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, }
598 }
599}
600
601fn 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 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 #[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 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}