rustango 0.60.7

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! Server-side session store backed by [`crate::cache::Cache`].
//!
//! The cookie holds only an opaque session ID. Everything else lives
//! in the cache. Use `RedisCache` when several replicas must share
//! sessions, or `InMemoryCache` for one process and for tests.
//!
//! Unlike a JWT, a session can be revoked: delete the cache entry and
//! every replica sees the user logged out. The cost is one cache read
//! per authenticated request.
//!
//! Send the cookie with `HttpOnly`, `Secure` and a `SameSite` value,
//! and call [`SessionStore::save`](crate::sessions::SessionStore::save)
//! again after login so the user gets
//! a new ID. Reusing the ID across the login boundary leaves the door
//! open to session fixation.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::sessions::{Session, SessionStore};
//! use rustango::cache::{BoxedCache, InMemoryCache};
//! use std::sync::Arc;
//!
//! let store = SessionStore::new(redis_cache);
//!
//! // After successful login:
//! let mut session = Session::new();
//! session.set("user_id", 42);
//! session.set("csrf_at", chrono::Utc::now().to_rfc3339());
//! let id = store.save(&session).await?;
//! // Set a cookie: format!("rustango_session={id}; HttpOnly; SameSite=Lax")
//!
//! // On subsequent requests:
//! let session = store.load(&id).await?.unwrap_or_default();
//! let user_id: Option<i64> = session.get("user_id");
//!
//! // Logout — drops the cache entry, cookie is now meaningless.
//! store.destroy(&id).await;
//! ```

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;

use crate::cache::{BoxedCache, CacheError};

const KEY_PREFIX: &str = "session";
const DEFAULT_TTL_SECS: u64 = 60 * 60 * 24 * 14; // 2 weeks
const ID_BYTES: usize = 24; // 192 bits, base64 → 32 chars

/// Per-request session bag: typed values under string keys, plus a
/// dirty flag so the store can skip a write when nothing changed.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Session {
    data: HashMap<String, Value>,
    #[serde(skip)]
    dirty: bool,
}

impl Session {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Read a typed value. `None` when the key is missing or the
    /// stored value is not a `T`.
    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
        self.data
            .get(key)
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// Store a value and mark the session dirty.
    pub fn set<T: Serialize>(&mut self, key: impl Into<String>, value: T) {
        if let Ok(v) = serde_json::to_value(value) {
            self.data.insert(key.into(), v);
            self.dirty = true;
        }
    }

    /// Remove a key and return its old value, if there was one.
    pub fn remove(&mut self, key: &str) -> Option<Value> {
        let prev = self.data.remove(key);
        if prev.is_some() {
            self.dirty = true;
        }
        prev
    }

    /// Remove every key and mark the session dirty.
    pub fn clear(&mut self) {
        if !self.data.is_empty() {
            self.dirty = true;
        }
        self.data.clear();
    }

    /// `true` when something was set, removed or cleared since the
    /// last load or save.
    #[must_use]
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    #[must_use]
    pub fn keys(&self) -> impl Iterator<Item = &String> {
        self.data.keys()
    }
}

#[derive(Debug, thiserror::Error)]
pub enum SessionError {
    #[error("cache: {0}")]
    Cache(#[from] CacheError),
    #[error("session deserialize: {0}")]
    Serialization(String),
}

#[derive(Clone)]
pub struct SessionStore {
    cache: BoxedCache,
    ttl: Arc<Duration>,
}

impl SessionStore {
    #[must_use]
    pub fn new(cache: BoxedCache) -> Self {
        Self {
            cache,
            ttl: Arc::new(Duration::from_secs(DEFAULT_TTL_SECS)),
        }
    }

    /// Set the per-session TTL. Default is 2 weeks.
    #[must_use]
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = Arc::new(ttl);
        self
    }

    /// Store `session` under a new ID and return it. Use this at
    /// login, so the user gets a fresh ID. To update a session that
    /// already exists, use [`Self::save_with_id`].
    ///
    /// # Errors
    /// A cache or serialization error.
    pub async fn save(&self, session: &Session) -> Result<String, SessionError> {
        let id = generate_id();
        self.save_with_id(&id, session).await?;
        Ok(id)
    }

    /// Store `session` under `id`, replacing any existing entry.
    ///
    /// # Errors
    /// A cache or serialization error.
    pub async fn save_with_id(&self, id: &str, session: &Session) -> Result<(), SessionError> {
        let json = serde_json::to_string(session)
            .map_err(|e| SessionError::Serialization(e.to_string()))?;
        self.cache
            .set(&self.cache_key(id), &json, Some(*self.ttl))
            .await?;
        Ok(())
    }

    /// Load a session by ID. Missing, expired and unreadable entries
    /// all give `Ok(None)`.
    ///
    /// # Errors
    /// A cache error. A value that fails to parse gives `Ok(None)`
    /// instead, so a stored-format change does not 500 every request.
    pub async fn load(&self, id: &str) -> Result<Option<Session>, SessionError> {
        let Some(raw) = self.cache.get(&self.cache_key(id)).await? else {
            return Ok(None);
        };
        let mut session: Session = match serde_json::from_str(&raw) {
            Ok(s) => s,
            Err(_) => return Ok(None),
        };
        // A freshly loaded session is clean until something changes it.
        session.dirty = false;
        Ok(Some(session))
    }

    /// Delete the session, as on logout. Does nothing for an unknown
    /// ID.
    ///
    /// # Errors
    /// A cache error.
    pub async fn destroy(&self, id: &str) -> Result<(), SessionError> {
        self.cache.delete(&self.cache_key(id)).await?;
        Ok(())
    }

    /// Extend the session's TTL without changing its contents. Call
    /// it on each request to keep active users signed in.
    ///
    /// # Errors
    /// A cache error. Returns `false` when the session is gone.
    pub async fn touch(&self, id: &str) -> Result<bool, SessionError> {
        // `Cache::touch` only extends a live key, so it cannot undo a racing destroy (#2300).
        Ok(self
            .cache
            .touch(&self.cache_key(id), Some(*self.ttl))
            .await?)
    }

    fn cache_key(&self, id: &str) -> String {
        format!("{KEY_PREFIX}:{id}")
    }
}

/// Make a 32-character base64url session ID with 192 bits of entropy,
/// above the 128 bits usually recommended. It draws from the OS CSPRNG
/// ([`rand::rngs::OsRng`]), not `thread_rng`, because a session ID is
/// an authentication secret.
fn generate_id() -> String {
    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
    use rand::{rngs::OsRng, RngCore};
    let mut buf = [0u8; ID_BYTES];
    OsRng.fill_bytes(&mut buf);
    URL_SAFE_NO_PAD.encode(buf)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::InMemoryCache;
    use std::sync::Arc as StdArc;

    fn store() -> SessionStore {
        let cache: BoxedCache = StdArc::new(InMemoryCache::new());
        SessionStore::new(cache)
    }

    // -------- Session bag

    #[test]
    fn fresh_session_is_clean_and_empty() {
        let s = Session::new();
        assert!(!s.is_dirty());
        assert!(s.is_empty());
        assert_eq!(s.len(), 0);
    }

    #[test]
    fn set_marks_dirty_and_stores() {
        let mut s = Session::new();
        s.set("user_id", 42_i64);
        assert!(s.is_dirty());
        assert_eq!(s.get::<i64>("user_id"), Some(42));
        assert_eq!(s.len(), 1);
    }

    #[test]
    fn get_returns_none_for_missing() {
        let s = Session::new();
        assert_eq!(s.get::<i64>("nope"), None);
    }

    #[test]
    fn get_returns_none_for_wrong_type() {
        let mut s = Session::new();
        s.set("flag", "string-not-a-number");
        // A wrong-type read returns None instead of panicking.
        assert_eq!(s.get::<i64>("flag"), None);
    }

    #[test]
    fn remove_returns_previous_and_marks_dirty() {
        let mut s = Session::new();
        s.set("k", "v");
        let prev = s.remove("k");
        assert_eq!(prev.unwrap(), "v");
        assert!(s.is_dirty());
        assert!(s.is_empty());
    }

    #[test]
    fn remove_missing_does_not_mark_dirty() {
        let mut s = Session::new();
        assert!(s.remove("nope").is_none());
        assert!(!s.is_dirty());
    }

    #[test]
    fn clear_wipes_all_keys() {
        let mut s = Session::new();
        s.set("a", 1);
        s.set("b", 2);
        s.clear();
        assert!(s.is_empty());
        assert!(s.is_dirty());
    }

    #[test]
    fn keys_iterates_inserted_keys() {
        let mut s = Session::new();
        s.set("a", 1);
        s.set("b", 2);
        let mut keys: Vec<&String> = s.keys().collect();
        keys.sort();
        assert_eq!(
            keys.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            vec!["a", "b"]
        );
    }

    // -------- SessionStore

    #[tokio::test]
    async fn save_then_load_roundtrips() {
        let store = store();
        let mut s = Session::new();
        s.set("user_id", 42_i64);
        s.set("name", "Alice");
        let id = store.save(&s).await.unwrap();

        let loaded = store.load(&id).await.unwrap().unwrap();
        assert_eq!(loaded.get::<i64>("user_id"), Some(42));
        assert_eq!(loaded.get::<String>("name").as_deref(), Some("Alice"));
        // Loaded session starts clean.
        assert!(!loaded.is_dirty());
    }

    #[tokio::test]
    async fn load_unknown_id_returns_none() {
        let store = store();
        assert!(store.load("does-not-exist").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn destroy_removes_session() {
        let store = store();
        let id = store.save(&Session::new()).await.unwrap();
        assert!(store.load(&id).await.unwrap().is_some());
        store.destroy(&id).await.unwrap();
        assert!(store.load(&id).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn touch_extends_ttl_on_existing_session() {
        let store = store();
        let id = store.save(&Session::new()).await.unwrap();
        assert!(store.touch(&id).await.unwrap());
        assert!(store.load(&id).await.unwrap().is_some());
    }

    /// A cache where a logout lands inside every `get` and `touch`.
    struct LogoutMidTouch(InMemoryCache);

    #[async_trait::async_trait]
    impl crate::cache::Cache for LogoutMidTouch {
        async fn get(&self, key: &str) -> Result<Option<String>, CacheError> {
            let v = self.0.get(key).await?;
            self.0.delete(key).await?;
            Ok(v)
        }
        async fn set(&self, k: &str, v: &str, t: Option<Duration>) -> Result<(), CacheError> {
            self.0.set(k, v, t).await
        }
        async fn touch(&self, k: &str, t: Option<Duration>) -> Result<bool, CacheError> {
            self.0.delete(k).await?;
            self.0.touch(k, t).await
        }
        async fn delete(&self, key: &str) -> Result<(), CacheError> {
            self.0.delete(key).await
        }
        async fn exists(&self, key: &str) -> Result<bool, CacheError> {
            self.0.exists(key).await
        }
        async fn clear(&self) -> Result<(), CacheError> {
            self.0.clear().await
        }
    }

    /// #2300 — touch must not write back a session destroyed under it.
    #[tokio::test]
    async fn touch_does_not_revive_a_destroyed_session() {
        let inner = StdArc::new(LogoutMidTouch(InMemoryCache::new()));
        let store = SessionStore::new(inner.clone());
        let id = store.save(&Session::new()).await.unwrap();
        assert!(!store.touch(&id).await.unwrap());
        assert!(store.load(&id).await.unwrap().is_none(), "session revived");
    }

    #[tokio::test]
    async fn touch_returns_false_on_missing_session() {
        let store = store();
        assert!(!store.touch("does-not-exist").await.unwrap());
    }

    #[tokio::test]
    async fn save_with_id_rewrites_existing_session() {
        let store = store();
        let mut s = Session::new();
        s.set("v", 1);
        let id = store.save(&s).await.unwrap();
        // Change it and save under the same id.
        let mut loaded = store.load(&id).await.unwrap().unwrap();
        loaded.set("v", 2);
        store.save_with_id(&id, &loaded).await.unwrap();
        let again = store.load(&id).await.unwrap().unwrap();
        assert_eq!(again.get::<i64>("v"), Some(2));
    }

    #[tokio::test]
    async fn each_save_generates_distinct_id() {
        let store = store();
        let id1 = store.save(&Session::new()).await.unwrap();
        let id2 = store.save(&Session::new()).await.unwrap();
        assert_ne!(id1, id2);
    }

    #[tokio::test]
    async fn corrupted_cache_value_loads_as_none() {
        let store = store();
        // Plant garbage under a session key.
        store
            .cache
            .set(
                "session:corrupt",
                "not-json-{}",
                Some(Duration::from_secs(60)),
            )
            .await
            .unwrap();
        // load() must not panic; it returns None.
        assert!(store.load("corrupt").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn complex_value_roundtrips() {
        let store = store();
        let mut s = Session::new();
        let payload = serde_json::json!({"role": "admin", "perms": ["read", "write"]});
        s.set("ctx", payload.clone());
        let id = store.save(&s).await.unwrap();
        let loaded = store.load(&id).await.unwrap().unwrap();
        assert_eq!(loaded.get::<serde_json::Value>("ctx"), Some(payload));
    }

    #[test]
    fn generated_id_is_url_safe_and_192_bits() {
        let id = generate_id();
        // 24 bytes encoded = ceil(24*4/3) = 32 chars (no padding).
        assert_eq!(id.len(), 32);
        assert!(id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
    }

    #[test]
    fn generated_ids_are_distinct() {
        let a = generate_id();
        let b = generate_id();
        assert_ne!(a, b);
    }
}