seshcookie 0.1.0

Stateless, encrypted, type-safe session cookies for Rust web applications.
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
//! Per-layer session policy: cookie attributes, expiry, and sliding refresh.
//!
//! pattern: Functional Core
//!
//! This module is part of the Functional Core: it defines a plain configuration
//! value with pure builder setters. No I/O, randomness, or wall-clock reads occur
//! here. All `SessionConfig` setters consume `self` and return `Self`, enabling a
//! chained builder style. `SessionConfig::default()` provides safe defaults
//! suitable for production deployments (`Secure`, `HttpOnly`, `SameSite::Lax`,
//! 24h `max_age`).

use std::time::Duration;

/// Re-export of [`cookie::SameSite`]. Stored by [`SessionConfig`] and reflected in the
/// emitted `SameSite` cookie attribute.
///
/// ```
/// use seshcookie::{SameSite, SessionConfig};
///
/// let c = SessionConfig::default().same_site(SameSite::Strict);
/// assert_eq!(c.same_site_ref(), SameSite::Strict);
/// ```
pub use cookie::SameSite;

/// Returns `true` if every byte in `s` is safe for use in a cookie attribute
/// value: visible ASCII (0x20..=0x7E) or horizontal tab (0x09).
///
/// This is stricter than `http::HeaderValue::try_from`, which additionally
/// accepts opaque high-bit bytes (0x80-0xFF). The stricter check is intentional:
/// cookie attribute values are US-ASCII per RFC 6265, so high-bit bytes and
/// DEL (0x7F) are always rejected.
fn is_safe_cookie_attribute_byte(s: &str) -> bool {
    s.bytes().all(|b| b == b'\t' || (0x20..=0x7E).contains(&b))
}

/// Cookie-policy configuration for a [`crate::SessionLayer`].
///
/// Construct a value via [`SessionConfig::default()`] and apply builder setters:
///
/// ```
/// use seshcookie::{SameSite, SessionConfig};
/// use std::time::Duration;
///
/// let config = SessionConfig::default()
///     .cookie_name("my_session")
///     .max_age(Duration::from_secs(60 * 60))
///     .same_site(SameSite::Strict);
/// assert_eq!(config.cookie_name_ref(), "my_session");
/// ```
///
/// # Defaults
///
/// | Field | Default |
/// |---|---|
/// | `cookie_name` | `"session"` |
/// | `path` | `"/"` |
/// | `domain` | `None` (host-scoped) |
/// | `max_age` | 24 hours |
/// | `secure` | `true` |
/// | `http_only` | `true` |
/// | `same_site` | `SameSite::Lax` |
/// | `refresh_after` | `None` (sliding refresh disabled) |
#[derive(Debug, Clone)]
pub struct SessionConfig {
    pub(crate) cookie_name: String,
    pub(crate) path: String,
    pub(crate) domain: Option<String>,
    pub(crate) max_age: Duration,
    pub(crate) secure: bool,
    pub(crate) http_only: bool,
    pub(crate) same_site: SameSite,
    pub(crate) refresh_after: Option<Duration>,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            cookie_name: "session".to_string(),
            path: "/".to_string(),
            domain: None,
            max_age: Duration::from_secs(24 * 60 * 60),
            secure: true,
            http_only: true,
            same_site: SameSite::Lax,
            refresh_after: None,
        }
    }
}

impl SessionConfig {
    /// Set the cookie name. Default: `"session"`.
    ///
    /// # Panics
    ///
    /// Panics if `name` contains any byte outside visible ASCII (0x20-0x7E) or
    /// horizontal tab — i.e., control characters, DEL, high-bit bytes, or NUL.
    /// Cookie names appear verbatim in `Set-Cookie` response headers; catching
    /// invalid bytes here at setup time prevents a panic on every request.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    ///
    /// let c = SessionConfig::default().cookie_name("my_session");
    /// assert_eq!(c.cookie_name_ref(), "my_session");
    /// ```
    #[must_use]
    pub fn cookie_name(mut self, name: impl Into<String>) -> Self {
        let name = name.into();
        assert!(
            is_safe_cookie_attribute_byte(&name),
            "seshcookie: cookie_name must contain only printable ASCII or tab; got {name:?}"
        );
        self.cookie_name = name;
        self
    }

    /// Set the cookie `Path` attribute. Default: `"/"`.
    ///
    /// # Panics
    ///
    /// Panics if `path` contains any byte outside visible ASCII (0x20-0x7E) or
    /// horizontal tab — i.e., control characters, DEL, high-bit bytes, or NUL.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    ///
    /// let c = SessionConfig::default().path("/api");
    /// assert_eq!(c.path_ref(), "/api");
    /// ```
    #[must_use]
    pub fn path(mut self, path: impl Into<String>) -> Self {
        let path = path.into();
        assert!(
            is_safe_cookie_attribute_byte(&path),
            "seshcookie: path must contain only printable ASCII or tab; got {path:?}"
        );
        self.path = path;
        self
    }

    /// Set the cookie `Domain` attribute. Pass a host (e.g., `"example.com"`).
    /// Default: `None` (host-scoped).
    ///
    /// # Panics
    ///
    /// Panics if `domain` contains any byte outside visible ASCII (0x20-0x7E) or
    /// horizontal tab — i.e., control characters, DEL, high-bit bytes, or NUL.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    ///
    /// let c = SessionConfig::default().domain("example.com");
    /// assert_eq!(c.domain_ref(), Some("example.com"));
    /// ```
    #[must_use]
    pub fn domain(mut self, domain: impl Into<String>) -> Self {
        let domain = domain.into();
        assert!(
            is_safe_cookie_attribute_byte(&domain),
            "seshcookie: domain must contain only printable ASCII or tab; got {domain:?}"
        );
        self.domain = Some(domain);
        self
    }

    /// Clear the cookie `Domain` attribute - emit a host-scoped cookie.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    ///
    /// let c = SessionConfig::default().domain("example.com").no_domain();
    /// assert!(c.domain_ref().is_none());
    /// ```
    #[must_use]
    pub fn no_domain(mut self) -> Self {
        self.domain = None;
        self
    }

    /// Set the server-side session maximum age. Cookies older than this (by
    /// authenticated `issued_at`) are rejected and a cookie-delete is emitted.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    /// use std::time::Duration;
    ///
    /// let c = SessionConfig::default().max_age(Duration::from_secs(60 * 60));
    /// assert_eq!(c.max_age_ref(), Duration::from_secs(60 * 60));
    /// ```
    #[must_use]
    pub fn max_age(mut self, max_age: Duration) -> Self {
        self.max_age = max_age;
        self
    }

    /// Set the cookie `Secure` attribute (default `true`). Set to `false` only
    /// for local development over plain HTTP.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    ///
    /// let c = SessionConfig::default().secure(false);
    /// assert!(!c.is_secure());
    /// ```
    #[must_use]
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self
    }

    /// Set the cookie `HttpOnly` attribute. Default: `true`.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    ///
    /// let c = SessionConfig::default().http_only(false);
    /// assert!(!c.is_http_only());
    /// ```
    #[must_use]
    pub fn http_only(mut self, http_only: bool) -> Self {
        self.http_only = http_only;
        self
    }

    /// Set the cookie `SameSite` attribute. Default: `SameSite::Lax`.
    ///
    /// ```
    /// use seshcookie::{SameSite, SessionConfig};
    ///
    /// let c = SessionConfig::default().same_site(SameSite::Strict);
    /// assert_eq!(c.same_site_ref(), SameSite::Strict);
    /// ```
    #[must_use]
    pub fn same_site(mut self, same_site: SameSite) -> Self {
        self.same_site = same_site;
        self
    }

    /// Enable or disable sliding refresh. `Some(d)` rewrites the cookie with a
    /// bumped `issued_at` once the session is older than `d` (but still within
    /// `max_age`). `None` disables sliding refresh - the default.
    ///
    /// ```
    /// use seshcookie::SessionConfig;
    /// use std::time::Duration;
    ///
    /// let c = SessionConfig::default().refresh_after(Some(Duration::from_secs(60 * 60)));
    /// assert_eq!(c.refresh_after_ref(), Some(Duration::from_secs(60 * 60)));
    /// ```
    #[must_use]
    pub fn refresh_after(mut self, refresh_after: Option<Duration>) -> Self {
        self.refresh_after = refresh_after;
        self
    }

    // Getters - public, read-only accessors. Useful for downstream apps that
    // need to reflect the effective config (e.g., build a CSRF cookie matching
    // the path/domain). All getters use the `_ref` suffix (or `is_` prefix for
    // booleans) for naming uniformity, since the bare names are claimed by the
    // builder setters above.

    /// Current cookie name.
    pub fn cookie_name_ref(&self) -> &str {
        &self.cookie_name
    }

    /// Current cookie path.
    pub fn path_ref(&self) -> &str {
        &self.path
    }

    /// Current cookie domain, if set.
    pub fn domain_ref(&self) -> Option<&str> {
        self.domain.as_deref()
    }

    /// Current server-side max-age.
    pub fn max_age_ref(&self) -> Duration {
        self.max_age
    }

    /// Current `Secure` flag.
    pub fn is_secure(&self) -> bool {
        self.secure
    }

    /// Current `HttpOnly` flag.
    pub fn is_http_only(&self) -> bool {
        self.http_only
    }

    /// Current `SameSite` attribute.
    pub fn same_site_ref(&self) -> SameSite {
        self.same_site
    }

    /// Current sliding refresh threshold, if set.
    pub fn refresh_after_ref(&self) -> Option<Duration> {
        self.refresh_after
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- seshcookie-rs.AC7.1: defaults ---------------------------------------------

    /// seshcookie-rs.AC7.1: every field of `SessionConfig::default()` matches the
    /// documented default. Asserting each field individually so a single regression
    /// localizes precisely.
    #[test]
    fn default_cookie_name_is_session_ac7_1() {
        let c = SessionConfig::default();
        assert_eq!(c.cookie_name_ref(), "session");
    }

    /// seshcookie-rs.AC7.1: default `path` is `"/"`.
    #[test]
    fn default_path_is_root_ac7_1() {
        let c = SessionConfig::default();
        assert_eq!(c.path_ref(), "/");
    }

    /// seshcookie-rs.AC7.1: default `domain` is `None` (host-scoped).
    #[test]
    fn default_domain_is_none_ac7_1() {
        let c = SessionConfig::default();
        assert_eq!(c.domain_ref(), None);
    }

    /// seshcookie-rs.AC7.1: default `max_age` is exactly 24 hours.
    #[test]
    fn default_max_age_is_24h_ac7_1() {
        let c = SessionConfig::default();
        assert_eq!(c.max_age_ref(), Duration::from_secs(24 * 60 * 60));
    }

    /// seshcookie-rs.AC7.1: default `secure` is `true`.
    #[test]
    fn default_secure_is_true_ac7_1() {
        let c = SessionConfig::default();
        assert!(c.is_secure());
    }

    /// seshcookie-rs.AC7.1: default `http_only` is `true`.
    #[test]
    fn default_http_only_is_true_ac7_1() {
        let c = SessionConfig::default();
        assert!(c.is_http_only());
    }

    /// seshcookie-rs.AC7.1: default `same_site` is `SameSite::Lax`.
    #[test]
    fn default_same_site_is_lax_ac7_1() {
        let c = SessionConfig::default();
        assert_eq!(c.same_site_ref(), SameSite::Lax);
    }

    /// seshcookie-rs.AC7.1: default `refresh_after` is `None` (sliding refresh
    /// disabled).
    #[test]
    fn default_refresh_after_is_none_ac7_1() {
        let c = SessionConfig::default();
        assert_eq!(c.refresh_after_ref(), None);
    }

    // --- seshcookie-rs.AC7.2: setters return Self and update fields ----------------

    /// seshcookie-rs.AC7.2: every setter accepts a value, returns `Self`, and the
    /// new value is reflected by its `_ref`/`is_*` getter. The chained-builder
    /// expression below would not compile if any setter failed to return `Self`,
    /// so the type-system check is the heart of this test; the per-field
    /// assertions confirm each setter wrote the value it received.
    #[test]
    fn builder_chain_sets_every_field_and_returns_self_ac7_2() {
        let c = SessionConfig::default()
            .cookie_name("s")
            .path("/api")
            .domain("x.test")
            .max_age(Duration::from_secs(60))
            .secure(false)
            .http_only(false)
            .same_site(SameSite::Strict)
            .refresh_after(Some(Duration::from_secs(30)));

        assert_eq!(c.cookie_name_ref(), "s");
        assert_eq!(c.path_ref(), "/api");
        assert_eq!(c.domain_ref(), Some("x.test"));
        assert_eq!(c.max_age_ref(), Duration::from_secs(60));
        assert!(!c.is_secure());
        assert!(!c.is_http_only());
        assert_eq!(c.same_site_ref(), SameSite::Strict);
        assert_eq!(c.refresh_after_ref(), Some(Duration::from_secs(30)));
    }

    /// seshcookie-rs.AC7.2: `cookie_name` accepts both `&str` and `String` via
    /// `Into<String>`.
    #[test]
    fn cookie_name_accepts_str_and_string_ac7_2() {
        let c1 = SessionConfig::default().cookie_name("from-str");
        assert_eq!(c1.cookie_name_ref(), "from-str");

        let c2 = SessionConfig::default().cookie_name(String::from("from-string"));
        assert_eq!(c2.cookie_name_ref(), "from-string");
    }

    /// seshcookie-rs.AC7.2: `path` accepts both `&str` and `String` via
    /// `Into<String>`.
    #[test]
    fn path_accepts_str_and_string_ac7_2() {
        let c1 = SessionConfig::default().path("/from-str");
        assert_eq!(c1.path_ref(), "/from-str");

        let c2 = SessionConfig::default().path(String::from("/from-string"));
        assert_eq!(c2.path_ref(), "/from-string");
    }

    /// seshcookie-rs.AC7.2: `domain` accepts both `&str` and `String` via
    /// `Into<String>`.
    #[test]
    fn domain_accepts_str_and_string_ac7_2() {
        let c1 = SessionConfig::default().domain("a.test");
        assert_eq!(c1.domain_ref(), Some("a.test"));

        let c2 = SessionConfig::default().domain(String::from("b.test"));
        assert_eq!(c2.domain_ref(), Some("b.test"));
    }

    /// seshcookie-rs.AC7.2: `refresh_after(None)` re-disables sliding refresh
    /// after it had been enabled.
    #[test]
    fn refresh_after_can_be_disabled_after_being_enabled_ac7_2() {
        let c = SessionConfig::default()
            .refresh_after(Some(Duration::from_secs(60)))
            .refresh_after(None);
        assert_eq!(c.refresh_after_ref(), None);
    }

    // --- no_domain clears a previously-set domain ----------------------------------

    /// `no_domain()` clears a previously set domain so the cookie becomes
    /// host-scoped.
    #[test]
    fn no_domain_clears_previously_set_domain() {
        let c = SessionConfig::default().domain("a.test").no_domain();
        assert_eq!(c.domain_ref(), None);
    }

    /// `no_domain()` is a no-op when no domain was set.
    #[test]
    fn no_domain_is_noop_when_already_none() {
        let c = SessionConfig::default().no_domain();
        assert_eq!(c.domain_ref(), None);
    }

    // --- setter validation (panic on control chars) --------------------------------

    /// `cookie_name` rejects a newline injection attempt. The panic protects
    /// the response path's `HeaderValue::try_from` from a guaranteed panic on
    /// every request.
    #[test]
    #[should_panic(expected = "seshcookie: cookie_name must contain only printable ASCII or tab")]
    fn cookie_name_with_newline_panics() {
        let _ = SessionConfig::default().cookie_name("bad\nname");
    }

    /// `cookie_name` rejects a NUL byte.
    #[test]
    #[should_panic(expected = "seshcookie: cookie_name must contain only printable ASCII or tab")]
    fn cookie_name_with_nul_panics() {
        let _ = SessionConfig::default().cookie_name("bad\x00name");
    }

    /// `path` rejects a CR/LF header-injection attempt. An attacker-controlled
    /// `path` containing `\r\n` would let them inject arbitrary response
    /// headers.
    #[test]
    #[should_panic(expected = "seshcookie: path must contain only printable ASCII or tab")]
    fn path_with_crlf_panics() {
        let _ = SessionConfig::default().path("/api\r\nattacker=evil");
    }

    /// `path` rejects a plain newline.
    #[test]
    #[should_panic(expected = "seshcookie: path must contain only printable ASCII or tab")]
    fn path_with_newline_panics() {
        let _ = SessionConfig::default().path("/api\nattacker=evil");
    }

    /// `domain` rejects a newline injection attempt.
    #[test]
    #[should_panic(expected = "seshcookie: domain must contain only printable ASCII or tab")]
    fn domain_with_newline_panics() {
        let _ = SessionConfig::default().domain("evil\ndomain");
    }

    // --- Derived traits ------------------------------------------------------------

    /// `SessionConfig` is `Clone` and `Debug`. The struct stores no resources, so
    /// `Clone` produces an independent value with identical field contents.
    #[test]
    fn config_is_clone_and_debug() {
        let original = SessionConfig::default()
            .cookie_name("orig")
            .domain("a.test");
        let cloned = original.clone();
        assert_eq!(cloned.cookie_name_ref(), "orig");
        assert_eq!(cloned.domain_ref(), Some("a.test"));

        // Independence: mutating the clone via the consuming builder does not
        // affect the original.
        let mutated = cloned.cookie_name("mutated");
        assert_eq!(mutated.cookie_name_ref(), "mutated");
        assert_eq!(original.cookie_name_ref(), "orig");

        // Debug formatting succeeds and mentions a known field name.
        let dbg = format!("{original:?}");
        assert!(dbg.contains("cookie_name"));
    }
}