nitr-std 0.0.0-beta.7

The built-in `nitr.*` standard library for Nitr: dbg, fetch, template, json, http, log, crypto, and the SQLite driver.
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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Nitr.
// See https://nitrweb.com/ for more information
// Copyright (C) 2024-present Jose Quintana <joseluisq.net>

//! Request/response cookies: parsing, the `Set-Cookie` builder, the
//! server-resolved `Secure` default, and HMAC-SHA256 signed variants.

use std::sync::Mutex;

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use hmac::{Hmac, Mac as _};
use mlua::{Lua, MetaMethod, Table, UserData, UserDataMethods, Value};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

/// Cookies parsed from a request's `Cookie` header: values via indexing
/// (`req.cookies.session`) and signed-cookie verification via
/// `req.cookies:verify(name, secret)`.
pub struct RequestCookies(Vec<(String, String)>);

impl RequestCookies {
    /// Parses a `Cookie` request header (an empty string yields no cookies).
    pub fn parse(header: &str) -> Self {
        Self(
            cookie::Cookie::split_parse(header)
                .flatten()
                .map(|c| (c.name().to_string(), c.value().to_string()))
                .collect(),
        )
    }

    /// The parsed (name, value) pairs, in header order, for the
    /// `cookie_header` fuzz target — the parse result is otherwise only
    /// observable through Lua indexing.
    #[doc(hidden)]
    pub fn pairs(&self) -> &[(String, String)] {
        &self.0
    }

    pub(crate) fn get(&self, name: &str) -> Option<&str> {
        self.0
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| v.as_str())
    }
}

impl UserData for RequestCookies {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        methods.add_meta_method(MetaMethod::Index, |lua, this, name: Value| {
            let Value::String(name) = name else {
                return Ok(Value::Nil);
            };
            match this.get(&name.to_string_lossy()) {
                Some(v) => Ok(Value::String(lua.create_string(v)?)),
                None => Ok(Value::Nil),
            }
        });

        // Returns the verified value of a signed cookie, or nil when the
        // cookie is missing, malformed, or its signature does not match.
        methods.add_method(
            "verify",
            |lua, this, (name, secret): (String, String)| match this
                .get(&name)
                .and_then(|raw| verify(&name, raw, &secret))
            {
                Some(v) => Ok(Value::String(lua.create_string(v)?)),
                None => Ok(Value::Nil),
            },
        );
    }
}

/// Builder for response `Set-Cookie` headers, attached as the `cookies`
/// field of helper-built response tables. The server serializes each entry
/// into its own `Set-Cookie` header.
#[derive(Default)]
pub struct ResponseCookies(Mutex<Vec<String>>);

impl ResponseCookies {
    /// The serialized `Set-Cookie` values collected so far.
    pub fn values(&self) -> Vec<String> {
        self.0.lock().map(|v| v.clone()).unwrap_or_default()
    }

    fn push(&self, value: String) -> mlua::Result<()> {
        self.0
            .lock()
            .map_err(|_| mlua::Error::RuntimeError("the cookie list lock is poisoned".into()))?
            .push(value);
        Ok(())
    }
}

impl UserData for ResponseCookies {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        methods.add_method(
            "set",
            |lua, this, (name, value, opts): (String, String, Option<Table>)| {
                this.push(build_cookie(lua, &name, &value, opts.as_ref())?)
            },
        );

        // Signs the value with HMAC-SHA256 so `req.cookies:verify(name,
        // secret)` can authenticate it on later requests.
        methods.add_method(
            "set_signed",
            |lua, this, (name, value, secret, opts): (String, String, String, Option<Table>)| {
                this.push(build_cookie(
                    lua,
                    &name,
                    &sign(&name, &value, &secret),
                    opts.as_ref(),
                )?)
            },
        );
    }
}

/// Attaches a serialized `Set-Cookie` value to a handler response table:
/// through its `cookies` builder when present (helper-built responses), or
/// by creating one (hand-built plain tables), so the server's response
/// conversion picks it up either way.
pub(crate) fn attach_cookie(resp: &Table, cookie: String) -> mlua::Result<()> {
    match resp.raw_get::<Value>("cookies")? {
        Value::UserData(ud) => {
            let cookies = ud.borrow::<ResponseCookies>().map_err(|_| {
                mlua::Error::RuntimeError(
                    "the response `cookies` field is not a cookie builder".into(),
                )
            })?;
            cookies.push(cookie)
        }
        Value::Nil => {
            let cookies = ResponseCookies::default();
            cookies.push(cookie)?;
            resp.set("cookies", cookies)
        }
        other => Err(mlua::Error::RuntimeError(format!(
            "invalid `cookies` field of type `{}` in the response table",
            other.type_name()
        ))),
    }
}

/// The per-state cookie policy, stashed by `register_builtins` and read
/// by [`build_cookie`].
///
/// App data rather than a captured value because [`build_cookie`] is
/// reached from `UserData` methods, whose closures are registered once per
/// *type* and so cannot capture per-server state — the alternative would
/// be threading the flag into every `ResponseCookies` construction site.
/// Absent means not secure, matching `BuiltinsEnv`'s derived `Default`, so
/// an embedder who never sets one keeps today's behaviour.
#[derive(Debug, Clone, Default)]
pub struct CookieDefaults {
    /// Whether cookies carry `Secure` when the caller's options do not say.
    pub secure: bool,
    /// Why a cookie built without `Secure` deserves a warning, when the
    /// server could not tell whether a proxy terminates TLS in front of
    /// it. Logged once per process, the first time such a cookie is
    /// built: a service that never sets one is never told about them.
    pub insecure_warning: Option<String>,
}

/// The resolved `Secure` default for this state; `false` when nothing
/// registered one.
fn secure_default(lua: &Lua) -> bool {
    lua.app_data_ref::<CookieDefaults>()
        .is_some_and(|defaults| defaults.secure)
}

/// Logs the configured warning the first time a cookie ships without
/// `Secure` by default; reports whether this call was the one to log it.
fn warn_insecure_once(lua: &Lua) -> bool {
    static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    let Some(why) = lua
        .app_data_ref::<CookieDefaults>()
        .and_then(|defaults| defaults.insecure_warning.clone())
    else {
        return false;
    };
    if WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
        return false;
    }
    tracing::warn!("{why}");
    true
}

/// Merges caller-supplied cookie options over a module's defaults and
/// forces `http_only` back on.
///
/// The single home of "extend, don't replace" for cookie options. CSRF
/// used to do the opposite — a caller passing `cookie_opts = { path =
/// "/admin" }` got *only* that path, silently losing `HttpOnly` and
/// `SameSite` — while sessions merged. Both now come through here, so the
/// two cannot disagree again.
///
/// `http_only` is forced because no script has business reading these
/// cookies (`nitr.csrf.token(req)` is the supported route, and a session
/// is server state). `same_site` deliberately stays overridable: a
/// legitimate cross-site form needs `None`, and forcing it would repeat
/// the same mistake in the other direction.
pub(crate) fn merge_cookie_opts(defaults: Table, caller: Option<&Table>) -> mlua::Result<Table> {
    if let Some(caller) = caller {
        for pair in caller.pairs::<Value, Value>() {
            let (key, value) = pair?;
            defaults.set(key, value)?;
        }
    }
    defaults.set("http_only", true)?;
    Ok(defaults)
}

/// Serializes one cookie, applying the recognized options: `http_only`,
/// `secure`, `path`, `domain`, `max_age` (seconds), `same_site`
/// (`"Strict"` / `"Lax"` / `"None"`).
///
/// `secure` is the one attribute with a server-resolved default (see
/// [`CookieDefaults`]): an explicit value from Lua always wins, in both
/// directions, and its absence means the `[cookies] secure` policy
/// decides. That resolution happens *outside* the options block below, so
/// it also covers `res.cookies:set(name, value)` called with no options
/// table at all.
pub(crate) fn build_cookie(
    lua: &Lua,
    name: &str,
    value: &str,
    opts: Option<&Table>,
) -> mlua::Result<String> {
    // The `cookie` crate serializes without encoding anything, so a value
    // taken from a request (`res.cookies:set("lang", req.query.lang)`)
    // could carry `; Domain=.example.com; SameSite=None` straight into the
    // header. RFC 6265's grammar is enforced here instead: a name is a
    // token, a value has no separators, and the path/domain attributes
    // cannot start a new attribute. CRLF is caught again downstream by
    // the header-value check, but by then the damage is a whole header.
    check_cookie_name(name)?;
    check_cookie_value(value)?;
    let mut builder = cookie::Cookie::build((name.to_owned(), value.to_owned()));
    let explicit_secure = match opts {
        Some(opts) => opts.get::<Option<bool>>("secure")?,
        None => None,
    };
    match explicit_secure {
        Some(true) => builder = builder.secure(true),
        Some(false) => {}
        None if secure_default(lua) => builder = builder.secure(true),
        None => {
            warn_insecure_once(lua);
        }
    }
    if let Some(opts) = opts {
        if opts.get::<Option<bool>>("http_only")?.unwrap_or(false) {
            builder = builder.http_only(true);
        }
        if let Some(path) = opts.get::<Option<String>>("path")? {
            check_cookie_attribute("path", &path)?;
            builder = builder.path(path);
        }
        if let Some(domain) = opts.get::<Option<String>>("domain")? {
            check_cookie_attribute("domain", &domain)?;
            builder = builder.domain(domain);
        }
        if let Some(secs) = opts.get::<Option<i64>>("max_age")? {
            builder = builder.max_age(cookie::time::Duration::seconds(secs));
        }
        if let Some(same_site) = opts.get::<Option<String>>("same_site")? {
            builder = builder.same_site(match same_site.to_ascii_lowercase().as_str() {
                "strict" => cookie::SameSite::Strict,
                "lax" => cookie::SameSite::Lax,
                "none" => cookie::SameSite::None,
                other => {
                    return Err(mlua::Error::RuntimeError(format!(
                        "invalid same_site value `{other}`: expected Strict, Lax or None"
                    )));
                }
            });
        }
    }
    Ok(builder.build().to_string())
}

/// RFC 6265 `token`: printable ASCII minus the separators.
fn check_cookie_name(name: &str) -> mlua::Result<()> {
    const SEPARATORS: &[u8] = b"()<>@,;:\\\"/[]?={} \t";
    let ok = !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_graphic() && !SEPARATORS.contains(&b));
    if ok {
        Ok(())
    } else {
        Err(mlua::Error::RuntimeError(format!(
            "invalid cookie name {name:?}: a name is one or more ASCII characters other \
             than controls, whitespace and ()<>@,;:\\\"/[]?={{}}"
        )))
    }
}

/// RFC 6265 `cookie-octet`: no controls, whitespace, quotes, commas,
/// semicolons or backslashes. Values that need those are the caller's to
/// encode (base64 or percent-encoding) — signed cookies already are.
fn check_cookie_value(value: &str) -> mlua::Result<()> {
    let ok = value
        .bytes()
        .all(|b| b.is_ascii_graphic() && !matches!(b, b'"' | b',' | b';' | b'\\'));
    if ok {
        Ok(())
    } else {
        Err(mlua::Error::RuntimeError(
            "invalid cookie value: values may not contain controls, whitespace, quotes, \
             commas, semicolons or backslashes — encode it first (nitr.base64, or a signed \
             cookie)"
                .into(),
        ))
    }
}

/// `Path`/`Domain` attribute values: anything printable except `;`, which
/// would start a new attribute.
fn check_cookie_attribute(attr: &str, value: &str) -> mlua::Result<()> {
    if value.bytes().all(|b| b.is_ascii_graphic() && b != b';') {
        Ok(())
    } else {
        Err(mlua::Error::RuntimeError(format!(
            "invalid cookie {attr} {value:?}: controls, whitespace and ';' are not allowed"
        )))
    }
}

/// One `Set-Cookie` line as a client reads it: the pair plus every
/// attribute, `Expires` as unix seconds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetCookie {
    /// Cookie name.
    pub name: String,
    /// Cookie value, as sent.
    pub value: String,
    /// `Path`, when present.
    pub path: Option<String>,
    /// `Domain`, when present.
    pub domain: Option<String>,
    /// `Max-Age` in seconds, when present (`0` or less deletes).
    pub max_age: Option<i64>,
    /// `Expires` as unix seconds, when present and parseable.
    pub expires: Option<i64>,
    /// Whether `Secure` is set.
    pub secure: bool,
    /// Whether `HttpOnly` is set.
    pub http_only: bool,
    /// `SameSite` as written (`Strict`, `Lax`, `None`), when present.
    pub same_site: Option<String>,
}

/// Parses one `Set-Cookie` header value, or `None` when it has no valid
/// `name=value` pair. The attribute grammar is the `cookie` crate's (the
/// same crate that serializes Nitr's own cookies), so a round trip cannot
/// disagree with the writer.
pub fn parse_set_cookie(line: &str) -> Option<SetCookie> {
    let parsed = cookie::Cookie::parse(line).ok()?;
    Some(SetCookie {
        name: parsed.name().to_string(),
        value: parsed.value().to_string(),
        path: parsed.path().map(str::to_string),
        domain: parsed.domain().map(str::to_string),
        max_age: parsed.max_age().map(|age| age.whole_seconds()),
        expires: parsed.expires_datetime().map(|at| at.unix_timestamp()),
        secure: parsed.secure().unwrap_or(false),
        http_only: parsed.http_only().unwrap_or(false),
        same_site: parsed.same_site().map(|s| s.to_string()),
    })
}

/// Encodes and signs a cookie value: `b64(value) . b64(hmac)`, with the
/// cookie name bound into the MAC so values cannot be swapped between
/// cookies.
pub fn sign(name: &str, value: &str, secret: &str) -> String {
    let payload = B64.encode(value);
    format!(
        "{payload}.{}",
        B64.encode(mac_bytes(name, &payload, secret))
    )
}

/// Verifies a value produced by [`sign()`]; the MAC comparison is
/// constant-time (`hmac::Mac::verify_slice`).
pub fn verify(name: &str, signed: &str, secret: &str) -> Option<String> {
    let (payload, sig) = signed.rsplit_once('.')?;
    let sig = B64.decode(sig).ok()?;
    new_mac(name, payload, secret).verify_slice(&sig).ok()?;
    String::from_utf8(B64.decode(payload).ok()?).ok()
}

fn new_mac(name: &str, payload: &str, secret: &str) -> HmacSha256 {
    let mut mac: HmacSha256 = crate::utils::new_hmac(secret.as_bytes());
    mac.update(name.as_bytes());
    mac.update(b"=");
    mac.update(payload.as_bytes());
    mac
}

fn mac_bytes(name: &str, payload: &str, secret: &str) -> Vec<u8> {
    new_mac(name, payload, secret)
        .finalize()
        .into_bytes()
        .to_vec()
}

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

    #[test]
    fn signed_cookies_round_trip_and_reject_tampering() {
        let signed = sign("session", "user-42", "s3cret");
        assert_eq!(
            verify("session", &signed, "s3cret").as_deref(),
            Some("user-42")
        );

        // Wrong secret, wrong name (cookie swapping), tampered payload.
        assert_eq!(verify("session", &signed, "other"), None);
        assert_eq!(verify("tracking", &signed, "s3cret"), None);
        let tampered = format!("x{signed}");
        assert_eq!(verify("session", &tampered, "s3cret"), None);
        assert_eq!(verify("session", "garbage", "s3cret"), None);
    }

    /// The `Secure` default reaches every cookie Nitr serializes, and an
    /// explicit value from Lua wins in *both* directions — a caller who
    /// writes `secure = false` on a TLS server must still get a plain
    /// cookie, or the escape hatch is gone.
    #[test]
    fn the_secure_default_applies_unless_the_caller_says_otherwise() {
        for (default_secure, explicit, want_secure) in [
            // No policy registered at all: today's behaviour.
            (None, None, false),
            (Some(false), None, false),
            (Some(true), None, true),
            // An explicit value always wins.
            (Some(true), Some(false), false),
            (Some(false), Some(true), true),
        ] {
            let lua = mlua::Lua::new();
            if let Some(secure) = default_secure {
                lua.set_app_data(CookieDefaults {
                    secure,
                    insecure_warning: None,
                });
            }
            let opts = match explicit {
                Some(value) => {
                    let opts = lua.create_table().expect("table");
                    opts.set("secure", value).expect("set");
                    Some(opts)
                }
                None => None,
            };
            let cookie = build_cookie(&lua, "session", "abc", opts.as_ref()).expect("cookie");
            assert_eq!(
                cookie.contains("Secure"),
                want_secure,
                "default={default_secure:?} explicit={explicit:?} gave `{cookie}`"
            );
        }
    }

    /// The warning about cookies without `Secure` belongs to the first
    /// cookie built that way, once: an explicit `secure = false` is the
    /// caller's decision and says nothing.
    #[test]
    fn the_insecure_warning_fires_once_on_the_first_cookie_built_without_secure() {
        let lua = mlua::Lua::new();
        assert!(
            !warn_insecure_once(&lua),
            "nothing registered, nothing to say"
        );
        lua.set_app_data(CookieDefaults {
            secure: false,
            insecure_warning: Some("[tls] enabled = false".into()),
        });
        let opts = lua.create_table().expect("table");
        opts.set("secure", false).expect("set");
        build_cookie(&lua, "a", "1", Some(&opts)).expect("cookie");
        assert!(
            warn_insecure_once(&lua),
            "an explicit false must not have spent the warning"
        );
        build_cookie(&lua, "b", "2", None).expect("cookie");
        assert!(
            !warn_insecure_once(&lua),
            "spent by the cookie built without Secure"
        );
    }

    /// A caller's options extend the module defaults rather than replacing
    /// them, and `http_only` cannot be un-set.
    #[test]
    fn merging_cookie_options_keeps_the_defaults_a_caller_did_not_mention() {
        let lua = mlua::Lua::new();
        let defaults = lua.create_table().expect("table");
        defaults.set("path", "/").expect("set");
        defaults.set("same_site", "Lax").expect("set");

        // A partial table: only `path` is mentioned.
        let caller = lua.create_table().expect("table");
        caller.set("path", "/admin").expect("set");
        let merged = merge_cookie_opts(defaults, Some(&caller)).expect("merge");
        assert_eq!(
            merged.get::<String>("path").expect("path"),
            "/admin",
            "the caller's value wins"
        );
        assert_eq!(
            merged.get::<String>("same_site").expect("same_site"),
            "Lax",
            "a default the caller did not mention must survive"
        );
        assert!(
            merged.get::<bool>("http_only").expect("http_only"),
            "http_only must survive"
        );

        // `http_only = false` cannot un-set it; `same_site` stays
        // overridable, because a legitimate cross-site form needs `None`.
        let defaults = lua.create_table().expect("table");
        defaults.set("same_site", "Lax").expect("set");
        let caller = lua.create_table().expect("table");
        caller.set("http_only", false).expect("set");
        caller.set("same_site", "None").expect("set");
        let merged = merge_cookie_opts(defaults, Some(&caller)).expect("merge");
        assert!(
            merged.get::<bool>("http_only").expect("http_only"),
            "http_only is forced, not merely defaulted"
        );
        assert_eq!(
            merged.get::<String>("same_site").expect("same_site"),
            "None",
            "same_site is deliberately overridable"
        );
    }

    /// A value or attribute taken from a request cannot smuggle further
    /// attributes into the header.
    #[test]
    fn cookie_parts_that_would_inject_attributes_are_refused() {
        let lua = mlua::Lua::new();
        for (name, value) in [
            ("lang", "en; Domain=.example.com; SameSite=None"),
            ("lang", "a b"),
            ("lang", "x\"y"),
            ("lang", "a,b"),
            ("lang", "back\\slash"),
            ("bad name", "v"),
            ("bad=name", "v"),
            ("", "v"),
        ] {
            let err = build_cookie(&lua, name, value, None).expect_err("injection");
            assert!(
                err.to_string().contains("invalid cookie"),
                "{name}={value}: {err}"
            );
        }
        for attr in ["path", "domain"] {
            let opts = lua.create_table().expect("table");
            opts.set(attr, "/x; Secure").expect("set");
            let err = build_cookie(&lua, "n", "v", Some(&opts)).expect_err(attr);
            assert!(err.to_string().contains(attr), "{err}");
        }
        // Ordinary and signed values pass, including base64url alphabet.
        for value in ["", "abc", "a-b_c.d~e=", "ZmZm.YWJj"] {
            build_cookie(&lua, "ok", value, None).expect("plain value");
        }
    }

    #[test]
    fn cookies_serialize_their_options() {
        let lua = mlua::Lua::new();
        let opts: Table = lua
            .load(r#"{ http_only = true, secure = true, same_site = "Lax", max_age = 3600, path = "/" }"#)
            .eval()
            .expect("opts table");
        let cookie = build_cookie(&lua, "session", "abc", Some(&opts)).expect("cookie");
        for part in [
            "session=abc",
            "HttpOnly",
            "Secure",
            "SameSite=Lax",
            "Max-Age=3600",
            "Path=/",
        ] {
            assert!(cookie.contains(part), "`{cookie}` should contain `{part}`");
        }
    }

    #[test]
    fn set_cookie_lines_parse_into_their_attributes() {
        let full = parse_set_cookie(
            "sid=abc; Path=/app; Domain=example.com; Max-Age=60; \
             Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly; SameSite=Strict",
        )
        .expect("parses");
        assert_eq!(
            full,
            SetCookie {
                name: "sid".into(),
                value: "abc".into(),
                path: Some("/app".into()),
                domain: Some("example.com".into()),
                max_age: Some(60),
                expires: Some(1_445_412_480),
                secure: true,
                http_only: true,
                same_site: Some("Strict".into()),
            }
        );
        let bare = parse_set_cookie("theme=dark").expect("bare");
        assert_eq!((bare.path, bare.max_age, bare.secure), (None, None, false));
        let deleted = parse_set_cookie("sid=; Max-Age=0").expect("deletion");
        assert_eq!((deleted.value.as_str(), deleted.max_age), ("", Some(0)));
        assert_eq!(parse_set_cookie("no pair here"), None);
        assert_eq!(parse_set_cookie(""), None);
    }

    #[test]
    fn nitr_cookie_signs_and_verifies_like_the_cookie_builders() {
        let lua = mlua::Lua::new();
        let nitr = lua.create_table().expect("table");
        super::super::register(&lua, &nitr).expect("register");
        lua.globals().set("nitr", nitr).expect("global");
        let (signed, back, forged, swapped): (String, String, Value, Value) = lua
            .load(
                r#"local s = nitr.cookie.sign("session", '{"user":"ann"}', "k")
                   return s, nitr.cookie.verify("session", s, "k"),
                          nitr.cookie.verify("session", s, "other"),
                          nitr.cookie.verify("tracking", s, "k")"#,
            )
            .eval()
            .expect("eval");
        assert_eq!(signed, sign("session", r#"{"user":"ann"}"#, "k"));
        assert_eq!(back, r#"{"user":"ann"}"#);
        assert!(forged.is_nil() && swapped.is_nil());
    }

    proptest::proptest! {
        /// Property: a cookie Nitr serializes parses back to exactly the
        /// name, value and attributes it was built with — the client jar
        /// in `nitr test` reads what production writes.
        #[test]
        fn prop_set_cookie_round_trip(
            name in "[A-Za-z0-9_!#$%&'*+.^`|~-]{1,16}",
            value in "[A-Za-z0-9!#$%&'()*+./:<=>?@^_`{|}~-]{0,32}",
            path in proptest::option::of("/[A-Za-z0-9_./-]{0,16}"),
            max_age in proptest::option::of(-10i64..100_000),
            same_site in proptest::option::of(proptest::sample::select(vec!["Strict", "Lax", "None"])),
            secure in proptest::bool::ANY,
            http_only in proptest::bool::ANY,
        ) {
            let lua = mlua::Lua::new();
            let opts = lua.create_table().expect("opts");
            opts.set("secure", secure).expect("secure");
            opts.set("http_only", http_only).expect("http_only");
            if let Some(path) = &path {
                opts.set("path", path.as_str()).expect("path");
            }
            if let Some(age) = max_age {
                opts.set("max_age", age).expect("max_age");
            }
            if let Some(same_site) = same_site {
                opts.set("same_site", same_site).expect("same_site");
            }
            let line = build_cookie(&lua, &name, &value, Some(&opts)).expect("build");
            let parsed = parse_set_cookie(&line).expect("parse back");
            proptest::prop_assert_eq!(parsed.name, name);
            proptest::prop_assert_eq!(parsed.value, value);
            proptest::prop_assert_eq!(parsed.path, path);
            // A negative `Max-Age` is written as given and read as 0 —
            // both mean "delete now" (RFC 6265 §5.2.2).
            proptest::prop_assert_eq!(parsed.max_age, max_age.map(|age| age.max(0)));
            proptest::prop_assert_eq!(parsed.same_site.as_deref(), same_site);
            // The `cookie` crate writes `Secure` whenever `SameSite=None`
            // is set, as browsers require.
            proptest::prop_assert_eq!(parsed.secure, secure || same_site == Some("None"));
            proptest::prop_assert_eq!(parsed.http_only, http_only);
        }

        /// Property: sign/verify round-trips arbitrary printable inputs,
        /// and flipping any single character of the signed value breaks
        /// it — as do the wrong secret and a swapped cookie name.
        #[test]
        fn prop_signed_cookies_round_trip_and_any_tamper_fails(
            name in "[ -~]{1,16}",
            value in "[ -~]{0,48}",
            secret in "[ -~]{1,32}",
            pos in proptest::prelude::any::<proptest::sample::Index>(),
        ) {
            let signed = sign(&name, &value, &secret);
            let verified = verify(&name, &signed, &secret);
            proptest::prop_assert_eq!(verified.as_deref(), Some(value.as_str()));

            // One changed character anywhere — payload or MAC — must fail.
            // The index is taken over the collected chars, not the byte
            // length: the two only coincide while the signed encoding
            // stays pure ASCII, and the test must not depend on that.
            let mut tampered: Vec<char> = signed.chars().collect();
            let pos = pos.index(tampered.len());
            tampered[pos] = if tampered[pos] == 'A' { 'B' } else { 'A' };
            let tampered: String = tampered.into_iter().collect();
            proptest::prop_assert_eq!(verify(&name, &tampered, &secret), None);

            proptest::prop_assert_eq!(verify(&name, &signed, "other-secret"), None);
            proptest::prop_assert_eq!(verify("other-name", &signed, &secret), None);
        }
    }
}