Skip to main content

rustlavel_auth/
middleware.rs

1//! The `session` middleware: cookie in, session out, and back again.
2//!
3//! ```ignore
4//! let sessions = SessionManager::from_config(&config, FileStore::new("storage/sessions"))?;
5//! router.middleware(sessions);
6//! ```
7//!
8//! After that a handler reaches the session through the request:
9//!
10//! ```ignore
11//! async fn show(req: Request) -> String {
12//!     req.session().put("last_seen", "/dashboard");
13//!     format!("visits: {:?}", req.session().get("visits"))
14//! }
15//! ```
16
17use crate::key::AppKey;
18use crate::session::{Session, is_valid_id};
19use crate::store::{DEFAULT_LIFETIME, SessionStore, SharedStore};
20use crate::{base64, constant_time_eq};
21use hmac::{Hmac, Mac};
22use rustlavel_core::{Config, Json, Result};
23use rustlavel_http::handler::BoxFuture;
24use rustlavel_http::middleware::{Middleware, Next};
25use rustlavel_http::{Cookie, Request, Response, SameSite};
26use sha2::Sha256;
27use std::collections::BTreeMap;
28use std::sync::{Arc, Mutex, MutexGuard};
29use std::time::Duration;
30
31type HmacSha256 = Hmac<Sha256>;
32
33/// The cookie name used when nothing is configured.
34pub const DEFAULT_COOKIE: &str = "rustlavel_session";
35
36/// The request's session, shared between the middleware and the handler.
37///
38/// `Request::extension` hands out a shared reference, but the middleware has to
39/// read the session back *after* the handler has changed it — so the session
40/// lives behind a mutex and both sides hold the same handle. Cloning a handle
41/// is cloning an `Arc`; every clone is the same session.
42#[derive(Clone)]
43pub struct SessionHandle(Arc<Mutex<Session>>);
44
45impl SessionHandle {
46    pub fn new(session: Session) -> Self {
47        SessionHandle(Arc::new(Mutex::new(session)))
48    }
49
50    /// Borrow the session directly.
51    ///
52    /// The guard is not `Send`, so holding it across an `.await` will not
53    /// compile — which is the behaviour we want: a session held open across an
54    /// await is a session held open across another request.
55    pub fn lock(&self) -> MutexGuard<'_, Session> {
56        self.0.lock().expect("session lock poisoned")
57    }
58
59    /// Run a closure against the session, releasing the lock immediately.
60    pub fn with<R>(&self, action: impl FnOnce(&mut Session) -> R) -> R {
61        action(&mut self.lock())
62    }
63
64    pub fn id(&self) -> String {
65        self.lock().id().to_string()
66    }
67
68    pub fn get(&self, key: &str) -> Option<Json> {
69        self.lock().get(key).cloned()
70    }
71
72    pub fn get_string(&self, key: &str) -> Option<String> {
73        self.lock().get_string(key)
74    }
75
76    pub fn has(&self, key: &str) -> bool {
77        self.lock().has(key)
78    }
79
80    pub fn put(&self, key: impl Into<String>, value: impl Into<Json>) {
81        self.lock().put(key, value);
82    }
83
84    pub fn forget(&self, key: &str) -> Option<Json> {
85        self.lock().forget(key)
86    }
87
88    pub fn flush(&self) {
89        self.lock().flush();
90    }
91
92    pub fn all(&self) -> BTreeMap<String, Json> {
93        self.lock().all().clone()
94    }
95
96    pub fn flash(&self, key: impl Into<String>, value: impl Into<Json>) {
97        self.lock().flash(key, value);
98    }
99
100    pub fn keep(&self, key: &str) {
101        self.lock().keep(key);
102    }
103
104    pub fn reflash(&self) {
105        self.lock().reflash();
106    }
107
108    /// Rotate the id, keeping the contents. See [`Session::regenerate`].
109    pub fn regenerate(&self) -> String {
110        self.lock().regenerate().to_string()
111    }
112
113    /// Empty the session and rotate the id.
114    pub fn invalidate(&self) -> String {
115        self.lock().invalidate().to_string()
116    }
117
118    /// The CSRF token, generated on first use.
119    pub fn token(&self) -> String {
120        self.lock().token()
121    }
122}
123
124impl std::fmt::Debug for SessionHandle {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.debug_struct("SessionHandle").field("id", &self.id()).finish()
127    }
128}
129
130/// `req.session()` — reaching the session from a handler.
131pub trait SessionExt {
132    /// The session, or `None` when the `session` middleware is not installed.
133    fn try_session(&self) -> Option<&SessionHandle>;
134
135    /// The session, panicking with an actionable message if it is absent.
136    fn session(&self) -> &SessionHandle;
137}
138
139impl SessionExt for Request {
140    fn try_session(&self) -> Option<&SessionHandle> {
141        self.extension::<SessionHandle>()
142    }
143
144    fn session(&self) -> &SessionHandle {
145        self.try_session().expect(
146            "no session on this request. Add the `session` middleware to the router \
147             (`router.middleware(SessionManager::from_config(&config, store)?)`) before any route \
148             that uses `req.session()`.",
149        )
150    }
151}
152
153/// Loads and stores the session around every request.
154///
155/// Cheap to clone; the clone shares one store.
156#[derive(Clone)]
157pub struct SessionManager {
158    inner: Arc<Inner>,
159}
160
161struct Inner {
162    store: SharedStore,
163    cookie_key: [u8; 32],
164    cookie: String,
165    lifetime: Duration,
166    path: String,
167    secure: bool,
168    same_site: SameSite,
169}
170
171impl SessionManager {
172    /// Build with an explicit key and store.
173    pub fn new(key: &AppKey, store: impl SessionStore) -> Self {
174        SessionManager { inner: Arc::new(SessionManager::defaults(key, store)) }
175    }
176
177    /// Build from configuration: `app.key`, `session.cookie`, `session.lifetime`.
178    ///
179    /// The store keeps its own lifetime — build it with
180    /// [`SessionManager::lifetime_from_config`] so the cookie and the stored
181    /// session expire together.
182    pub fn from_config(config: &Config, store: impl SessionStore) -> Result<Self> {
183        let mut inner = SessionManager::defaults(&AppKey::from_config(config)?, store);
184        inner.cookie = config.string("session.cookie", DEFAULT_COOKIE);
185        inner.lifetime = SessionManager::lifetime_from_config(config);
186        inner.path = config.string("session.path", "/");
187        // Default on in production, where the site is expected to be HTTPS.
188        inner.secure = config.bool("session.secure", config.is_production());
189
190        Ok(SessionManager { inner: Arc::new(inner) })
191    }
192
193    fn defaults(key: &AppKey, store: impl SessionStore) -> Inner {
194        let lifetime = store.lifetime();
195        Inner {
196            store: Arc::new(store),
197            cookie_key: key.derive("session-cookie"),
198            cookie: DEFAULT_COOKIE.to_string(),
199            lifetime,
200            path: "/".to_string(),
201            // `SameSite=Lax` already blocks the cross-site POST that CSRF
202            // depends on, so the cookie is only marked `Secure` when the
203            // application is actually served over HTTPS — otherwise local
204            // development over http:// would silently lose its session.
205            secure: false,
206            same_site: SameSite::Lax,
207        }
208    }
209
210    /// `session.lifetime`, in minutes, as Laravel writes it.
211    pub fn lifetime_from_config(config: &Config) -> Duration {
212        match config.int("session.lifetime", -1) {
213            minutes if minutes > 0 => Duration::from_secs(minutes as u64 * 60),
214            _ => DEFAULT_LIFETIME,
215        }
216    }
217
218    pub fn cookie_name(mut self, name: impl Into<String>) -> Self {
219        Arc::make_mut(&mut self.inner).cookie = name.into();
220        self
221    }
222
223    pub fn lifetime(mut self, lifetime: Duration) -> Self {
224        Arc::make_mut(&mut self.inner).lifetime = lifetime;
225        self
226    }
227
228    pub fn path(mut self, path: impl Into<String>) -> Self {
229        Arc::make_mut(&mut self.inner).path = path.into();
230        self
231    }
232
233    /// Mark the cookie `Secure`, so browsers only send it over HTTPS.
234    pub fn secure(mut self, secure: bool) -> Self {
235        Arc::make_mut(&mut self.inner).secure = secure;
236        self
237    }
238
239    pub fn same_site(mut self, same_site: SameSite) -> Self {
240        Arc::make_mut(&mut self.inner).same_site = same_site;
241        self
242    }
243
244    pub fn store(&self) -> &SharedStore {
245        &self.inner.store
246    }
247
248    /// The signed cookie value for a session id: `<id>.<mac>`.
249    ///
250    /// Signing does not hide the id — it is `HttpOnly` and travels over TLS —
251    /// it stops the *store* being probed. Without a MAC, anybody could send
252    /// millions of guessed ids and make the server hit the filesystem for each
253    /// one; with it, a forged cookie is rejected before the store is touched.
254    fn sign(&self, id: &str) -> String {
255        let mut mac =
256            HmacSha256::new_from_slice(&self.inner.cookie_key).expect("HMAC accepts any key length");
257        mac.update(id.as_bytes());
258        format!("{id}.{}", base64::encode_url(&mac.finalize().into_bytes()))
259    }
260
261    /// Recover the id from a cookie, or `None` if it was not signed by us.
262    fn unsign(&self, value: &str) -> Option<String> {
263        let (id, signature) = value.rsplit_once('.')?;
264        if !is_valid_id(id) {
265            return None;
266        }
267
268        let expected = self.sign(id);
269        let expected = expected.rsplit_once('.')?.1;
270        constant_time_eq(expected.as_bytes(), signature.as_bytes()).then(|| id.to_string())
271    }
272
273    fn cookie_for(&self, id: &str) -> Cookie {
274        Cookie::new(self.inner.cookie.clone(), self.sign(id))
275            .path(self.inner.path.clone())
276            .max_age(self.inner.lifetime)
277            .http_only(true)
278            .secure(self.inner.secure)
279            .same_site(self.inner.same_site)
280    }
281}
282
283impl Clone for Inner {
284    fn clone(&self) -> Self {
285        Inner {
286            store: Arc::clone(&self.store),
287            cookie_key: self.cookie_key,
288            cookie: self.cookie.clone(),
289            lifetime: self.lifetime,
290            path: self.path.clone(),
291            secure: self.secure,
292            same_site: self.same_site,
293        }
294    }
295}
296
297impl Middleware for SessionManager {
298    fn handle(&self, mut request: Request, next: Next) -> BoxFuture<Response> {
299        let manager = self.clone();
300
301        Box::pin(async move {
302            let presented = request
303                .cookie(&manager.inner.cookie)
304                .and_then(|value| manager.unsign(&value));
305
306            let (session, existed) = match &presented {
307                Some(id) => match manager.inner.store.read(id).await {
308                    Ok(Some(session)) => (session, true),
309                    Ok(None) => (Session::new(), false),
310                    Err(error) => {
311                        // A store that is down must not take the site down with
312                        // it: the visitor gets a fresh, empty session.
313                        rustlavel_core::error!("could not read the session: {error}");
314                        (Session::new(), false)
315                    }
316                },
317                None => (Session::new(), false),
318            };
319
320            let loaded_id = session.id().to_string();
321            let handle = SessionHandle::new(session);
322            request.extend(handle.clone());
323
324            let response = next.run(request).await;
325
326            // Age the flash and take a copy, then drop the lock: the guard must
327            // not be alive across the store's `.await`.
328            let (session, dirty) = {
329                let mut session = handle.lock();
330                session.age_flash();
331                (session.clone(), session.is_dirty())
332            };
333
334            // A visitor who never touched the session gets no cookie and no
335            // stored file — a crawler should not leave one behind per page.
336            if !dirty && !existed {
337                return response;
338            }
339
340            // `regenerate` gave the session a new id; the old record is now a
341            // valid credential nobody should still be able to present.
342            if existed && session.id() != loaded_id
343                && let Err(error) = manager.inner.store.destroy(&loaded_id).await
344            {
345                rustlavel_core::error!("could not destroy the previous session: {error}");
346            }
347
348            if let Err(error) = manager.inner.store.write(&session).await {
349                rustlavel_core::error!("could not write the session: {error}");
350                return response;
351            }
352
353            response.with_cookie(manager.cookie_for(session.id()))
354        })
355    }
356}
357
358impl std::fmt::Debug for SessionManager {
359    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360        f.debug_struct("SessionManager")
361            .field("cookie", &self.inner.cookie)
362            .field("lifetime", &self.inner.lifetime)
363            .field("secure", &self.inner.secure)
364            .finish()
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use crate::store::MemoryStore;
372    use rustlavel_http::{Method, Router, TestClient};
373
374    fn key() -> AppKey {
375        AppKey::from_bytes([3u8; 32])
376    }
377
378    fn manager() -> SessionManager {
379        SessionManager::new(&key(), MemoryStore::new())
380    }
381
382    /// Pull the session cookie out of a response, ready to send back.
383    fn cookie_of(response: &rustlavel_http::TestResponse) -> String {
384        let header = response
385            .header("set-cookie")
386            .unwrap_or_else(|| panic!("no set-cookie header on the response"));
387        header.split(';').next().unwrap().to_string()
388    }
389
390    fn counting_router(manager: SessionManager) -> Router {
391        let mut router = Router::new();
392        router.middleware(manager);
393        router.get("/count", |request: Request| async move {
394            let visits = request.session().get("visits").and_then(|v| v.as_i64()).unwrap_or(0) + 1;
395            request.session().put("visits", visits);
396            format!("{visits}")
397        });
398        router.get("/quiet", |_request: Request| async { "nothing to see" });
399        router.get("/flash", |request: Request| async move {
400            request.session().flash("status", "Saved");
401            "flashed"
402        });
403        router.get("/status", |request: Request| async move {
404            request.session().get_string("status").unwrap_or_else(|| "none".into())
405        });
406        router.get("/rotate", |request: Request| async move {
407            request.session().put("kept", "yes");
408            request.session().regenerate()
409        });
410        router
411    }
412
413    #[tokio::test]
414    async fn a_session_survives_between_requests_through_the_cookie() {
415        let client = TestClient::new(counting_router(manager()));
416
417        let first = client.get("/count").await.assert_ok();
418        assert_eq!(first.body(), "1");
419        let cookie = cookie_of(&first);
420        assert!(cookie.starts_with(DEFAULT_COOKIE));
421
422        let second = client
423            .send(Request::new(Method::Get, "/count").with_header("cookie", cookie.clone()))
424            .await;
425        assert_eq!(second.body(), "2");
426
427        let third = client
428            .send(Request::new(Method::Get, "/count").with_header("cookie", cookie))
429            .await;
430        assert_eq!(third.body(), "3");
431    }
432
433    #[tokio::test]
434    async fn the_session_cookie_is_http_only_and_scoped() {
435        let response = TestClient::new(counting_router(manager())).get("/count").await;
436        let header = response.header("set-cookie").unwrap();
437
438        assert!(header.contains("HttpOnly"), "header was {header}");
439        assert!(header.contains("SameSite=Lax"));
440        assert!(header.contains("Path=/"));
441        assert!(header.contains("Max-Age=7200"));
442        assert!(!header.contains("Secure"), "a plain-http development cookie is not Secure");
443    }
444
445    #[tokio::test]
446    async fn a_request_that_never_touches_the_session_gets_no_cookie() {
447        let response = TestClient::new(counting_router(manager())).get("/quiet").await.assert_ok();
448
449        assert_eq!(
450            response.header("set-cookie"),
451            None,
452            "nothing was stored, so there is nothing to hand the client"
453        );
454    }
455
456    #[tokio::test]
457    async fn a_forged_or_unsigned_cookie_starts_a_fresh_session() {
458        let client = TestClient::new(counting_router(manager()));
459
460        let real = client.get("/count").await;
461        let cookie = cookie_of(&real);
462
463        // Same id, signature replaced.
464        let (name_and_id, _) = cookie.rsplit_once('.').unwrap();
465        let forged = format!("{name_and_id}.{}", base64::encode_url(&[0u8; 32]));
466        let response = client
467            .send(Request::new(Method::Get, "/count").with_header("cookie", forged))
468            .await;
469        assert_eq!(response.body(), "1", "a forged cookie must not open the real session");
470
471        // An id-shaped value with no signature at all.
472        let response = client
473            .send(Request::new(Method::Get, "/count").with_header(
474                "cookie",
475                format!("{DEFAULT_COOKIE}={}", Session::new_id()),
476            ))
477            .await;
478        assert_eq!(response.body(), "1");
479    }
480
481    #[test]
482    fn a_cookie_signed_with_another_key_is_refused() {
483        let mine = SessionManager::new(&key(), MemoryStore::new());
484        let theirs = SessionManager::new(&AppKey::from_bytes([4u8; 32]), MemoryStore::new());
485        let id = Session::new_id();
486
487        assert_eq!(mine.unsign(&mine.sign(&id)).as_deref(), Some(id.as_str()));
488        assert!(mine.unsign(&theirs.sign(&id)).is_none());
489        // And a value that is not even shaped like a signed cookie.
490        assert!(mine.unsign("no-dot-here").is_none());
491        assert!(mine.unsign(&format!("not-an-id.{}", base64::encode_url(&[0u8; 32]))).is_none());
492    }
493
494    #[tokio::test]
495    async fn flashed_data_is_readable_on_the_next_request_and_gone_after_it() {
496        let client = TestClient::new(counting_router(manager()));
497
498        let flashed = client.get("/flash").await;
499        let cookie = cookie_of(&flashed);
500
501        let next = client
502            .send(Request::new(Method::Get, "/status").with_header("cookie", cookie.clone()))
503            .await;
504        assert_eq!(next.body(), "Saved");
505
506        let after = client
507            .send(Request::new(Method::Get, "/status").with_header("cookie", cookie))
508            .await;
509        assert_eq!(after.body(), "none");
510    }
511
512    #[tokio::test]
513    async fn regenerating_issues_a_new_cookie_and_drops_the_old_record() {
514        let manager = manager();
515        let store = Arc::clone(manager.store());
516        let client = TestClient::new(counting_router(manager));
517
518        let first = client.get("/count").await;
519        let old_cookie = cookie_of(&first);
520        let old_id = old_cookie.split_once('=').unwrap().1.rsplit_once('.').unwrap().0.to_string();
521        assert!(store.read(&old_id).await.unwrap().is_some());
522
523        let rotated = client
524            .send(Request::new(Method::Get, "/rotate").with_header("cookie", old_cookie.clone()))
525            .await;
526        let new_id = rotated.body();
527        let new_cookie = cookie_of(&rotated);
528
529        assert_ne!(new_id, old_id);
530        assert!(store.read(&old_id).await.unwrap().is_none(), "the old id must stop working");
531
532        let carried = store.read(&new_id).await.unwrap().expect("the new id holds the session");
533        assert_eq!(carried.get_string("kept").as_deref(), Some("yes"));
534        assert_ne!(new_cookie, old_cookie);
535    }
536
537    #[tokio::test]
538    async fn an_expired_stored_session_starts_over() {
539        let manager = SessionManager::new(&key(), MemoryStore::with_lifetime(Duration::ZERO));
540        let client = TestClient::new(counting_router(manager));
541
542        let first = client.get("/count").await;
543        let cookie = cookie_of(&first);
544
545        let second = client
546            .send(Request::new(Method::Get, "/count").with_header("cookie", cookie))
547            .await;
548        assert_eq!(second.body(), "1", "the stored session had already expired");
549    }
550
551    #[test]
552    fn configuration_drives_the_cookie_name_lifetime_and_secure_flag() {
553        let config = Config::new();
554        config.set("app.key", AppKey::generate());
555        config.set("session.cookie", "my_app_session");
556        config.set("session.lifetime", 30);
557        config.set("app.env", "production");
558
559        let manager = SessionManager::from_config(&config, MemoryStore::new()).unwrap();
560
561        assert_eq!(manager.inner.cookie, "my_app_session");
562        assert_eq!(manager.inner.lifetime, Duration::from_secs(30 * 60));
563        assert!(manager.inner.secure, "production cookies default to Secure");
564        assert_eq!(SessionManager::lifetime_from_config(&Config::new()), DEFAULT_LIFETIME);
565    }
566
567    #[test]
568    fn builders_override_configuration() {
569        let manager = manager()
570            .cookie_name("custom")
571            .lifetime(Duration::from_secs(60))
572            .path("/app")
573            .secure(true)
574            .same_site(SameSite::Strict);
575
576        assert_eq!(manager.inner.cookie, "custom");
577        assert_eq!(manager.inner.path, "/app");
578        assert!(manager.inner.secure);
579
580        let header = manager.cookie_for(&Session::new_id()).to_header();
581        assert!(header.contains("SameSite=Strict"));
582        assert!(header.contains("Secure"));
583        assert!(header.starts_with("custom="));
584    }
585
586    #[tokio::test]
587    async fn a_handler_without_the_middleware_says_what_is_missing() {
588        let mut router = Router::new();
589        router.get("/", |request: Request| async move {
590            assert!(request.try_session().is_none());
591            request.session().id()
592        });
593
594        // The router turns the panic into a 500 rather than aborting the test.
595        let response = TestClient::new(router).get("/").await;
596        assert_eq!(response.status(), 500);
597    }
598}