1use 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
25const SUBJECT: &str = "__luxid_subject";
27
28const FLASH_NEXT: &str = "__luxid_flash_next";
30
31const FLASH_NOW: &str = "__luxid_flash_now";
33
34pub 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 attached: bool,
46}
47
48#[derive(Debug, Clone, Default)]
50pub struct Session {
51 state: Arc<Mutex<State>>,
52}
53
54impl Session {
55 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 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 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 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 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 state.dirty = true;
209 }
210 None => {
211 if had_now {
212 state.dirty = true;
213 }
214 }
215 }
216 }
217
218 pub fn flush(&self) -> Result<()> {
220 self.write(|state| state.data.clear())
221 }
222
223 pub fn destroy(&self) -> Result<()> {
226 self.write(|state| {
227 state.data.clear();
228 state.destroyed = true;
229 })
230 }
231
232 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 pub fn regenerate(&self) -> Result<()> {
255 let id = new_id();
256 self.write(|state| state.id = id)
257 }
258
259 pub fn login(&self, identity: &Identity) -> Result<()> {
261 self.regenerate()?;
262 self.set_subject(identity.subject())
263 }
264
265 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
282pub 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#[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 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
357pub 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 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}