Skip to main content

nitr_std/http/
cookies.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Request/response cookies: parsing, the `Set-Cookie` builder, the
7//! server-resolved `Secure` default, and HMAC-SHA256 signed variants.
8
9use std::sync::Mutex;
10
11use base64::Engine as _;
12use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
13use hmac::{Hmac, Mac as _};
14use mlua::{Lua, MetaMethod, Table, UserData, UserDataMethods, Value};
15use sha2::Sha256;
16
17type HmacSha256 = Hmac<Sha256>;
18
19/// Cookies parsed from a request's `Cookie` header: values via indexing
20/// (`req.cookies.session`) and signed-cookie verification via
21/// `req.cookies:verify(name, secret)`.
22pub struct RequestCookies(Vec<(String, String)>);
23
24impl RequestCookies {
25    /// Parses a `Cookie` request header (an empty string yields no cookies).
26    pub fn parse(header: &str) -> Self {
27        Self(
28            cookie::Cookie::split_parse(header)
29                .flatten()
30                .map(|c| (c.name().to_string(), c.value().to_string()))
31                .collect(),
32        )
33    }
34
35    /// The parsed (name, value) pairs, in header order, for the
36    /// `cookie_header` fuzz target — the parse result is otherwise only
37    /// observable through Lua indexing.
38    #[doc(hidden)]
39    pub fn pairs(&self) -> &[(String, String)] {
40        &self.0
41    }
42
43    pub(crate) fn get(&self, name: &str) -> Option<&str> {
44        self.0
45            .iter()
46            .find(|(n, _)| n == name)
47            .map(|(_, v)| v.as_str())
48    }
49}
50
51impl UserData for RequestCookies {
52    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
53        methods.add_meta_method(MetaMethod::Index, |lua, this, name: Value| {
54            let Value::String(name) = name else {
55                return Ok(Value::Nil);
56            };
57            match this.get(&name.to_string_lossy()) {
58                Some(v) => Ok(Value::String(lua.create_string(v)?)),
59                None => Ok(Value::Nil),
60            }
61        });
62
63        // Returns the verified value of a signed cookie, or nil when the
64        // cookie is missing, malformed, or its signature does not match.
65        methods.add_method(
66            "verify",
67            |lua, this, (name, secret): (String, String)| match this
68                .get(&name)
69                .and_then(|raw| verify(&name, raw, &secret))
70            {
71                Some(v) => Ok(Value::String(lua.create_string(v)?)),
72                None => Ok(Value::Nil),
73            },
74        );
75    }
76}
77
78/// Builder for response `Set-Cookie` headers, attached as the `cookies`
79/// field of helper-built response tables. The server serializes each entry
80/// into its own `Set-Cookie` header.
81#[derive(Default)]
82pub struct ResponseCookies(Mutex<Vec<String>>);
83
84impl ResponseCookies {
85    /// The serialized `Set-Cookie` values collected so far.
86    pub fn values(&self) -> Vec<String> {
87        self.0.lock().map(|v| v.clone()).unwrap_or_default()
88    }
89
90    fn push(&self, value: String) -> mlua::Result<()> {
91        self.0
92            .lock()
93            .map_err(|_| mlua::Error::RuntimeError("the cookie list lock is poisoned".into()))?
94            .push(value);
95        Ok(())
96    }
97}
98
99impl UserData for ResponseCookies {
100    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
101        methods.add_method(
102            "set",
103            |lua, this, (name, value, opts): (String, String, Option<Table>)| {
104                this.push(build_cookie(lua, &name, &value, opts.as_ref())?)
105            },
106        );
107
108        // Signs the value with HMAC-SHA256 so `req.cookies:verify(name,
109        // secret)` can authenticate it on later requests.
110        methods.add_method(
111            "set_signed",
112            |lua, this, (name, value, secret, opts): (String, String, String, Option<Table>)| {
113                this.push(build_cookie(
114                    lua,
115                    &name,
116                    &sign(&name, &value, &secret),
117                    opts.as_ref(),
118                )?)
119            },
120        );
121    }
122}
123
124/// Attaches a serialized `Set-Cookie` value to a handler response table:
125/// through its `cookies` builder when present (helper-built responses), or
126/// by creating one (hand-built plain tables), so the server's response
127/// conversion picks it up either way.
128pub(crate) fn attach_cookie(resp: &Table, cookie: String) -> mlua::Result<()> {
129    match resp.raw_get::<Value>("cookies")? {
130        Value::UserData(ud) => {
131            let cookies = ud.borrow::<ResponseCookies>().map_err(|_| {
132                mlua::Error::RuntimeError(
133                    "the response `cookies` field is not a cookie builder".into(),
134                )
135            })?;
136            cookies.push(cookie)
137        }
138        Value::Nil => {
139            let cookies = ResponseCookies::default();
140            cookies.push(cookie)?;
141            resp.set("cookies", cookies)
142        }
143        other => Err(mlua::Error::RuntimeError(format!(
144            "invalid `cookies` field of type `{}` in the response table",
145            other.type_name()
146        ))),
147    }
148}
149
150/// The per-state cookie policy, stashed by `register_builtins` and read
151/// by [`build_cookie`].
152///
153/// App data rather than a captured value because [`build_cookie`] is
154/// reached from `UserData` methods, whose closures are registered once per
155/// *type* and so cannot capture per-server state — the alternative would
156/// be threading the flag into every `ResponseCookies` construction site.
157/// Absent means not secure, matching `BuiltinsEnv`'s derived `Default`, so
158/// an embedder who never sets one keeps today's behaviour.
159#[derive(Debug, Clone, Default)]
160pub struct CookieDefaults {
161    /// Whether cookies carry `Secure` when the caller's options do not say.
162    pub secure: bool,
163    /// Why a cookie built without `Secure` deserves a warning, when the
164    /// server could not tell whether a proxy terminates TLS in front of
165    /// it. Logged once per process, the first time such a cookie is
166    /// built: a service that never sets one is never told about them.
167    pub insecure_warning: Option<String>,
168}
169
170/// The resolved `Secure` default for this state; `false` when nothing
171/// registered one.
172fn secure_default(lua: &Lua) -> bool {
173    lua.app_data_ref::<CookieDefaults>()
174        .is_some_and(|defaults| defaults.secure)
175}
176
177/// Logs the configured warning the first time a cookie ships without
178/// `Secure` by default; reports whether this call was the one to log it.
179fn warn_insecure_once(lua: &Lua) -> bool {
180    static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
181    let Some(why) = lua
182        .app_data_ref::<CookieDefaults>()
183        .and_then(|defaults| defaults.insecure_warning.clone())
184    else {
185        return false;
186    };
187    if WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
188        return false;
189    }
190    tracing::warn!("{why}");
191    true
192}
193
194/// Merges caller-supplied cookie options over a module's defaults and
195/// forces `http_only` back on.
196///
197/// The single home of "extend, don't replace" for cookie options. CSRF
198/// used to do the opposite — a caller passing `cookie_opts = { path =
199/// "/admin" }` got *only* that path, silently losing `HttpOnly` and
200/// `SameSite` — while sessions merged. Both now come through here, so the
201/// two cannot disagree again.
202///
203/// `http_only` is forced because no script has business reading these
204/// cookies (`nitr.csrf.token(req)` is the supported route, and a session
205/// is server state). `same_site` deliberately stays overridable: a
206/// legitimate cross-site form needs `None`, and forcing it would repeat
207/// the same mistake in the other direction.
208pub(crate) fn merge_cookie_opts(defaults: Table, caller: Option<&Table>) -> mlua::Result<Table> {
209    if let Some(caller) = caller {
210        for pair in caller.pairs::<Value, Value>() {
211            let (key, value) = pair?;
212            defaults.set(key, value)?;
213        }
214    }
215    defaults.set("http_only", true)?;
216    Ok(defaults)
217}
218
219/// Serializes one cookie, applying the recognized options: `http_only`,
220/// `secure`, `path`, `domain`, `max_age` (seconds), `same_site`
221/// (`"Strict"` / `"Lax"` / `"None"`).
222///
223/// `secure` is the one attribute with a server-resolved default (see
224/// [`CookieDefaults`]): an explicit value from Lua always wins, in both
225/// directions, and its absence means the `[cookies] secure` policy
226/// decides. That resolution happens *outside* the options block below, so
227/// it also covers `res.cookies:set(name, value)` called with no options
228/// table at all.
229pub(crate) fn build_cookie(
230    lua: &Lua,
231    name: &str,
232    value: &str,
233    opts: Option<&Table>,
234) -> mlua::Result<String> {
235    // The `cookie` crate serializes without encoding anything, so a value
236    // taken from a request (`res.cookies:set("lang", req.query.lang)`)
237    // could carry `; Domain=.example.com; SameSite=None` straight into the
238    // header. RFC 6265's grammar is enforced here instead: a name is a
239    // token, a value has no separators, and the path/domain attributes
240    // cannot start a new attribute. CRLF is caught again downstream by
241    // the header-value check, but by then the damage is a whole header.
242    check_cookie_name(name)?;
243    check_cookie_value(value)?;
244    let mut builder = cookie::Cookie::build((name.to_owned(), value.to_owned()));
245    let explicit_secure = match opts {
246        Some(opts) => opts.get::<Option<bool>>("secure")?,
247        None => None,
248    };
249    match explicit_secure {
250        Some(true) => builder = builder.secure(true),
251        Some(false) => {}
252        None if secure_default(lua) => builder = builder.secure(true),
253        None => {
254            warn_insecure_once(lua);
255        }
256    }
257    if let Some(opts) = opts {
258        if opts.get::<Option<bool>>("http_only")?.unwrap_or(false) {
259            builder = builder.http_only(true);
260        }
261        if let Some(path) = opts.get::<Option<String>>("path")? {
262            check_cookie_attribute("path", &path)?;
263            builder = builder.path(path);
264        }
265        if let Some(domain) = opts.get::<Option<String>>("domain")? {
266            check_cookie_attribute("domain", &domain)?;
267            builder = builder.domain(domain);
268        }
269        if let Some(secs) = opts.get::<Option<i64>>("max_age")? {
270            builder = builder.max_age(cookie::time::Duration::seconds(secs));
271        }
272        if let Some(same_site) = opts.get::<Option<String>>("same_site")? {
273            builder = builder.same_site(match same_site.to_ascii_lowercase().as_str() {
274                "strict" => cookie::SameSite::Strict,
275                "lax" => cookie::SameSite::Lax,
276                "none" => cookie::SameSite::None,
277                other => {
278                    return Err(mlua::Error::RuntimeError(format!(
279                        "invalid same_site value `{other}`: expected Strict, Lax or None"
280                    )));
281                }
282            });
283        }
284    }
285    Ok(builder.build().to_string())
286}
287
288/// RFC 6265 `token`: printable ASCII minus the separators.
289fn check_cookie_name(name: &str) -> mlua::Result<()> {
290    const SEPARATORS: &[u8] = b"()<>@,;:\\\"/[]?={} \t";
291    let ok = !name.is_empty()
292        && name
293            .bytes()
294            .all(|b| b.is_ascii_graphic() && !SEPARATORS.contains(&b));
295    if ok {
296        Ok(())
297    } else {
298        Err(mlua::Error::RuntimeError(format!(
299            "invalid cookie name {name:?}: a name is one or more ASCII characters other \
300             than controls, whitespace and ()<>@,;:\\\"/[]?={{}}"
301        )))
302    }
303}
304
305/// RFC 6265 `cookie-octet`: no controls, whitespace, quotes, commas,
306/// semicolons or backslashes. Values that need those are the caller's to
307/// encode (base64 or percent-encoding) — signed cookies already are.
308fn check_cookie_value(value: &str) -> mlua::Result<()> {
309    let ok = value
310        .bytes()
311        .all(|b| b.is_ascii_graphic() && !matches!(b, b'"' | b',' | b';' | b'\\'));
312    if ok {
313        Ok(())
314    } else {
315        Err(mlua::Error::RuntimeError(
316            "invalid cookie value: values may not contain controls, whitespace, quotes, \
317             commas, semicolons or backslashes — encode it first (nitr.base64, or a signed \
318             cookie)"
319                .into(),
320        ))
321    }
322}
323
324/// `Path`/`Domain` attribute values: anything printable except `;`, which
325/// would start a new attribute.
326fn check_cookie_attribute(attr: &str, value: &str) -> mlua::Result<()> {
327    if value.bytes().all(|b| b.is_ascii_graphic() && b != b';') {
328        Ok(())
329    } else {
330        Err(mlua::Error::RuntimeError(format!(
331            "invalid cookie {attr} {value:?}: controls, whitespace and ';' are not allowed"
332        )))
333    }
334}
335
336/// One `Set-Cookie` line as a client reads it: the pair plus every
337/// attribute, `Expires` as unix seconds.
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct SetCookie {
340    /// Cookie name.
341    pub name: String,
342    /// Cookie value, as sent.
343    pub value: String,
344    /// `Path`, when present.
345    pub path: Option<String>,
346    /// `Domain`, when present.
347    pub domain: Option<String>,
348    /// `Max-Age` in seconds, when present (`0` or less deletes).
349    pub max_age: Option<i64>,
350    /// `Expires` as unix seconds, when present and parseable.
351    pub expires: Option<i64>,
352    /// Whether `Secure` is set.
353    pub secure: bool,
354    /// Whether `HttpOnly` is set.
355    pub http_only: bool,
356    /// `SameSite` as written (`Strict`, `Lax`, `None`), when present.
357    pub same_site: Option<String>,
358}
359
360/// Parses one `Set-Cookie` header value, or `None` when it has no valid
361/// `name=value` pair. The attribute grammar is the `cookie` crate's (the
362/// same crate that serializes Nitr's own cookies), so a round trip cannot
363/// disagree with the writer.
364pub fn parse_set_cookie(line: &str) -> Option<SetCookie> {
365    let parsed = cookie::Cookie::parse(line).ok()?;
366    Some(SetCookie {
367        name: parsed.name().to_string(),
368        value: parsed.value().to_string(),
369        path: parsed.path().map(str::to_string),
370        domain: parsed.domain().map(str::to_string),
371        max_age: parsed.max_age().map(|age| age.whole_seconds()),
372        expires: parsed.expires_datetime().map(|at| at.unix_timestamp()),
373        secure: parsed.secure().unwrap_or(false),
374        http_only: parsed.http_only().unwrap_or(false),
375        same_site: parsed.same_site().map(|s| s.to_string()),
376    })
377}
378
379/// Encodes and signs a cookie value: `b64(value) . b64(hmac)`, with the
380/// cookie name bound into the MAC so values cannot be swapped between
381/// cookies.
382pub fn sign(name: &str, value: &str, secret: &str) -> String {
383    let payload = B64.encode(value);
384    format!(
385        "{payload}.{}",
386        B64.encode(mac_bytes(name, &payload, secret))
387    )
388}
389
390/// Verifies a value produced by [`sign()`]; the MAC comparison is
391/// constant-time (`hmac::Mac::verify_slice`).
392pub fn verify(name: &str, signed: &str, secret: &str) -> Option<String> {
393    let (payload, sig) = signed.rsplit_once('.')?;
394    let sig = B64.decode(sig).ok()?;
395    new_mac(name, payload, secret).verify_slice(&sig).ok()?;
396    String::from_utf8(B64.decode(payload).ok()?).ok()
397}
398
399fn new_mac(name: &str, payload: &str, secret: &str) -> HmacSha256 {
400    let mut mac: HmacSha256 = crate::utils::new_hmac(secret.as_bytes());
401    mac.update(name.as_bytes());
402    mac.update(b"=");
403    mac.update(payload.as_bytes());
404    mac
405}
406
407fn mac_bytes(name: &str, payload: &str, secret: &str) -> Vec<u8> {
408    new_mac(name, payload, secret)
409        .finalize()
410        .into_bytes()
411        .to_vec()
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417
418    #[test]
419    fn signed_cookies_round_trip_and_reject_tampering() {
420        let signed = sign("session", "user-42", "s3cret");
421        assert_eq!(
422            verify("session", &signed, "s3cret").as_deref(),
423            Some("user-42")
424        );
425
426        // Wrong secret, wrong name (cookie swapping), tampered payload.
427        assert_eq!(verify("session", &signed, "other"), None);
428        assert_eq!(verify("tracking", &signed, "s3cret"), None);
429        let tampered = format!("x{signed}");
430        assert_eq!(verify("session", &tampered, "s3cret"), None);
431        assert_eq!(verify("session", "garbage", "s3cret"), None);
432    }
433
434    /// The `Secure` default reaches every cookie Nitr serializes, and an
435    /// explicit value from Lua wins in *both* directions — a caller who
436    /// writes `secure = false` on a TLS server must still get a plain
437    /// cookie, or the escape hatch is gone.
438    #[test]
439    fn the_secure_default_applies_unless_the_caller_says_otherwise() {
440        for (default_secure, explicit, want_secure) in [
441            // No policy registered at all: today's behaviour.
442            (None, None, false),
443            (Some(false), None, false),
444            (Some(true), None, true),
445            // An explicit value always wins.
446            (Some(true), Some(false), false),
447            (Some(false), Some(true), true),
448        ] {
449            let lua = mlua::Lua::new();
450            if let Some(secure) = default_secure {
451                lua.set_app_data(CookieDefaults {
452                    secure,
453                    insecure_warning: None,
454                });
455            }
456            let opts = match explicit {
457                Some(value) => {
458                    let opts = lua.create_table().expect("table");
459                    opts.set("secure", value).expect("set");
460                    Some(opts)
461                }
462                None => None,
463            };
464            let cookie = build_cookie(&lua, "session", "abc", opts.as_ref()).expect("cookie");
465            assert_eq!(
466                cookie.contains("Secure"),
467                want_secure,
468                "default={default_secure:?} explicit={explicit:?} gave `{cookie}`"
469            );
470        }
471    }
472
473    /// The warning about cookies without `Secure` belongs to the first
474    /// cookie built that way, once: an explicit `secure = false` is the
475    /// caller's decision and says nothing.
476    #[test]
477    fn the_insecure_warning_fires_once_on_the_first_cookie_built_without_secure() {
478        let lua = mlua::Lua::new();
479        assert!(
480            !warn_insecure_once(&lua),
481            "nothing registered, nothing to say"
482        );
483        lua.set_app_data(CookieDefaults {
484            secure: false,
485            insecure_warning: Some("[tls] enabled = false".into()),
486        });
487        let opts = lua.create_table().expect("table");
488        opts.set("secure", false).expect("set");
489        build_cookie(&lua, "a", "1", Some(&opts)).expect("cookie");
490        assert!(
491            warn_insecure_once(&lua),
492            "an explicit false must not have spent the warning"
493        );
494        build_cookie(&lua, "b", "2", None).expect("cookie");
495        assert!(
496            !warn_insecure_once(&lua),
497            "spent by the cookie built without Secure"
498        );
499    }
500
501    /// A caller's options extend the module defaults rather than replacing
502    /// them, and `http_only` cannot be un-set.
503    #[test]
504    fn merging_cookie_options_keeps_the_defaults_a_caller_did_not_mention() {
505        let lua = mlua::Lua::new();
506        let defaults = lua.create_table().expect("table");
507        defaults.set("path", "/").expect("set");
508        defaults.set("same_site", "Lax").expect("set");
509
510        // A partial table: only `path` is mentioned.
511        let caller = lua.create_table().expect("table");
512        caller.set("path", "/admin").expect("set");
513        let merged = merge_cookie_opts(defaults, Some(&caller)).expect("merge");
514        assert_eq!(
515            merged.get::<String>("path").expect("path"),
516            "/admin",
517            "the caller's value wins"
518        );
519        assert_eq!(
520            merged.get::<String>("same_site").expect("same_site"),
521            "Lax",
522            "a default the caller did not mention must survive"
523        );
524        assert!(
525            merged.get::<bool>("http_only").expect("http_only"),
526            "http_only must survive"
527        );
528
529        // `http_only = false` cannot un-set it; `same_site` stays
530        // overridable, because a legitimate cross-site form needs `None`.
531        let defaults = lua.create_table().expect("table");
532        defaults.set("same_site", "Lax").expect("set");
533        let caller = lua.create_table().expect("table");
534        caller.set("http_only", false).expect("set");
535        caller.set("same_site", "None").expect("set");
536        let merged = merge_cookie_opts(defaults, Some(&caller)).expect("merge");
537        assert!(
538            merged.get::<bool>("http_only").expect("http_only"),
539            "http_only is forced, not merely defaulted"
540        );
541        assert_eq!(
542            merged.get::<String>("same_site").expect("same_site"),
543            "None",
544            "same_site is deliberately overridable"
545        );
546    }
547
548    /// A value or attribute taken from a request cannot smuggle further
549    /// attributes into the header.
550    #[test]
551    fn cookie_parts_that_would_inject_attributes_are_refused() {
552        let lua = mlua::Lua::new();
553        for (name, value) in [
554            ("lang", "en; Domain=.example.com; SameSite=None"),
555            ("lang", "a b"),
556            ("lang", "x\"y"),
557            ("lang", "a,b"),
558            ("lang", "back\\slash"),
559            ("bad name", "v"),
560            ("bad=name", "v"),
561            ("", "v"),
562        ] {
563            let err = build_cookie(&lua, name, value, None).expect_err("injection");
564            assert!(
565                err.to_string().contains("invalid cookie"),
566                "{name}={value}: {err}"
567            );
568        }
569        for attr in ["path", "domain"] {
570            let opts = lua.create_table().expect("table");
571            opts.set(attr, "/x; Secure").expect("set");
572            let err = build_cookie(&lua, "n", "v", Some(&opts)).expect_err(attr);
573            assert!(err.to_string().contains(attr), "{err}");
574        }
575        // Ordinary and signed values pass, including base64url alphabet.
576        for value in ["", "abc", "a-b_c.d~e=", "ZmZm.YWJj"] {
577            build_cookie(&lua, "ok", value, None).expect("plain value");
578        }
579    }
580
581    #[test]
582    fn cookies_serialize_their_options() {
583        let lua = mlua::Lua::new();
584        let opts: Table = lua
585            .load(r#"{ http_only = true, secure = true, same_site = "Lax", max_age = 3600, path = "/" }"#)
586            .eval()
587            .expect("opts table");
588        let cookie = build_cookie(&lua, "session", "abc", Some(&opts)).expect("cookie");
589        for part in [
590            "session=abc",
591            "HttpOnly",
592            "Secure",
593            "SameSite=Lax",
594            "Max-Age=3600",
595            "Path=/",
596        ] {
597            assert!(cookie.contains(part), "`{cookie}` should contain `{part}`");
598        }
599    }
600
601    #[test]
602    fn set_cookie_lines_parse_into_their_attributes() {
603        let full = parse_set_cookie(
604            "sid=abc; Path=/app; Domain=example.com; Max-Age=60; \
605             Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly; SameSite=Strict",
606        )
607        .expect("parses");
608        assert_eq!(
609            full,
610            SetCookie {
611                name: "sid".into(),
612                value: "abc".into(),
613                path: Some("/app".into()),
614                domain: Some("example.com".into()),
615                max_age: Some(60),
616                expires: Some(1_445_412_480),
617                secure: true,
618                http_only: true,
619                same_site: Some("Strict".into()),
620            }
621        );
622        let bare = parse_set_cookie("theme=dark").expect("bare");
623        assert_eq!((bare.path, bare.max_age, bare.secure), (None, None, false));
624        let deleted = parse_set_cookie("sid=; Max-Age=0").expect("deletion");
625        assert_eq!((deleted.value.as_str(), deleted.max_age), ("", Some(0)));
626        assert_eq!(parse_set_cookie("no pair here"), None);
627        assert_eq!(parse_set_cookie(""), None);
628    }
629
630    #[test]
631    fn nitr_cookie_signs_and_verifies_like_the_cookie_builders() {
632        let lua = mlua::Lua::new();
633        let nitr = lua.create_table().expect("table");
634        super::super::register(&lua, &nitr).expect("register");
635        lua.globals().set("nitr", nitr).expect("global");
636        let (signed, back, forged, swapped): (String, String, Value, Value) = lua
637            .load(
638                r#"local s = nitr.cookie.sign("session", '{"user":"ann"}', "k")
639                   return s, nitr.cookie.verify("session", s, "k"),
640                          nitr.cookie.verify("session", s, "other"),
641                          nitr.cookie.verify("tracking", s, "k")"#,
642            )
643            .eval()
644            .expect("eval");
645        assert_eq!(signed, sign("session", r#"{"user":"ann"}"#, "k"));
646        assert_eq!(back, r#"{"user":"ann"}"#);
647        assert!(forged.is_nil() && swapped.is_nil());
648    }
649
650    proptest::proptest! {
651        /// Property: a cookie Nitr serializes parses back to exactly the
652        /// name, value and attributes it was built with — the client jar
653        /// in `nitr test` reads what production writes.
654        #[test]
655        fn prop_set_cookie_round_trip(
656            name in "[A-Za-z0-9_!#$%&'*+.^`|~-]{1,16}",
657            value in "[A-Za-z0-9!#$%&'()*+./:<=>?@^_`{|}~-]{0,32}",
658            path in proptest::option::of("/[A-Za-z0-9_./-]{0,16}"),
659            max_age in proptest::option::of(-10i64..100_000),
660            same_site in proptest::option::of(proptest::sample::select(vec!["Strict", "Lax", "None"])),
661            secure in proptest::bool::ANY,
662            http_only in proptest::bool::ANY,
663        ) {
664            let lua = mlua::Lua::new();
665            let opts = lua.create_table().expect("opts");
666            opts.set("secure", secure).expect("secure");
667            opts.set("http_only", http_only).expect("http_only");
668            if let Some(path) = &path {
669                opts.set("path", path.as_str()).expect("path");
670            }
671            if let Some(age) = max_age {
672                opts.set("max_age", age).expect("max_age");
673            }
674            if let Some(same_site) = same_site {
675                opts.set("same_site", same_site).expect("same_site");
676            }
677            let line = build_cookie(&lua, &name, &value, Some(&opts)).expect("build");
678            let parsed = parse_set_cookie(&line).expect("parse back");
679            proptest::prop_assert_eq!(parsed.name, name);
680            proptest::prop_assert_eq!(parsed.value, value);
681            proptest::prop_assert_eq!(parsed.path, path);
682            // A negative `Max-Age` is written as given and read as 0 —
683            // both mean "delete now" (RFC 6265 §5.2.2).
684            proptest::prop_assert_eq!(parsed.max_age, max_age.map(|age| age.max(0)));
685            proptest::prop_assert_eq!(parsed.same_site.as_deref(), same_site);
686            // The `cookie` crate writes `Secure` whenever `SameSite=None`
687            // is set, as browsers require.
688            proptest::prop_assert_eq!(parsed.secure, secure || same_site == Some("None"));
689            proptest::prop_assert_eq!(parsed.http_only, http_only);
690        }
691
692        /// Property: sign/verify round-trips arbitrary printable inputs,
693        /// and flipping any single character of the signed value breaks
694        /// it — as do the wrong secret and a swapped cookie name.
695        #[test]
696        fn prop_signed_cookies_round_trip_and_any_tamper_fails(
697            name in "[ -~]{1,16}",
698            value in "[ -~]{0,48}",
699            secret in "[ -~]{1,32}",
700            pos in proptest::prelude::any::<proptest::sample::Index>(),
701        ) {
702            let signed = sign(&name, &value, &secret);
703            let verified = verify(&name, &signed, &secret);
704            proptest::prop_assert_eq!(verified.as_deref(), Some(value.as_str()));
705
706            // One changed character anywhere — payload or MAC — must fail.
707            // The index is taken over the collected chars, not the byte
708            // length: the two only coincide while the signed encoding
709            // stays pure ASCII, and the test must not depend on that.
710            let mut tampered: Vec<char> = signed.chars().collect();
711            let pos = pos.index(tampered.len());
712            tampered[pos] = if tampered[pos] == 'A' { 'B' } else { 'A' };
713            let tampered: String = tampered.into_iter().collect();
714            proptest::prop_assert_eq!(verify(&name, &tampered, &secret), None);
715
716            proptest::prop_assert_eq!(verify(&name, &signed, "other-secret"), None);
717            proptest::prop_assert_eq!(verify("other-name", &signed, &secret), None);
718        }
719    }
720}