Skip to main content

glacier/
session.rs

1//! Cookie-backed sessions and flash messages.
2//!
3//! The session is a JSON object stored in an encrypted cookie, so it is
4//! private and tamper-proof but limited to roughly 4 KB. Store ids, not
5//! records. It is loaded lazily on first use and only re-written when it
6//! changes.
7
8use std::sync::{Arc, Mutex, MutexGuard};
9
10use serde::Serialize;
11use serde::de::DeserializeOwned;
12use serde_json::{Map, Value};
13
14use crate::cookies::{Cookie, Cookies, SameSite};
15use crate::error::Result;
16
17pub(crate) const COOKIE_NAME: &str = "_glacier_session";
18const FLASH_KEY: &str = "_flash";
19
20#[derive(Clone)]
21pub struct Session {
22    state: Arc<Mutex<State>>,
23    cookies: Cookies,
24    secure: bool,
25}
26
27#[derive(Default)]
28struct State {
29    loaded: bool,
30    dirty: bool,
31    data: Map<String, Value>,
32    /// Flash set by an earlier request (or `flash_now`), readable now.
33    flash: Map<String, Value>,
34    /// Whether this request read the flash, so it's spent.
35    flash_read: bool,
36    /// Kinds `put_flash` set during this request, for the next one.
37    flash_set: Vec<String>,
38}
39
40impl Session {
41    pub(crate) fn new(cookies: Cookies, secure: bool) -> Self {
42        Self {
43            state: Arc::default(),
44            cookies,
45            secure,
46        }
47    }
48
49    fn state(&self) -> MutexGuard<'_, State> {
50        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
51        if !state.loaded {
52            state.loaded = true;
53            let found = self.cookies.get_private_rotated(COOKIE_NAME);
54            // Encrypted with a previous key: written again with this one.
55            if found.as_ref().is_some_and(|(_, old)| *old) {
56                state.dirty = true;
57            }
58            if let Some(Value::Object(data)) =
59                found.and_then(|(raw, _)| serde_json::from_str(&raw).ok())
60            {
61                // Flash stays until a request reads it, as Rails' does: a
62                // request that never looks (an asset, a 404) leaves it.
63                if let Some(Value::Object(flash)) = data.get(FLASH_KEY) {
64                    state.flash = flash.clone();
65                }
66                state.data = data;
67            }
68        }
69        state
70    }
71
72    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
73        let value = self.state().data.get(key)?.clone();
74        serde_json::from_value(value).ok()
75    }
76
77    pub fn insert<T: Serialize>(&self, key: &str, value: T) -> Result<()> {
78        let value = serde_json::to_value(value)?;
79        let mut state = self.state();
80        state.data.insert(key.to_owned(), value);
81        state.dirty = true;
82        Ok(())
83    }
84
85    pub fn remove(&self, key: &str) {
86        let mut state = self.state();
87        if state.data.remove(key).is_some() {
88            state.dirty = true;
89        }
90    }
91
92    /// Removes everything, e.g. on sign-out.
93    pub fn clear(&self) {
94        let mut state = self.state();
95        state.data.clear();
96        state.dirty = true;
97    }
98
99    /// A flash message set by an earlier request (or `flash_now`). Reading
100    /// the flash spends it: the next request won't see these messages.
101    pub fn flash(&self, kind: &str) -> Option<String> {
102        let mut state = self.state();
103        if !state.flash.is_empty() && !state.flash_read {
104            state.flash_read = true;
105            state.dirty = true;
106        }
107        state
108            .flash
109            .get(kind)
110            .and_then(Value::as_str)
111            .map(str::to_owned)
112    }
113
114    /// A flash message for the page this request renders, not the next
115    /// one, as Rails' `flash.now`: for a form shown again with an error.
116    pub fn flash_now(&self, kind: &str, message: impl Into<String>) {
117        self.state()
118            .flash
119            .insert(kind.to_owned(), Value::String(message.into()));
120    }
121
122    /// Sets a flash message for the next request, typically before a redirect.
123    pub fn put_flash(&self, kind: &str, message: impl Into<String>) {
124        let mut state = self.state();
125        let flash = state
126            .data
127            .entry(FLASH_KEY)
128            .or_insert_with(|| Value::Object(Map::new()));
129        if let Value::Object(flash) = flash {
130            flash.insert(kind.to_owned(), Value::String(message.into()));
131        }
132        state.flash_set.push(kind.to_owned());
133        state.dirty = true;
134    }
135
136    /// Writes the session cookie if anything changed.
137    pub(crate) fn commit(&self) {
138        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
139        if !state.loaded || !state.dirty {
140            return;
141        }
142        // A read flash is spent: keep only what this request set.
143        if state.flash_read {
144            let set = std::mem::take(&mut state.flash_set);
145            let kept: Map<String, Value> = match state.data.remove(FLASH_KEY) {
146                Some(Value::Object(flash)) => flash
147                    .into_iter()
148                    .filter(|(kind, _)| set.contains(kind))
149                    .collect(),
150                _ => Map::new(),
151            };
152            if !kept.is_empty() {
153                state.data.insert(FLASH_KEY.to_owned(), Value::Object(kept));
154            }
155        }
156        if state.data.is_empty() {
157            if self.cookies.get(COOKIE_NAME).is_some() {
158                self.cookies.remove(COOKIE_NAME);
159            }
160            return;
161        }
162        let json = Value::Object(state.data.clone()).to_string();
163        self.cookies.add_private(
164            Cookie::build((COOKIE_NAME, json))
165                .path("/")
166                .http_only(true)
167                .same_site(SameSite::Lax)
168                .secure(self.secure),
169        );
170    }
171}