Skip to main content

luxid_core/
session.rs

1//! Server-side sessions.
2//!
3//! A session is a bag of values keyed by an opaque id, carried in a cookie.
4//! The values live in a [`SessionStore`]; the cookie carries only the id, so a
5//! client can neither read nor forge the contents.
6//!
7//! The session handle is shared rather than owned. Middleware needs to persist
8//! whatever the action did, but the action *consumes* the context — so the
9//! handle wraps shared state, and the middleware keeps a clone to read back
10//! afterwards. That is the same problem the owning context created for the
11//! database scope, solved the same way.
12
13use std::collections::BTreeMap;
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, Instant};
16
17use serde::Serialize;
18use serde::de::DeserializeOwned;
19use serde_json::Value;
20
21use crate::auth::Identity;
22use crate::error::{Error, Result};
23use crate::middleware::BoxFuture;
24
25/// The reserved key holding the authenticated subject.
26const SUBJECT: &str = "__luxid_subject";
27
28/// Flash values written during this request, readable on the *next* one.
29const FLASH_NEXT: &str = "__luxid_flash_next";
30
31/// Flash values written during the previous request, readable now.
32const FLASH_NOW: &str = "__luxid_flash_now";
33
34/// Everything stored against one session id.
35pub type SessionData = BTreeMap<String, Value>;
36
37#[derive(Debug, Default)]
38struct State {
39    id: String,
40    data: SessionData,
41    dirty: bool,
42    destroyed: bool,
43    /// False when no session middleware ran, so writes can say so rather than
44    /// vanishing.
45    attached: bool,
46}
47
48/// The request's session.
49#[derive(Debug, Clone, Default)]
50pub struct Session {
51    state: Arc<Mutex<State>>,
52}
53
54impl Session {
55    /// A session that is not backed by anything. Reads are empty and writes
56    /// report the missing middleware.
57    pub fn detached() -> Self {
58        Self::default()
59    }
60
61    pub(crate) fn attached(id: String, data: SessionData) -> Self {
62        Self {
63            state: Arc::new(Mutex::new(State {
64                id,
65                data,
66                dirty: false,
67                destroyed: false,
68                attached: true,
69            })),
70        }
71    }
72
73    fn with<T>(&self, read: impl FnOnce(&State) -> T) -> T {
74        read(&self.state.lock().expect("session state is not poisoned"))
75    }
76
77    fn write<T>(&self, change: impl FnOnce(&mut State) -> T) -> Result<T> {
78        let mut state = self.state.lock().expect("session state is not poisoned");
79
80        if !state.attached {
81            return Err(Error::internal(
82                "no session is active on this route. Add `.middleware(Auth::session())`, \
83                 and bind a `SessionStore` in `providers()`.",
84            ));
85        }
86
87        state.dirty = true;
88        Ok(change(&mut state))
89    }
90
91    pub fn id(&self) -> String {
92        self.with(|state| state.id.clone())
93    }
94
95    pub fn is_active(&self) -> bool {
96        self.with(|state| state.attached)
97    }
98
99    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
100        let raw = self.with(|state| state.data.get(key).cloned());
101
102        match raw {
103            Some(value) => serde_json::from_value(value)
104                .map(Some)
105                .map_err(|err| Error::internal(format!("session key `{key}`: {err}"))),
106            None => Ok(None),
107        }
108    }
109
110    pub fn put<T: Serialize>(&self, key: impl Into<String>, value: T) -> Result<()> {
111        let key = key.into();
112        let value = serde_json::to_value(value)
113            .map_err(|err| Error::internal(format!("session key `{key}`: {err}")))?;
114
115        self.write(|state| {
116            state.data.insert(key, value);
117        })
118    }
119
120    pub fn has(&self, key: &str) -> bool {
121        self.with(|state| state.data.contains_key(key))
122    }
123
124    pub fn forget(&self, key: &str) -> Result<()> {
125        self.write(|state| {
126            state.data.remove(key);
127        })
128    }
129
130    /// Store a value readable on the *next* request only, then discarded.
131    ///
132    /// This is what makes the post-redirect-get pattern work: an action that
133    /// fails validation flashes the errors and redirects, and the GET that
134    /// follows reads them once. Nothing has to remember to clean up.
135    ///
136    /// Flash is deliberately separate from [`Session::put`]. A value that
137    /// should survive exactly one hop and a value that should persist are
138    /// different intentions, and conflating them is how stale error messages
139    /// end up rendered on unrelated pages.
140    pub fn flash<T: Serialize>(&self, key: impl Into<String>, value: T) -> Result<()> {
141        let key = key.into();
142        let value = serde_json::to_value(value)
143            .map_err(|err| Error::internal(format!("flash key `{key}`: {err}")))?;
144
145        self.write(|state| {
146            let bag = state
147                .data
148                .entry(FLASH_NEXT.to_owned())
149                .or_insert_with(|| Value::Object(Default::default()));
150
151            if let Some(map) = bag.as_object_mut() {
152                map.insert(key, value);
153            }
154        })
155    }
156
157    /// Read a value flashed by the previous request.
158    ///
159    /// Reading does not consume it: within one request the same flash can be
160    /// read by middleware and by an action. It is discarded when the *next*
161    /// request ages the bag.
162    pub fn flashed<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
163        let raw = self.with(|state| {
164            state
165                .data
166                .get(FLASH_NOW)
167                .and_then(|bag| bag.as_object())
168                .and_then(|map| map.get(key))
169                .cloned()
170        });
171
172        match raw {
173            Some(value) => serde_json::from_value(value)
174                .map(Some)
175                .map_err(|err| Error::internal(format!("flash key `{key}`: {err}"))),
176            None => Ok(None),
177        }
178    }
179
180    /// Whether anything was flashed by the previous request.
181    pub fn has_flash(&self) -> bool {
182        self.with(|state| {
183            state
184                .data
185                .get(FLASH_NOW)
186                .and_then(|bag| bag.as_object())
187                .is_some_and(|map| !map.is_empty())
188        })
189    }
190
191    /// Promote last request's flash bag to be readable now, and start an empty
192    /// one for this request. Called by the session middleware at load time.
193    ///
194    /// This does not mark the session dirty on its own: a request that neither
195    /// reads nor writes anything should not cause a store write just because
196    /// an empty bag was rotated.
197    pub(crate) fn age_flash(&self) {
198        let mut state = self.state.lock().expect("session state is not poisoned");
199
200        let carried = state.data.remove(FLASH_NEXT);
201        let had_now = state.data.remove(FLASH_NOW).is_some();
202
203        match carried {
204            Some(bag) => {
205                state.data.insert(FLASH_NOW.to_owned(), bag);
206                // Something changed that must reach the store, or the flash
207                // would be delivered again on the request after this one.
208                state.dirty = true;
209            }
210            None => {
211                if had_now {
212                    state.dirty = true;
213                }
214            }
215        }
216    }
217
218    /// Empty the session, keeping the id.
219    pub fn flush(&self) -> Result<()> {
220        self.write(|state| state.data.clear())
221    }
222
223    /// Invalidate the session entirely: the store entry is removed and the
224    /// cookie cleared.
225    pub fn destroy(&self) -> Result<()> {
226        self.write(|state| {
227            state.data.clear();
228            state.destroyed = true;
229        })
230    }
231
232    /// Record who this session belongs to.
233    ///
234    /// Does **not** rotate the id — call [`Session::regenerate`] on login to
235    /// defeat session fixation, which is what `login_as` does for you.
236    pub fn set_subject(&self, subject: impl Into<String>) -> Result<()> {
237        self.put(SUBJECT, subject.into())
238    }
239
240    pub fn subject(&self) -> Option<String> {
241        self.with(|state| {
242            state
243                .data
244                .get(SUBJECT)
245                .and_then(Value::as_str)
246                .map(str::to_owned)
247        })
248    }
249
250    /// Give the session a fresh id, keeping its contents.
251    ///
252    /// Do this whenever privilege changes. Without it, an attacker who fixed a
253    /// victim's session id before login still holds a valid id afterwards.
254    pub fn regenerate(&self) -> Result<()> {
255        let id = new_id();
256        self.write(|state| state.id = id)
257    }
258
259    /// Log an identity in: rotate the id, then record the subject.
260    pub fn login(&self, identity: &Identity) -> Result<()> {
261        self.regenerate()?;
262        self.set_subject(identity.subject())
263    }
264
265    /// Log out and invalidate, so the old cookie is worthless.
266    pub fn logout(&self) -> Result<()> {
267        self.destroy()
268    }
269
270    pub(crate) fn snapshot(&self) -> (String, SessionData, bool, bool) {
271        self.with(|state| {
272            (
273                state.id.clone(),
274                state.data.clone(),
275                state.dirty,
276                state.destroyed,
277            )
278        })
279    }
280}
281
282/// Where session data lives.
283pub trait SessionStore: Send + Sync + 'static {
284    fn load(&self, id: &str) -> BoxFuture<'_, Result<Option<SessionData>>>;
285
286    fn save(&self, id: &str, data: SessionData, ttl: Duration) -> BoxFuture<'_, Result<()>>;
287
288    fn destroy(&self, id: &str) -> BoxFuture<'_, Result<()>>;
289}
290
291/// An in-process store.
292///
293/// Fine for a single process and for tests. Sessions are lost on restart and
294/// are not shared between instances, so anything running more than one process
295/// needs a shared store.
296#[derive(Debug, Default)]
297pub struct MemoryStore {
298    entries: Mutex<BTreeMap<String, (SessionData, Instant)>>,
299}
300
301impl MemoryStore {
302    pub fn new() -> Self {
303        Self::default()
304    }
305
306    pub fn len(&self) -> usize {
307        self.entries.lock().expect("not poisoned").len()
308    }
309
310    pub fn is_empty(&self) -> bool {
311        self.len() == 0
312    }
313}
314
315impl SessionStore for MemoryStore {
316    fn load(&self, id: &str) -> BoxFuture<'_, Result<Option<SessionData>>> {
317        let id = id.to_owned();
318
319        Box::pin(async move {
320            let mut entries = self.entries.lock().expect("not poisoned");
321
322            // Expiry is checked on read rather than swept on a timer: a store
323            // this simple should not own a background task.
324            match entries.get(&id) {
325                Some((_, expires)) if *expires <= Instant::now() => {
326                    entries.remove(&id);
327                    Ok(None)
328                }
329                Some((data, _)) => Ok(Some(data.clone())),
330                None => Ok(None),
331            }
332        })
333    }
334
335    fn save(&self, id: &str, data: SessionData, ttl: Duration) -> BoxFuture<'_, Result<()>> {
336        let id = id.to_owned();
337
338        Box::pin(async move {
339            self.entries
340                .lock()
341                .expect("not poisoned")
342                .insert(id, (data, Instant::now() + ttl));
343            Ok(())
344        })
345    }
346
347    fn destroy(&self, id: &str) -> BoxFuture<'_, Result<()>> {
348        let id = id.to_owned();
349
350        Box::pin(async move {
351            self.entries.lock().expect("not poisoned").remove(&id);
352            Ok(())
353        })
354    }
355}
356
357/// A 256-bit opaque identifier.
358///
359/// Sourced from the OS random generator, not a counter or a timestamp: a
360/// guessable session id is an account takeover.
361pub fn new_id() -> String {
362    use argon2::password_hash::rand_core::RngCore;
363
364    let mut bytes = [0u8; 32];
365    argon2::password_hash::rand_core::OsRng.fill_bytes(&mut bytes);
366
367    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    fn session() -> Session {
375        Session::attached(new_id(), SessionData::new())
376    }
377
378    #[test]
379    fn ids_are_long_and_unpredictable() {
380        let a = new_id();
381        let b = new_id();
382
383        assert_eq!(a.len(), 64, "32 bytes as hex");
384        assert_ne!(a, b);
385    }
386
387    #[test]
388    fn values_round_trip() {
389        let session = session();
390
391        session.put("cart", vec![1, 2, 3]).expect("attached");
392        session.put("name", "Ada").expect("attached");
393
394        assert_eq!(
395            session.get::<Vec<i32>>("cart").unwrap(),
396            Some(vec![1, 2, 3])
397        );
398        assert_eq!(session.get::<String>("name").unwrap(), Some("Ada".into()));
399        assert_eq!(session.get::<String>("absent").unwrap(), None);
400    }
401
402    #[test]
403    fn a_detached_session_reports_the_missing_middleware() {
404        let session = Session::detached();
405
406        assert!(!session.is_active());
407        assert_eq!(session.get::<String>("name").unwrap(), None);
408
409        let err = session.put("name", "Ada").unwrap_err();
410        let message = format!("{err}");
411
412        assert!(message.contains("no session is active"), "{message}");
413        assert!(message.contains("Auth::session()"), "{message}");
414    }
415
416    #[test]
417    fn forget_and_flush() {
418        let session = session();
419        session.put("a", 1).unwrap();
420        session.put("b", 2).unwrap();
421
422        session.forget("a").unwrap();
423        assert!(!session.has("a"));
424        assert!(session.has("b"));
425
426        session.flush().unwrap();
427        assert!(!session.has("b"));
428    }
429
430    #[test]
431    fn login_rotates_the_id_to_defeat_fixation() {
432        let session = session();
433        let before = session.id();
434
435        session.login(&Identity::new("42")).expect("attached");
436
437        assert_ne!(session.id(), before, "the id must change on login");
438        assert_eq!(session.subject(), Some("42".to_owned()));
439    }
440
441    #[test]
442    fn logout_destroys_the_session() {
443        let session = session();
444        session.login(&Identity::new("42")).unwrap();
445
446        session.logout().unwrap();
447
448        let (_, data, _, destroyed) = session.snapshot();
449        assert!(destroyed);
450        assert!(data.is_empty());
451        assert_eq!(session.subject(), None);
452    }
453
454    #[test]
455    fn a_clone_shares_state_with_the_original() {
456        // This is what lets middleware read back what the action did.
457        let session = session();
458        let handle = session.clone();
459
460        session.put("touched", true).unwrap();
461
462        assert_eq!(handle.get::<bool>("touched").unwrap(), Some(true));
463        assert!(handle.snapshot().2, "dirty must be visible to the holder");
464    }
465
466    #[tokio::test]
467    async fn the_memory_store_round_trips() {
468        let store = MemoryStore::new();
469        let mut data = SessionData::new();
470        data.insert("name".into(), Value::String("Ada".into()));
471
472        store
473            .save("abc", data.clone(), Duration::from_secs(60))
474            .await
475            .unwrap();
476
477        assert_eq!(store.load("abc").await.unwrap(), Some(data));
478        assert_eq!(store.load("nope").await.unwrap(), None);
479
480        store.destroy("abc").await.unwrap();
481        assert_eq!(store.load("abc").await.unwrap(), None);
482    }
483
484    #[tokio::test]
485    async fn expired_entries_read_as_absent_and_are_dropped() {
486        let store = MemoryStore::new();
487
488        store
489            .save("abc", SessionData::new(), Duration::from_secs(0))
490            .await
491            .unwrap();
492
493        assert_eq!(store.load("abc").await.unwrap(), None);
494        assert!(
495            store.is_empty(),
496            "the expired entry was removed, not merely hidden"
497        );
498    }
499}