1use 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
19pub struct RequestCookies(Vec<(String, String)>);
23
24impl RequestCookies {
25 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 #[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 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#[derive(Default)]
82pub struct ResponseCookies(Mutex<Vec<String>>);
83
84impl ResponseCookies {
85 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 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
124pub(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#[derive(Debug, Clone, Default)]
160pub struct CookieDefaults {
161 pub secure: bool,
163 pub insecure_warning: Option<String>,
168}
169
170fn secure_default(lua: &Lua) -> bool {
173 lua.app_data_ref::<CookieDefaults>()
174 .is_some_and(|defaults| defaults.secure)
175}
176
177fn 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
194pub(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
219pub(crate) fn build_cookie(
230 lua: &Lua,
231 name: &str,
232 value: &str,
233 opts: Option<&Table>,
234) -> mlua::Result<String> {
235 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
288fn 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
305fn 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
324fn 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#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct SetCookie {
340 pub name: String,
342 pub value: String,
344 pub path: Option<String>,
346 pub domain: Option<String>,
348 pub max_age: Option<i64>,
350 pub expires: Option<i64>,
352 pub secure: bool,
354 pub http_only: bool,
356 pub same_site: Option<String>,
358}
359
360pub 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
379pub 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
390pub 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 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 #[test]
439 fn the_secure_default_applies_unless_the_caller_says_otherwise() {
440 for (default_secure, explicit, want_secure) in [
441 (None, None, false),
443 (Some(false), None, false),
444 (Some(true), None, true),
445 (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 #[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 #[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 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 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 #[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 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 #[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 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 proptest::prop_assert_eq!(parsed.secure, secure || same_site == Some("None"));
689 proptest::prop_assert_eq!(parsed.http_only, http_only);
690 }
691
692 #[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 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}