Skip to main content

serenade_session/
cookie.rs

1//! Cookie-backed session id + [`SessionStore`](crate::SessionStore) lifecycle.
2
3use std::sync::Arc;
4
5use crate::{Session, SessionError, SessionStore};
6
7/// Default session cookie name.
8pub const DEFAULT_SESSION_COOKIE: &str = "SERENADE_SESSION";
9
10/// Options for the session id cookie written on commit.
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct CookieSessionOptions {
13    name: String,
14    path: String,
15    http_only: bool,
16    secure: bool,
17    same_site: SameSite,
18    max_age_secs: Option<u64>,
19}
20
21impl Default for CookieSessionOptions {
22    fn default() -> Self {
23        Self {
24            name: DEFAULT_SESSION_COOKIE.to_owned(),
25            path: "/".to_owned(),
26            http_only: true,
27            secure: false,
28            same_site: SameSite::Lax,
29            max_age_secs: None,
30        }
31    }
32}
33
34impl CookieSessionOptions {
35    /// Cookie name (default [`DEFAULT_SESSION_COOKIE`]).
36    #[must_use]
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// Sets the cookie name.
42    #[must_use]
43    pub fn with_name(mut self, name: impl Into<String>) -> Self {
44        self.name = name.into();
45        self
46    }
47
48    /// Sets the cookie path.
49    #[must_use]
50    pub fn with_path(mut self, path: impl Into<String>) -> Self {
51        self.path = path.into();
52        self
53    }
54
55    /// Sets the `HttpOnly` flag.
56    #[must_use]
57    pub const fn with_http_only(mut self, http_only: bool) -> Self {
58        self.http_only = http_only;
59        self
60    }
61
62    /// Sets the `Secure` flag.
63    #[must_use]
64    pub const fn with_secure(mut self, secure: bool) -> Self {
65        self.secure = secure;
66        self
67    }
68
69    /// Sets `SameSite`.
70    #[must_use]
71    pub const fn with_same_site(mut self, same_site: SameSite) -> Self {
72        self.same_site = same_site;
73        self
74    }
75
76    /// Sets `Max-Age` in seconds (`None` = session cookie).
77    #[must_use]
78    pub const fn with_max_age_secs(mut self, max_age_secs: Option<u64>) -> Self {
79        self.max_age_secs = max_age_secs;
80        self
81    }
82
83    /// Cookie name.
84    #[must_use]
85    pub fn name(&self) -> &str {
86        &self.name
87    }
88}
89
90/// `SameSite` attribute for the session cookie.
91#[derive(Clone, Copy, Debug, Eq, PartialEq)]
92pub enum SameSite {
93    /// `SameSite=Lax`.
94    Lax,
95    /// `SameSite=Strict`.
96    Strict,
97    /// `SameSite=None` (requires `Secure` in browsers).
98    None,
99}
100
101impl SameSite {
102    const fn as_str(self) -> &'static str {
103        match self {
104            Self::Lax => "Lax",
105            Self::Strict => "Strict",
106            Self::None => "None",
107        }
108    }
109}
110
111/// Opens and commits sessions using a store plus a session-id cookie.
112#[derive(Clone)]
113pub struct CookieSession {
114    store: Arc<dyn SessionStore>,
115    options: CookieSessionOptions,
116}
117
118impl CookieSession {
119    /// Binds `store` with default cookie options.
120    #[must_use]
121    pub fn new(store: Arc<dyn SessionStore>) -> Self {
122        Self {
123            store,
124            options: CookieSessionOptions::default(),
125        }
126    }
127
128    /// Binds `store` with custom cookie options.
129    #[must_use]
130    pub fn with_options(store: Arc<dyn SessionStore>, options: CookieSessionOptions) -> Self {
131        Self { store, options }
132    }
133
134    /// Cookie options.
135    #[must_use]
136    pub const fn options(&self) -> &CookieSessionOptions {
137        &self.options
138    }
139
140    /// Loads or creates a session from an optional raw `Cookie` request header.
141    ///
142    /// # Errors
143    ///
144    /// Returns [`SessionError`] when id generation or the store fails.
145    pub fn open(&self, cookie_header: Option<&str>) -> Result<Session, SessionError> {
146        if let Some(id) =
147            cookie_header.and_then(|header| parse_cookie_value(header, self.options.name()))
148            && let Some(attributes) = self.store.load(&id)?
149        {
150            return Ok(Session::existing(id, attributes));
151        }
152        // Unknown id: start a fresh bag under a new id (avoids fixation on stale cookies).
153
154        Ok(Session::new(generate_session_id()?))
155    }
156
157    /// Persists `session` and returns a `Set-Cookie` header value when needed.
158    ///
159    /// Returns `None` when the session was neither new, dirty, nor invalidated.
160    ///
161    /// # Errors
162    ///
163    /// Returns [`SessionError`] when the store fails.
164    pub fn commit(&self, session: &Session) -> Result<Option<String>, SessionError> {
165        if session.is_invalidated() {
166            self.store.delete(session.id())?;
167            return Ok(Some(format_set_cookie(
168                &self.options,
169                session.id(),
170                ClearCookie::Yes,
171            )));
172        }
173        if !session.is_dirty() {
174            return Ok(None);
175        }
176        self.store.save(session.id(), &session.take_for_save())?;
177        Ok(Some(format_set_cookie(
178            &self.options,
179            session.id(),
180            ClearCookie::No,
181        )))
182    }
183}
184
185#[derive(Clone, Copy)]
186enum ClearCookie {
187    Yes,
188    No,
189}
190
191/// Generates a new opaque session id (32 random bytes, hex-encoded).
192///
193/// # Errors
194///
195/// Returns [`SessionError::Generation`] when the RNG fails.
196pub fn generate_session_id() -> Result<String, SessionError> {
197    let mut bytes = [0_u8; 32];
198    getrandom::fill(&mut bytes).map_err(|_| SessionError::Generation)?;
199    Ok(hex_encode(&bytes))
200}
201
202/// Reads `name` from a raw `Cookie` header (`a=1; b=2`).
203#[must_use]
204pub fn parse_cookie_value(cookie_header: &str, name: &str) -> Option<String> {
205    for part in cookie_header.split(';') {
206        let part = part.trim();
207        let Some((key, value)) = part.split_once('=') else {
208            continue;
209        };
210        if key.trim() == name {
211            return Some(value.trim().to_owned());
212        }
213    }
214    None
215}
216
217fn format_set_cookie(options: &CookieSessionOptions, id: &str, clear: ClearCookie) -> String {
218    let mut out = format!("{}={}", options.name, id);
219    out.push_str("; Path=");
220    out.push_str(&options.path);
221    match clear {
222        ClearCookie::Yes => out.push_str("; Max-Age=0"),
223        ClearCookie::No => {
224            if let Some(max_age) = options.max_age_secs {
225                out.push_str("; Max-Age=");
226                out.push_str(&max_age.to_string());
227            }
228        }
229    }
230    if options.http_only {
231        out.push_str("; HttpOnly");
232    }
233    if options.secure {
234        out.push_str("; Secure");
235    }
236    out.push_str("; SameSite=");
237    out.push_str(options.same_site.as_str());
238    out
239}
240
241fn hex_encode(bytes: &[u8]) -> String {
242    const HEX: &[u8; 16] = b"0123456789abcdef";
243    let mut out = String::with_capacity(bytes.len() * 2);
244    for byte in bytes {
245        out.push(HEX[usize::from(byte >> 4)] as char);
246        out.push(HEX[usize::from(byte & 0x0f)] as char);
247    }
248    out
249}