Skip to main content

next_rust_server/
cookies.rs

1//! Cookies with secure defaults.
2
3use std::sync::{Arc, Mutex};
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use http::HeaderMap;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum SameSite {
10    Strict,
11    Lax,
12    None,
13}
14
15impl SameSite {
16    fn as_str(self) -> &'static str {
17        match self {
18            SameSite::Strict => "Strict",
19            SameSite::Lax => "Lax",
20            SameSite::None => "None",
21        }
22    }
23}
24
25/// A cookie to set.
26///
27/// Unless configured explicitly, cookies set through [`Cookies::set`] get
28/// `Path=/`, `HttpOnly`, `SameSite=Lax`, and `Secure` outside development.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Cookie {
31    pub name: String,
32    pub value: String,
33    pub path: Option<String>,
34    pub domain: Option<String>,
35    pub max_age: Option<Duration>,
36    pub expires: Option<SystemTime>,
37    pub http_only: Option<bool>,
38    pub secure: Option<bool>,
39    pub same_site: Option<SameSite>,
40    pub partitioned: bool,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum CookieError {
45    InvalidName(String),
46    InvalidValue(String),
47    InvalidAttribute(String),
48}
49
50impl std::fmt::Display for CookieError {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        match self {
53            CookieError::InvalidName(n) => write!(f, "invalid cookie name {n:?}"),
54            CookieError::InvalidValue(n) => {
55                write!(f, "invalid value for cookie {n:?}; use Cookie::encoded for arbitrary text")
56            }
57            CookieError::InvalidAttribute(a) => write!(f, "invalid cookie attribute {a:?}"),
58        }
59    }
60}
61
62impl std::error::Error for CookieError {}
63
64fn is_token(s: &str) -> bool {
65    !s.is_empty() && s.bytes().all(|b| b.is_ascii_graphic() && !b"()<>@,;:\\\"/[]?={}".contains(&b))
66}
67
68fn is_cookie_value(s: &str) -> bool {
69    s.bytes().all(|b| {
70        b == 0x21
71            || (0x23..=0x2B).contains(&b)
72            || (0x2D..=0x3A).contains(&b)
73            || (0x3C..=0x5B).contains(&b)
74            || (0x5D..=0x7E).contains(&b)
75    })
76}
77
78fn is_attr_value(s: &str) -> bool {
79    s.bytes().all(|b| (0x20..0x7F).contains(&b) && b != b';')
80}
81
82impl Cookie {
83    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
84        Cookie {
85            name: name.into(),
86            value: value.into(),
87            path: None,
88            domain: None,
89            max_age: None,
90            expires: None,
91            http_only: None,
92            secure: None,
93            same_site: None,
94            partitioned: false,
95        }
96    }
97
98    /// Percent-encode `value` so it may contain any text. Read it back with
99    /// [`Cookies::get_decoded`].
100    pub fn encoded(name: impl Into<String>, value: &str) -> Self {
101        Cookie::new(name, percent_encode(value))
102    }
103
104    pub fn path(mut self, v: impl Into<String>) -> Self {
105        self.path = Some(v.into());
106        self
107    }
108    pub fn domain(mut self, v: impl Into<String>) -> Self {
109        self.domain = Some(v.into());
110        self
111    }
112    pub fn max_age(mut self, v: Duration) -> Self {
113        self.max_age = Some(v);
114        self
115    }
116    pub fn expires(mut self, v: SystemTime) -> Self {
117        self.expires = Some(v);
118        self
119    }
120    pub fn http_only(mut self, v: bool) -> Self {
121        self.http_only = Some(v);
122        self
123    }
124    pub fn secure(mut self, v: bool) -> Self {
125        self.secure = Some(v);
126        self
127    }
128    pub fn same_site(mut self, v: SameSite) -> Self {
129        self.same_site = Some(v);
130        self
131    }
132    pub fn partitioned(mut self, v: bool) -> Self {
133        self.partitioned = v;
134        self
135    }
136
137    /// Serialize as a `Set-Cookie` header value.
138    pub fn to_header_value(&self) -> Result<String, CookieError> {
139        if !is_token(&self.name) {
140            return Err(CookieError::InvalidName(self.name.clone()));
141        }
142        if !is_cookie_value(&self.value) {
143            return Err(CookieError::InvalidValue(self.name.clone()));
144        }
145        let mut s = format!("{}={}", self.name, self.value);
146        if let Some(p) = &self.path {
147            if !is_attr_value(p) {
148                return Err(CookieError::InvalidAttribute(p.clone()));
149            }
150            s.push_str("; Path=");
151            s.push_str(p);
152        }
153        if let Some(d) = &self.domain {
154            if !is_attr_value(d) {
155                return Err(CookieError::InvalidAttribute(d.clone()));
156            }
157            s.push_str("; Domain=");
158            s.push_str(d);
159        }
160        if let Some(m) = self.max_age {
161            s.push_str(&format!("; Max-Age={}", m.as_secs()));
162        }
163        if let Some(e) = self.expires {
164            s.push_str("; Expires=");
165            s.push_str(&crate::http_date::format(e));
166        }
167        if self.http_only == Some(true) {
168            s.push_str("; HttpOnly");
169        }
170        // SameSite=None requires Secure.
171        if self.secure == Some(true) || self.same_site == Some(SameSite::None) {
172            s.push_str("; Secure");
173        }
174        if let Some(ss) = self.same_site {
175            s.push_str("; SameSite=");
176            s.push_str(ss.as_str());
177        }
178        if self.partitioned {
179            s.push_str("; Partitioned");
180        }
181        Ok(s)
182    }
183}
184
185#[derive(Debug, Default)]
186struct JarInner {
187    incoming: Vec<(String, String)>,
188    changes: Vec<Cookie>,
189}
190
191/// Request cookies plus pending changes, shared between the request, the
192/// render context and the response.
193#[derive(Debug, Clone, Default)]
194pub struct Cookies {
195    inner: Arc<Mutex<JarInner>>,
196    secure_default: bool,
197}
198
199impl Cookies {
200    pub fn from_headers(headers: &HeaderMap, secure_default: bool) -> Self {
201        let mut incoming = Vec::new();
202        for value in headers.get_all(http::header::COOKIE) {
203            let Ok(s) = value.to_str() else { continue };
204            for pair in s.split(';') {
205                if let Some((k, v)) = pair.split_once('=') {
206                    let v = v.trim();
207                    let v = v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v);
208                    incoming.push((k.trim().to_owned(), v.to_owned()));
209                }
210            }
211        }
212        Cookies { inner: Arc::new(Mutex::new(JarInner { incoming, changes: Vec::new() })), secure_default }
213    }
214
215    fn lock(&self) -> std::sync::MutexGuard<'_, JarInner> {
216        self.inner.lock().unwrap_or_else(|e| e.into_inner())
217    }
218
219    /// Current value, reflecting changes made during this request.
220    pub fn get(&self, name: &str) -> Option<String> {
221        let inner = self.lock();
222        if let Some(c) = inner.changes.iter().rev().find(|c| c.name == name) {
223            let deleted = c.max_age == Some(Duration::ZERO);
224            return if deleted { None } else { Some(c.value.clone()) };
225        }
226        inner.incoming.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone())
227    }
228
229    /// Value decoded with percent-decoding (see [`Cookie::encoded`]).
230    pub fn get_decoded(&self, name: &str) -> Option<String> {
231        self.get(name).map(|v| percent_decode(&v))
232    }
233
234    pub fn all(&self) -> Vec<(String, String)> {
235        self.lock().incoming.clone()
236    }
237
238    /// Set a cookie (secure defaults are applied to unset attributes).
239    pub fn set(&self, mut cookie: Cookie) {
240        cookie.path.get_or_insert_with(|| "/".into());
241        cookie.http_only.get_or_insert(true);
242        cookie.same_site.get_or_insert(SameSite::Lax);
243        cookie.secure.get_or_insert(self.secure_default);
244        self.lock().changes.push(cookie);
245    }
246
247    /// Delete a cookie (on path `/`).
248    pub fn delete(&self, name: &str) {
249        self.delete_with_path(name, "/");
250    }
251
252    pub fn delete_with_path(&self, name: &str, path: &str) {
253        let cookie = Cookie::new(name, "")
254            .path(path)
255            .max_age(Duration::ZERO)
256            .expires(UNIX_EPOCH)
257            .http_only(true)
258            .secure(self.secure_default)
259            .same_site(SameSite::Lax);
260        self.lock().changes.push(cookie);
261    }
262
263    /// `Set-Cookie` header values for all changes (invalid cookies are
264    /// skipped and reported).
265    pub fn set_cookie_headers(&self) -> Vec<String> {
266        let inner = self.lock();
267        let mut out = Vec::new();
268        for c in &inner.changes {
269            match c.to_header_value() {
270                Ok(v) => out.push(v),
271                Err(e) => crate::log::warn(&format!("cookie not sent: {e}")),
272            }
273        }
274        out
275    }
276
277    pub fn has_changes(&self) -> bool {
278        !self.lock().changes.is_empty()
279    }
280}
281
282pub(crate) fn percent_encode(s: &str) -> String {
283    let mut out = String::with_capacity(s.len());
284    for b in s.bytes() {
285        if b.is_ascii_alphanumeric() || b"-._~!$&'()*+:@/?".contains(&b) {
286            out.push(b as char);
287        } else {
288            out.push_str(&format!("%{b:02X}"));
289        }
290    }
291    out
292}
293
294pub(crate) fn percent_decode(s: &str) -> String {
295    let bytes = s.as_bytes();
296    let mut out = Vec::with_capacity(bytes.len());
297    let mut i = 0;
298    while i < bytes.len() {
299        if bytes[i] == b'%'
300            && i + 2 < bytes.len()
301            && let Some(b) = std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok())
302        {
303            out.push(b);
304            i += 3;
305            continue;
306        }
307        out.push(bytes[i]);
308        i += 1;
309    }
310    String::from_utf8_lossy(&out).into_owned()
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn serializes_with_attributes() {
319        let c = Cookie::new("sid", "abc")
320            .path("/")
321            .domain("example.com")
322            .max_age(Duration::from_secs(60))
323            .http_only(true)
324            .secure(true)
325            .same_site(SameSite::Strict);
326        assert_eq!(
327            c.to_header_value().unwrap(),
328            "sid=abc; Path=/; Domain=example.com; Max-Age=60; HttpOnly; Secure; SameSite=Strict"
329        );
330        assert!(Cookie::new("a b", "x").to_header_value().is_err());
331        assert!(Cookie::new("a", "x;y").to_header_value().is_err());
332        assert!(Cookie::new("a", "x\r\nSet-Cookie: evil=1").to_header_value().is_err());
333        assert!(Cookie::new("a", "x").path("/;x").to_header_value().is_err());
334        assert_eq!(
335            Cookie::new("a", "").same_site(SameSite::None).to_header_value().unwrap(),
336            "a=; Secure; SameSite=None"
337        );
338    }
339
340    #[test]
341    fn jar_defaults_and_changes() {
342        let mut headers = HeaderMap::new();
343        headers.insert(http::header::COOKIE, "theme=dark; sid=\"123\"".parse().unwrap());
344        let jar = Cookies::from_headers(&headers, true);
345        assert_eq!(jar.get("theme").as_deref(), Some("dark"));
346        assert_eq!(jar.get("sid").as_deref(), Some("123"));
347        jar.set(Cookie::new("theme", "light"));
348        assert_eq!(jar.get("theme").as_deref(), Some("light"));
349        jar.delete("sid");
350        assert_eq!(jar.get("sid"), None);
351        let h = jar.set_cookie_headers();
352        assert_eq!(h[0], "theme=light; Path=/; HttpOnly; Secure; SameSite=Lax");
353        assert!(h[1].starts_with("sid=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly"));
354    }
355
356    #[test]
357    fn encoded_values_roundtrip() {
358        let c = Cookie::encoded("data", "{\"a\": \"b c;\"}");
359        assert!(c.to_header_value().is_ok());
360        let mut headers = HeaderMap::new();
361        headers.insert(http::header::COOKIE, format!("data={}", c.value).parse().unwrap());
362        let jar = Cookies::from_headers(&headers, false);
363        assert_eq!(jar.get_decoded("data").as_deref(), Some("{\"a\": \"b c;\"}"));
364    }
365}