sova-session 0.1.5

Session plugin for Sova
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Cookie-backed sessions for Sova (Express [`express-session`](https://expressjs.com/en/resources/middleware/session.html)-style).
//!
//! Flash helpers ([`Session::flash`], [`Session::take`]) store one-shot values for the next
//! request (status messages, validation errors, old form input).
//!
//! Persistence is [`SessionStore`]: [`KvSessionStore`], [`SqlSessionStore`], or
//! [`RedisSessionStore`]. Logout others/all:
//! [`SessionExt::logout_other_sessions`] / [`SessionExt::logout_all_sessions`].

mod store;
mod events;
#[cfg(feature = "sql")]
mod sql;
#[cfg(feature = "redis")]
mod redis_store;

use cookie::Cookie;
pub use cookie::SameSite;
use sova_cookies::{CookieLayer, CookieLayerPresent, Cookies, ResponseCookieExt};
use sova_core::extend::{named, BoxFuture, Needs};
use sova_core::{with_state, App, Error, EventBus, Plugin, Request, Result};
use sova_store::{namespace, KvStore, MemoryStore as KvMemory};
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::Duration;

pub use events::{SessionLogoutAll, SessionRegenerated};
pub use store::{KvSessionStore, SessionStore, SessionStoreHandle, SESSION_USER_KEY};
#[cfg(feature = "sql")]
pub use sql::SqlSessionStore;
#[cfg(feature = "redis")]
pub use redis_store::RedisSessionStore;

/// Session key for a one-line success/status message (templates: `status`).
pub const FLASH_STATUS: &str = "flash_status";
/// Session key for validation error map JSON (templates: `errors`).
pub const FLASH_ERRORS: &str = "flash_errors";
/// Session key for old form input JSON (templates: `old`).
pub const FLASH_OLD: &str = "flash_old";

#[derive(Debug)]
struct SessionInner {
    id: String,
    data: HashMap<String, String>,
    dirty: bool,
    /// Destroyed — remove from store and clear cookie.
    destroyed: bool,
    /// Sid rotated; old id should be removed after save.
    old_id: Option<String>,
    /// Fresh sid not yet persisted (for save_uninitialized).
    is_new: bool,
}

/// Shared per-request session (cheap to clone into middleware after `next`).
#[derive(Clone)]
pub struct Session {
    inner: Arc<Mutex<SessionInner>>,
    events: Option<EventBus>,
}

impl fmt::Debug for Session {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Session")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

impl Session {
    pub fn id(&self) -> String {
        self.inner.lock().unwrap().id.clone()
    }

    pub fn get(&self, key: &str) -> Option<String> {
        self.inner.lock().unwrap().data.get(key).cloned()
    }

    pub fn get_or(&self, key: &str, default: impl Into<String>) -> String {
        self.get(key).unwrap_or_else(|| default.into())
    }

    pub fn set(&self, key: impl Into<String>, value: impl Into<String>) {
        let mut g = self.inner.lock().unwrap();
        g.data.insert(key.into(), value.into());
        g.dirty = true;
    }

    /// One-shot value: survives until the next request that [`Self::take`]s it.
    pub fn flash(&self, key: impl Into<String>, value: impl Into<String>) {
        self.set(key, value);
    }

    /// Convenience for [`FLASH_STATUS`].
    pub fn flash_status(&self, msg: impl Into<String>) {
        self.flash(FLASH_STATUS, msg);
    }

    /// JSON flash (errors / old maps).
    pub fn flash_json(&self, key: &str, value: &serde_json::Value) {
        self.flash(
            key,
            serde_json::to_string(value).unwrap_or_else(|_| "{}".into()),
        );
    }

    /// Flash validation-style errors map (`{ field: message }`).
    pub fn flash_errors(&self, errors: &serde_json::Value) {
        self.flash_json(FLASH_ERRORS, errors);
    }

    /// Flash old form input map.
    pub fn flash_old(&self, old: &serde_json::Value) {
        self.flash_json(FLASH_OLD, old);
    }

    /// Read and clear a session key (empty string if missing).
    pub fn take(&self, key: &str) -> String {
        let mut g = self.inner.lock().unwrap();
        let val = g.data.remove(key).unwrap_or_default();
        if !val.is_empty() {
            g.dirty = true;
        }
        val
    }

    /// Parse JSON from [`Self::take`], or `{}` on empty/invalid.
    pub fn take_json(&self, key: &str) -> serde_json::Value {
        let raw = self.take(key);
        serde_json::from_str(&raw).unwrap_or_else(|_| serde_json::json!({}))
    }

    pub fn remove(&self, key: &str) {
        let mut g = self.inner.lock().unwrap();
        if g.data.remove(key).is_some() {
            g.dirty = true;
        }
    }

    pub fn clear(&self) {
        let mut g = self.inner.lock().unwrap();
        if !g.data.is_empty() {
            g.data.clear();
            g.dirty = true;
        }
    }

    /// Replace the entire session bag (marks dirty).
    pub fn replace(&self, data: HashMap<String, String>) {
        let mut g = self.inner.lock().unwrap();
        g.data = data;
        g.dirty = true;
    }

    /// Snapshot of all key/value pairs.
    pub fn data(&self) -> HashMap<String, String> {
        self.inner.lock().unwrap().data.clone()
    }

    /// Bind this session to a user id (for logout-others/all via [`SessionStore`]).
    pub fn bind_user(&self, user_id: impl Into<String>) {
        self.set(SESSION_USER_KEY, user_id);
    }

    /// User id from [`Self::bind_user`], if any.
    pub fn user_id(&self) -> Option<String> {
        self.get(SESSION_USER_KEY).filter(|s| !s.is_empty())
    }

    /// Drop session data and mark for store removal + cookie clear.
    pub fn destroy(&self) {
        let mut g = self.inner.lock().unwrap();
        g.data.clear();
        g.dirty = false;
        g.destroyed = true;
    }

    /// Issue a new session id, keep data, delete the old store entry.
    pub fn regenerate(&self) {
        let had_user = self.user_id().is_some();
        {
            let mut g = self.inner.lock().unwrap();
            let old = std::mem::replace(&mut g.id, new_sid());
            g.old_id = Some(old);
            g.dirty = true;
            g.is_new = true;
            g.destroyed = false;
        }
        if let Some(bus) = &self.events {
            bus.dispatch(SessionRegenerated { had_user });
        }
    }

    fn snapshot(&self) -> SessionSnapshot {
        let g = self.inner.lock().unwrap();
        SessionSnapshot {
            id: g.id.clone(),
            data: g.data.clone(),
            dirty: g.dirty,
            destroyed: g.destroyed,
            old_id: g.old_id.clone(),
            is_new: g.is_new,
        }
    }

    /// Detached empty session (not backed by a store — writes are local only).
    fn empty() -> Self {
        Self {
            inner: Arc::new(Mutex::new(SessionInner {
                id: String::new(),
                data: HashMap::new(),
                dirty: false,
                destroyed: false,
                old_id: None,
                is_new: true,
            })),
            events: None,
        }
    }
}

struct SessionSnapshot {
    id: String,
    data: HashMap<String, String>,
    dirty: bool,
    destroyed: bool,
    old_id: Option<String>,
    is_new: bool,
}

type HookFn = Arc<dyn Fn(Session, Request) -> BoxFuture<Result<Request>> + Send + Sync>;

/// Session middleware over a [`SessionStore`].
///
/// Cookie load/save stays here. App logic (hydrate user, ACL, …) goes in [`SessionLayer::hook`].
pub struct SessionLayer {
    store: Arc<dyn SessionStore>,
    cookie_name: String,
    cookie_name_explicit: bool,
    secure: bool,
    secure_explicit: bool,
    http_only: bool,
    same_site: SameSite,
    same_site_explicit: bool,
    path: String,
    ttl: Duration,
    ttl_explicit: bool,
    rolling: bool,
    save_uninitialized: bool,
    hook: Option<HookFn>,
}

impl SessionLayer {
    /// Wrap a [`KvStore`] (typically `namespace(store, "sess")`) in [`KvSessionStore`].
    pub fn new(kv: Arc<dyn KvStore>) -> Self {
        Self::from_store(Arc::new(KvSessionStore::new(kv)))
    }

    /// Use an arbitrary [`SessionStore`] (e.g. [`SqlSessionStore`]).
    pub fn from_store(store: Arc<dyn SessionStore>) -> Self {
        Self {
            store,
            cookie_name: "sova_sid".into(),
            cookie_name_explicit: false,
            secure: false,
            secure_explicit: false,
            http_only: true,
            same_site: SameSite::Lax,
            same_site_explicit: false,
            path: "/".into(),
            ttl: Duration::from_secs(86400),
            ttl_explicit: false,
            rolling: false,
            save_uninitialized: false,
            hook: None,
        }
    }

    /// SQL sessions — requires [`sova_db::Db`] installed first (`feature = "sql"`).
    #[cfg(feature = "sql")]
    pub fn sql(app: &App) -> Self {
        let pool = app.try_state::<sova_db::DbPool>().unwrap_or_else(|| {
            panic!("SessionLayer::sql requires Db plugin installed before session")
        });
        Self::from_store(Arc::new(SqlSessionStore::from_db_pool(pool.as_ref())))
    }

    /// Redis sessions — requires [`sova_redis::Redis`] installed first (`feature = "redis"`).
    #[cfg(feature = "redis")]
    pub fn redis(app: &App) -> Self {
        let pool = app.try_state::<sova_redis::RedisPool>().unwrap_or_else(|| {
            panic!("SessionLayer::redis requires Redis plugin installed before session")
        });
        Self::from_store(Arc::new(RedisSessionStore::from_redis_pool(pool.as_ref())))
    }

    /// Sessions on an installed [`sova_store::AppStore`] (namespaced `sess`).
    pub fn from_app_store(app: &App) -> Self {
        let store = app.try_state::<sova_store::AppStore>().unwrap_or_else(|| {
            panic!("SessionLayer::from_app_store requires SharedStore / AppStore installed")
        });
        Self::new(store.namespaced("sess"))
    }

    pub fn cookie_name(mut self, name: impl Into<String>) -> Self {
        self.cookie_name = name.into();
        self.cookie_name_explicit = true;
        self
    }

    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self.secure_explicit = true;
        self
    }

    pub fn http_only(mut self, on: bool) -> Self {
        self.http_only = on;
        self
    }

    pub fn same_site(mut self, same_site: SameSite) -> Self {
        self.same_site = same_site;
        self.same_site_explicit = true;
        self
    }

    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = path.into();
        self
    }

    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = ttl;
        self.ttl_explicit = true;
        self
    }

    /// Refresh store TTL and Set-Cookie on every response.
    pub fn rolling(mut self, on: bool) -> Self {
        self.rolling = on;
        self
    }

    /// Persist empty new sessions (Express default false).
    pub fn save_uninitialized(mut self, on: bool) -> Self {
        self.save_uninitialized = on;
        self
    }

    /// After cookie session is loaded (and set on `req`), run app logic.
    ///
    /// Clone Arcs from `req` **before** `async move`. Return the (possibly mutated) request:
    ///
    /// ```ignore
    /// SessionLayer::new(store).hook(|sess, mut req| async move {
    ///     if let Some(id) = sess.get("user_id") {
    ///         let db = req.state::<Db>().clone();
    ///         if let Some(u) = find_user(&db, &id).await? {
    ///             req.set(u);
    ///         }
    ///     }
    ///     Ok(req)
    /// })
    /// ```
    pub fn hook<F, Fut>(mut self, f: F) -> Self
    where
        F: Fn(Session, Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Request>> + Send + 'static,
    {
        self.hook = Some(Arc::new(move |sess, req| Box::pin(f(sess, req))));
        self
    }

    fn apply_config(&mut self, app: &App) {
        let Some(doc) = app.config_doc() else {
            return;
        };
        let Some(section) = doc.section("session") else {
            return;
        };
        if !self.cookie_name_explicit {
            if let Some(n) = section.get("cookie").and_then(|v| v.as_str()) {
                self.cookie_name = n.to_string();
            }
        }
        if !self.ttl_explicit {
            if let Some(s) = section.get("ttl").and_then(|v| v.as_str()) {
                if let Ok(d) = sova_core::extend::parse_duration(s) {
                    self.ttl = d;
                }
            }
        }
        if !self.same_site_explicit {
            if let Some(s) = section.get("same_site").and_then(|v| v.as_str()) {
                self.same_site = match s.to_ascii_lowercase().as_str() {
                    "strict" => SameSite::Strict,
                    "none" => SameSite::None,
                    _ => SameSite::Lax,
                };
            }
        }
        if let Some(v) = section.get("secure").and_then(|v| v.as_bool()) {
            self.secure = v;
            self.secure_explicit = true;
        }
    }

    fn apply_env_defaults(&mut self) {
        if self.secure_explicit {
            return;
        }
        // HTTPS deployments: prefer Secure cookies unless explicitly disabled.
        let production = std::env::var("SOVA_ENV")
            .map(|v| v.eq_ignore_ascii_case("production"))
            .unwrap_or(false);
        let session_secure = std::env::var("SESSION_SECURE")
            .map(|v| matches!(v.as_str(), "1" | "true" | "TRUE" | "yes"))
            .unwrap_or(false);
        if production || session_secure {
            self.secure = true;
        }
    }
}

impl Plugin for SessionLayer {
    fn id(&self) -> &'static str {
        "session"
    }

    fn meta(&self) -> sova_core::PluginMeta {
        sova_core::PluginMeta::new("Session")
            .description("Cookie sessions backed by a SessionStore")
            .version(env!("CARGO_PKG_VERSION"))
    }

    fn install(mut self, app: &mut App) {
        self.apply_config(app);
        self.apply_env_defaults();
        if !app.has_plugin("cookies") {
            app.install(CookieLayer);
        }

        app.state(SessionStoreHandle(Arc::clone(&self.store)));

        let store_check = Arc::clone(&self.store);
        app.register_check("session", move |_state| {
            let store = Arc::clone(&store_check);
            async move {
                let probe = "__sova_session_check__";
                let mut data = HashMap::new();
                data.insert("_probe".into(), "1".into());
                store
                    .save(probe, &data, Duration::from_secs(5))
                    .await;
                let got = store.load(probe).await;
                store.destroy(probe).await;
                if got.is_none() {
                    return Err(Error::Internal("session store probe failed".into()));
                }
                Ok(())
            }
        });

        app.use_middleware(named(
            "session",
            with_state(self, move |layer, mut req, next| {
                async move {
                    let had_cookie = req
                        .get::<Cookies>()
                        .and_then(|c| c.get(&layer.cookie_name).map(|s| s.to_string()));
                    let is_new = had_cookie.is_none();
                    let sid = had_cookie.unwrap_or_else(new_sid);

                    let data = if is_new {
                        HashMap::new()
                    } else {
                        layer.store.load(&sid).await.unwrap_or_default()
                    };
                    let session = Session {
                        inner: Arc::new(Mutex::new(SessionInner {
                            id: sid,
                            data,
                            dirty: false,
                            destroyed: false,
                            old_id: None,
                            is_new,
                        })),
                        events: req.try_state::<EventBus>().map(|b| (*b).clone()),
                    };
                    req.set(session.clone());

                    let req = if let Some(hook) = &layer.hook {
                        match hook(session.clone(), req).await {
                            Ok(r) => r,
                            Err(err) => return err.into_response(),
                        }
                    } else {
                        req
                    };

                    let mut res = next(req).await;
                    let snap = session.snapshot();

                    if snap.destroyed {
                        layer.store.destroy(&snap.id).await;
                        if let Some(old) = &snap.old_id {
                            layer.store.destroy(old).await;
                        }
                        let mut builder = Cookie::build((layer.cookie_name.clone(), ""))
                            .http_only(layer.http_only)
                            .same_site(layer.same_site)
                            .path(layer.path.clone())
                            .max_age(cookie::time::Duration::seconds(0));
                        if layer.secure {
                            builder = builder.secure(true);
                        }
                        return res.cookie(builder.build());
                    }

                    let should_persist = snap.dirty
                        || (snap.is_new && layer.save_uninitialized)
                        || (layer.rolling && !snap.is_new);

                    if should_persist {
                        if let Some(old) = &snap.old_id {
                            layer.store.destroy(old).await;
                        }
                        layer
                            .store
                            .save(&snap.id, &snap.data, layer.ttl)
                            .await;
                    }

                    let should_set_cookie = should_persist || (layer.rolling && !snap.is_new);
                    if should_set_cookie || (snap.is_new && snap.dirty) {
                        let mut builder = Cookie::build((layer.cookie_name.clone(), snap.id))
                            .http_only(layer.http_only)
                            .same_site(layer.same_site)
                            .path(layer.path.clone());
                        if layer.secure {
                            builder = builder.secure(true);
                        }
                        if let Ok(secs) = i64::try_from(layer.ttl.as_secs()) {
                            builder = builder.max_age(cookie::time::Duration::seconds(secs));
                        }
                        res = res.cookie(builder.build());
                    }

                    res
                }
            }),
        ));
        app.with(Needs::<CookieLayerPresent>::new());
    }
}

fn new_sid() -> String {
    let mut buf = [0u8; 16];
    if getrandom::getrandom(&mut buf).is_err() {
        let t = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        return format!("{t:032x}");
    }
    let mut s = String::with_capacity(32);
    for b in buf {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

/// Default in-memory sessions (`sova_store::MemoryStore` under `sess:`).
pub fn memory_sessions() -> SessionLayer {
    SessionLayer::new(Arc::new(namespace(Arc::new(KvMemory::new()), "sess")))
}

/// Convenient access to the request [`Session`] (empty session if the layer is absent).
pub trait SessionExt {
    fn session(&self) -> Session;

    fn flash(&self, key: impl Into<String>, value: impl Into<String>) {
        self.session().flash(key, value);
    }

    fn flash_status(&self, msg: impl Into<String>) {
        self.session().flash_status(msg);
    }

    fn flash_errors(&self, errors: &serde_json::Value) {
        self.session().flash_errors(errors);
    }

    fn flash_old(&self, old: &serde_json::Value) {
        self.session().flash_old(old);
    }

    /// Invalidate every other session for the bound user; keep the current cookie.
    ///
    /// Requires [`Session::bind_user`] (done by Passport/Fortify login).
    fn logout_other_sessions(
        &self,
    ) -> impl std::future::Future<Output = Result<u64>> + Send;

    /// Invalidate all sessions for the bound user, including this one (clears cookie).
    fn logout_all_sessions(
        &mut self,
    ) -> impl std::future::Future<Output = Result<u64>> + Send;
}

impl SessionExt for sova_core::Request {
    fn session(&self) -> Session {
        self.get::<Session>().cloned().unwrap_or_else(Session::empty)
    }

    async fn logout_other_sessions(&self) -> Result<u64> {
        let sess = self.session();
        let uid = sess
            .user_id()
            .ok_or_else(|| Error::BadRequest("no bound session user".into()))?;
        let handle = self.try_state::<SessionStoreHandle>().ok_or_else(|| {
            Error::Internal("SessionStore missing (is SessionLayer installed?)".into())
        })?;
        Ok(handle
            .0
            .destroy_user(&uid, Some(&sess.id()))
            .await)
    }

    async fn logout_all_sessions(&mut self) -> Result<u64> {
        let sess = self.session();
        let uid = sess
            .user_id()
            .ok_or_else(|| Error::BadRequest("no bound session user".into()))?;
        let handle = self.try_state::<SessionStoreHandle>().ok_or_else(|| {
            Error::Internal("SessionStore missing (is SessionLayer installed?)".into())
        })?;
        let n = handle.0.destroy_user(&uid, None).await;
        sess.destroy();
        let _ = self.take::<sova_core::RateLimitIdentity>();
        if let Some(bus) = self.try_state::<EventBus>() {
            bus.dispatch(SessionLogoutAll {
                user_id: uid,
                count: n,
            });
        }
        Ok(n)
    }
}

#[cfg(test)]
mod flash_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn flash_take_is_one_shot() {
        let s = Session::empty();
        s.flash_status("Saved");
        assert_eq!(s.take(FLASH_STATUS), "Saved");
        assert_eq!(s.take(FLASH_STATUS), "");

        s.flash_old(&json!({ "email": "a@b.c" }));
        let old = s.take_json(FLASH_OLD);
        assert_eq!(old["email"], "a@b.c");
        assert_eq!(s.take_json(FLASH_OLD), json!({}));
    }
}