Skip to main content

hyprstream_rpc/auth/
session_store.rs

1//! Durable (file-backed) session registry — the policy process's canonical
2//! session store, mirroring the credential-revocation authority's discipline.
3//!
4//! A JSONL append log holds one record per registration and one per
5//! revocation. Registration validates, appends, and fsyncs BEFORE the session
6//! becomes visible; revocation appends its marker BEFORE the in-memory status
7//! flips and the verified-subject cache generation is flushed
8//! (publication-before-eviction, v16 §3.3). Session identifiers are never
9//! reassigned: records are never dropped on load (an expired-but-present
10//! record still blocks re-registration), unlike the credential store whose
11//! entries expire with their tokens.
12
13#[cfg(not(target_arch = "wasm32"))]
14use std::io::Write as _;
15
16#[cfg(not(target_arch = "wasm32"))]
17use super::credential::{
18    ActiveOrRevoked, InMemorySessionRegistry, SessionKey, SessionRegisterError, SessionRegistry,
19    SessionRevokeError, SessionState,
20};
21#[cfg(not(target_arch = "wasm32"))]
22use super::credential::{SessionIdentifier, SessionKind};
23
24/// One JSONL session record. Registration records carry the full state;
25/// revocation markers carry only the key and `status: "revoked"`.
26#[cfg(not(target_arch = "wasm32"))]
27#[derive(serde::Serialize, serde::Deserialize)]
28struct SessionRecord {
29    iss: String,
30    /// "oidc" or "workload" — the disjoint identifier namespaces.
31    kind: String,
32    id: String,
33    status: String, // "active" | "revoked"
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    subject: Option<String>,
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    tenant: Option<String>,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    created_at: Option<i64>,
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    expires_at: Option<i64>,
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    clearance_epoch: Option<u64>,
44}
45
46#[cfg(not(target_arch = "wasm32"))]
47impl SessionRecord {
48    fn from_registration(key: &SessionKey, state: &SessionState) -> Self {
49        let (kind, id) = key_parts(key);
50        Self {
51            iss: key.issuer.clone(),
52            kind: kind.to_owned(),
53            id: id.to_owned(),
54            status: "active".to_owned(),
55            subject: Some(state.subject.clone()),
56            tenant: Some(state.tenant.clone()),
57            created_at: Some(state.created_at),
58            expires_at: Some(state.expires_at),
59            clearance_epoch: Some(state.clearance_epoch),
60        }
61    }
62
63    fn revocation_marker(key: &SessionKey) -> Self {
64        let (kind, id) = key_parts(key);
65        Self {
66            iss: key.issuer.clone(),
67            kind: kind.to_owned(),
68            id: id.to_owned(),
69            status: "revoked".to_owned(),
70            subject: None,
71            tenant: None,
72            created_at: None,
73            expires_at: None,
74            clearance_epoch: None,
75        }
76    }
77
78    fn key(&self) -> Option<SessionKey> {
79        let key = match self.kind.as_str() {
80            "oidc" => SessionKey::oidc(self.iss.clone(), self.id.clone()),
81            "workload" => SessionKey::workload(self.iss.clone(), self.id.clone()),
82            _ => return None,
83        };
84        key.is_valid().then_some(key)
85    }
86
87    /// Decode a registration record into its state. `None` = corrupt (a
88    /// registration missing any state field).
89    fn registration_state(&self) -> Option<SessionState> {
90        let kind = match self.kind.as_str() {
91            "oidc" => SessionKind::Interactive,
92            "workload" => SessionKind::Workload,
93            _ => return None,
94        };
95        Some(SessionState {
96            subject: self.subject.clone()?,
97            tenant: self.tenant.clone()?,
98            kind,
99            created_at: self.created_at?,
100            expires_at: self.expires_at?,
101            status: ActiveOrRevoked::Active,
102            clearance_epoch: self.clearance_epoch?,
103        })
104    }
105}
106
107#[cfg(not(target_arch = "wasm32"))]
108fn key_parts(key: &SessionKey) -> (&'static str, &str) {
109    match &key.id {
110        SessionIdentifier::OidcSid(sid) => ("oidc", sid),
111        SessionIdentifier::WorkloadSessionId(id) => ("workload", id),
112    }
113}
114
115/// Durable session registry: an in-memory index in front of a JSONL append
116/// file. This is the canonical registry form owned by the policy process.
117#[cfg(not(target_arch = "wasm32"))]
118pub struct FileBackedSessionRegistry {
119    inner: InMemorySessionRegistry,
120    file: parking_lot::Mutex<std::fs::File>,
121}
122
123#[cfg(not(target_arch = "wasm32"))]
124impl FileBackedSessionRegistry {
125    /// Open (creating if absent) the durable registry at `path` and load every
126    /// record. Records are kept regardless of expiry: an expired record still
127    /// blocks re-registration of its identifier (sessions are never
128    /// reassigned), and `is_revoked` treats expired as revoked anyway.
129    ///
130    /// Corruption policy matches the credential store: a malformed COMPLETE
131    /// line is a hard error; a malformed or newline-less FINAL fragment is a
132    /// torn tail — truncated and logged, with a parseable fragment salvaged
133    /// through the normal write path. A freshly created file fsyncs its
134    /// directory; creating one where a store should pre-exist warns loudly.
135    pub fn open(path: &std::path::Path) -> std::io::Result<Self> {
136        let pre_existed = path.exists();
137        let file = std::fs::OpenOptions::new()
138            .read(true)
139            .append(true)
140            .create(true)
141            .open(path)?;
142        if !pre_existed {
143            if let Some(parent) = path.parent() {
144                std::fs::File::open(parent)?.sync_all()?;
145            }
146        }
147        let registry = Self {
148            inner: InMemorySessionRegistry::new(),
149            file: parking_lot::Mutex::new(file.try_clone()?),
150        };
151
152        let content = std::fs::read(path)?;
153        let complete_len = content
154            .iter()
155            .rposition(|&b| b == b'\n')
156            .map_or(0, |i| i + 1);
157        let mut loaded = 0usize;
158        for line in content[..complete_len].split(|&b| b == b'\n') {
159            if line.iter().all(u8::is_ascii_whitespace) {
160                continue;
161            }
162            let record: SessionRecord = serde_json::from_slice(line).map_err(|e| {
163                std::io::Error::new(
164                    std::io::ErrorKind::InvalidData,
165                    format!("corrupt session record: {e}"),
166                )
167            })?;
168            registry
169                .apply_loaded(record)
170                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
171            loaded += 1;
172        }
173
174        let tail = &content[complete_len..];
175        if !tail.is_empty() {
176            // Salvage a parseable tail fragment before truncating.
177            let salvage = serde_json::from_slice::<SessionRecord>(tail).ok();
178            {
179                let mut file = registry.file.lock();
180                file.set_len(complete_len as u64)?;
181                if let Some(record) = salvage {
182                    if record.key().is_some() {
183                        let mut line = serde_json::to_string(&record).map_err(|e| {
184                            std::io::Error::new(
185                                std::io::ErrorKind::InvalidData,
186                                format!("torn-tail salvage serialization failed: {e}"),
187                            )
188                        })?;
189                        line.push('\n');
190                        file.write_all(line.as_bytes())?;
191                        registry
192                            .apply_loaded(record)
193                            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
194                        loaded += 1;
195                    }
196                }
197                file.sync_all()?;
198            }
199            tracing::warn!(
200                path = %path.display(),
201                "torn session-log tail recovered: truncated to the last complete record"
202            );
203        }
204
205        if pre_existed {
206            tracing::info!(path = %path.display(), loaded, "session registry loaded");
207        } else {
208            tracing::warn!(
209                path = %path.display(),
210                "session registry did not exist — created a fresh EMPTY registry; \
211                 on a non-fresh deployment every prior session record is lost"
212            );
213        }
214        Ok(registry)
215    }
216
217    /// Apply one loaded record. Registrations insert (duplicate registration
218    /// of a known key is log corruption — hard error); revocation markers
219    /// flip a known key or are skipped when the registration is absent (its
220    /// record may itself have been lost to an older torn tail).
221    fn apply_loaded(&self, record: SessionRecord) -> Result<(), String> {
222        let key = record.key().ok_or("corrupt session record: invalid key")?;
223        match record.status.as_str() {
224            "active" => {
225                let state = record
226                    .registration_state()
227                    .ok_or("corrupt session record: incomplete registration")?;
228                if self.inner.has_key(&key) {
229                    return Err(format!(
230                        "corrupt session log: duplicate registration for {key:?}"
231                    ));
232                }
233                self.inner.insert_loaded(key, state);
234                Ok(())
235            }
236            "revoked" => {
237                self.inner.mark_revoked_loaded(&key);
238                Ok(())
239            }
240            other => Err(format!("corrupt session record: unknown status {other:?}")),
241        }
242    }
243
244    /// Append one record and fsync. Caller MUST hold the writer lock (the
245    /// `file` guard is passed in) so check/append/publish stay atomic.
246    fn append_durable(
247        &self,
248        file: &mut std::fs::File,
249        record: &SessionRecord,
250    ) -> Result<(), SessionRevokeError> {
251        let mut line = serde_json::to_string(record)
252            .map_err(|e| SessionRevokeError::new(format!("record serialization failed: {e}")))?;
253        line.push('\n');
254        file.write_all(line.as_bytes())
255            .and_then(|()| file.sync_all())
256            .map_err(|e| SessionRevokeError::new(format!("durable append failed: {e}")))
257    }
258}
259
260#[cfg(not(target_arch = "wasm32"))]
261#[async_trait::async_trait]
262impl SessionRegistry for FileBackedSessionRegistry {
263    async fn session_state(&self, key: &SessionKey) -> Option<SessionState> {
264        self.inner.session_state(key).await
265    }
266
267    async fn register_session(
268        &self,
269        key: SessionKey,
270        state: SessionState,
271    ) -> Result<(), SessionRegisterError> {
272        // Validate FIRST — an invalid record never reaches the log.
273        if !key.is_valid() || state.subject.is_empty() || state.tenant.is_empty() {
274            return Err(super::credential::InvalidSessionRecord.into());
275        }
276        super::credential::validate_key_kind_coherence(&key, &state)?;
277        let record = SessionRecord::from_registration(&key, &state);
278        {
279            // Writer lock: existence check + durable append + memory publish
280            // are atomic against concurrent registrations of the same key.
281            let mut file = self.file.lock();
282            if self.inner.has_key(&key) {
283                return Err(super::credential::SessionExists.into());
284            }
285            self.append_durable(&mut file, &record).map_err(|e| {
286                tracing::error!(error = %e, "session registration durable append failed");
287                SessionRegisterError::PublicationFailed(super::credential::SessionPublicationFailed)
288            })?;
289            self.inner.insert_loaded(key, state);
290        }
291        Ok(())
292    }
293
294    async fn revoke_session(&self, key: &SessionKey) -> Result<(), SessionRevokeError> {
295        {
296            let mut file = self.file.lock();
297            if !self.inner.has_key(key) {
298                // Revoking a never-registered session is a no-op (nothing to
299                // publish); identifiers are random and unguessable, so this
300                // cannot be used to pre-empt a future registration.
301                return Ok(());
302            }
303            // Phase 1 — PUBLISH (durable): the marker is appended and fsync'd
304            // BEFORE the in-memory status flips.
305            self.append_durable(&mut file, &SessionRecord::revocation_marker(key))?;
306            self.inner.mark_revoked_loaded(key);
307        }
308        // Phase 2 — EVICT: flush the verified-subject cache generation, so
309        // cached handles derived from credentials carrying this session are
310        // invalidated (strictly after publication).
311        crate::auth::mac::flush_verified_subject_cache_generation();
312        Ok(())
313    }
314
315    async fn is_revoked(&self, key: &SessionKey) -> bool {
316        self.inner.is_revoked(key).await
317    }
318}
319
320#[cfg(all(test, not(target_arch = "wasm32")))]
321#[allow(clippy::unwrap_used)]
322mod tests {
323    use super::*;
324    use crate::auth::credential::SessionKind;
325
326    /// Unique tempdir per test without a dev-dependency.
327    struct TestDir(std::path::PathBuf);
328
329    impl TestDir {
330        fn new(tag: &str) -> Self {
331            let unique = format!(
332                "hyprstream-session-store-test-{}-{}-{:?}",
333                std::process::id(),
334                tag,
335                std::time::SystemTime::now()
336                    .duration_since(std::time::UNIX_EPOCH)
337                    .unwrap()
338                    .as_nanos()
339            );
340            let path = std::env::temp_dir().join(unique);
341            std::fs::create_dir_all(&path).unwrap();
342            Self(path)
343        }
344
345        fn path(&self) -> &std::path::Path {
346            &self.0
347        }
348    }
349
350    impl Drop for TestDir {
351        fn drop(&mut self) {
352            let _ = std::fs::remove_dir_all(&self.0);
353        }
354    }
355
356    fn active_state(subject: &str, expires_at: i64) -> SessionState {
357        SessionState {
358            subject: subject.to_owned(),
359            tenant: "default".to_owned(),
360            kind: SessionKind::Interactive,
361            created_at: 1,
362            expires_at,
363            status: ActiveOrRevoked::Active,
364            clearance_epoch: 0,
365        }
366    }
367
368    #[tokio::test]
369    async fn register_revoke_survive_reopen_and_never_reassign() {
370        let dir = TestDir::new("durability");
371        let path = dir.path().join("sessions.jsonl");
372        let now = chrono::Utc::now().timestamp();
373        let key = SessionKey::oidc("https://issuer.example", "ses-durable");
374
375        {
376            let reg = FileBackedSessionRegistry::open(&path).unwrap();
377            reg.register_session(key.clone(), active_state("alice", now + 3600))
378                .await
379                .unwrap();
380            assert!(!reg.is_revoked(&key).await, "active after register");
381            reg.revoke_session(&key).await.unwrap();
382            assert!(reg.is_revoked(&key).await, "revoked after revoke");
383        }
384
385        let reopened = FileBackedSessionRegistry::open(&path).unwrap();
386        assert!(
387            reopened.is_revoked(&key).await,
388            "revocation must survive reopen"
389        );
390        // Never reassignable: the revoked record still blocks registration.
391        let result = reopened
392            .register_session(key.clone(), active_state("alice", now + 7200))
393            .await;
394        assert!(
395            matches!(result, Err(SessionRegisterError::Exists(_))),
396            "revoked session identifier must never be reassigned, got {result:?}"
397        );
398
399        // An expired-but-never-revoked record also blocks re-registration.
400        let expired_key = SessionKey::oidc("https://issuer.example", "ses-expired");
401        {
402            let reg = FileBackedSessionRegistry::open(&path).unwrap();
403            reg.register_session(expired_key.clone(), active_state("bob", 1))
404                .await
405                .unwrap();
406        }
407        let reopened = FileBackedSessionRegistry::open(&path).unwrap();
408        assert!(
409            reopened.is_revoked(&expired_key).await,
410            "expired session reports revoked"
411        );
412        let result = reopened
413            .register_session(expired_key.clone(), active_state("bob", now + 3600))
414            .await;
415        assert!(
416            matches!(result, Err(SessionRegisterError::Exists(_))),
417            "expired session identifier must not be reassigned, got {result:?}"
418        );
419    }
420
421    #[tokio::test]
422    async fn duplicate_register_appends_nothing_and_errors() {
423        let dir = TestDir::new("dup");
424        let path = dir.path().join("sessions.jsonl");
425        let now = chrono::Utc::now().timestamp();
426        let key = SessionKey::oidc("https://issuer.example", "ses-dup");
427
428        let reg = FileBackedSessionRegistry::open(&path).unwrap();
429        reg.register_session(key.clone(), active_state("alice", now + 3600))
430            .await
431            .unwrap();
432        let result = reg
433            .register_session(key.clone(), active_state("alice", now + 3600))
434            .await;
435        assert!(matches!(result, Err(SessionRegisterError::Exists(_))));
436        let content = std::fs::read_to_string(&path).unwrap();
437        assert_eq!(
438            content.matches("ses-dup").count(),
439            1,
440            "a duplicate registration must not append"
441        );
442    }
443
444    #[tokio::test]
445    async fn torn_tail_recovers_and_midfile_corruption_fails() {
446        let dir = TestDir::new("torn");
447        let path = dir.path().join("sessions.jsonl");
448        let now = chrono::Utc::now().timestamp();
449        let key = SessionKey::oidc("https://issuer.example", "ses-torn");
450
451        let complete = {
452            let reg = FileBackedSessionRegistry::open(&path).unwrap();
453            reg.register_session(key.clone(), active_state("alice", now + 3600))
454                .await
455                .unwrap();
456            std::fs::read(&path).unwrap()
457        };
458        {
459            use std::io::Write as _;
460            let mut f = std::fs::OpenOptions::new()
461                .append(true)
462                .open(&path)
463                .unwrap();
464            f.write_all(b"{\"iss\":\"https://issuer.example\",\"kind\":\"oid")
465                .unwrap();
466        }
467        let recovered = FileBackedSessionRegistry::open(&path).unwrap();
468        assert!(
469            !recovered.is_revoked(&key).await,
470            "complete records survive torn-tail recovery"
471        );
472        assert_eq!(
473            std::fs::read(&path).unwrap(),
474            complete,
475            "torn fragment is truncated to the last complete newline"
476        );
477
478        // Mid-file corruption still fails closed.
479        std::fs::write(
480            &path,
481            b"{\"iss\":\"x\",\"kind\":\"oidc\",\"id\":\"a\",\"status\":\"active\",\"subject\":\"s\",\"tenant\":\"t\",\"created_at\":1,\"expires_at\":9999999999,\"clearance_epoch\":0}\ngarbage\n",
482        )
483        .unwrap();
484        assert!(
485            FileBackedSessionRegistry::open(&path).is_err(),
486            "mid-file corruption must fail closed"
487        );
488    }
489
490    #[tokio::test]
491    async fn namespaces_and_validation_hold_through_the_durable_wrapper() {
492        let dir = TestDir::new("ns");
493        let path = dir.path().join("sessions.jsonl");
494        let now = chrono::Utc::now().timestamp();
495        let reg = FileBackedSessionRegistry::open(&path).unwrap();
496
497        // Kind coherence is enforced before any log write.
498        let wl_key = SessionKey::workload("https://issuer.example", "ses-kind");
499        let result = reg
500            .register_session(wl_key, active_state("svc", now + 3600))
501            .await;
502        assert!(
503            matches!(result, Err(SessionRegisterError::KindMismatch(_))),
504            "workload key + interactive state must fail, got {result:?}"
505        );
506        assert_eq!(
507            std::fs::read_to_string(&path).unwrap().len(),
508            0,
509            "a rejected registration never reaches the log"
510        );
511
512        // OIDC vs workload namespaces stay disjoint on disk.
513        let oidc_key = SessionKey::oidc("https://issuer.example", "ses-shared");
514        let workload_key = SessionKey::workload("https://issuer.example", "ses-shared");
515        let mut wl_state = active_state("svc", now + 3600);
516        wl_state.kind = SessionKind::Workload;
517        reg.register_session(oidc_key.clone(), active_state("alice", now + 3600))
518            .await
519            .unwrap();
520        reg.register_session(workload_key.clone(), wl_state)
521            .await
522            .unwrap();
523        reg.revoke_session(&oidc_key).await.unwrap();
524        assert!(reg.is_revoked(&oidc_key).await);
525        assert!(
526            !reg.is_revoked(&workload_key).await,
527            "workload session with the same id string is unaffected"
528        );
529        drop(reg);
530        let reopened = FileBackedSessionRegistry::open(&path).unwrap();
531        assert!(reopened.is_revoked(&oidc_key).await);
532        assert!(!reopened.is_revoked(&workload_key).await);
533    }
534
535    #[tokio::test]
536    async fn unknown_session_revoke_is_a_noop_without_log_write() {
537        let dir = TestDir::new("unknown");
538        let path = dir.path().join("sessions.jsonl");
539        let reg = FileBackedSessionRegistry::open(&path).unwrap();
540        let key = SessionKey::oidc("https://issuer.example", "ses-never-registered");
541        reg.revoke_session(&key).await.unwrap();
542        assert_eq!(
543            std::fs::read_to_string(&path).unwrap().len(),
544            0,
545            "revoking an unknown session must not append"
546        );
547        // And the identifier remains registerable (no pre-emption tombstone).
548        let now = chrono::Utc::now().timestamp();
549        reg.register_session(key.clone(), active_state("alice", now + 3600))
550            .await
551            .unwrap();
552        assert!(!reg.is_revoked(&key).await);
553    }
554}