Skip to main content

nitr_std/
http.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//! HTTP ergonomics for Lua handlers: response helpers (`nitr.text`,
7//! `nitr.html`, `nitr.redirect`, `nitr.status`, `nitr.error`),
8//! request/response cookies with HMAC-SHA256 signed variants, and content
9//! negotiation (`nitr.negotiate`).
10//!
11//! Helpers build plain `{status, headers, body}` response tables — they are
12//! sugar, not a new type — plus a `cookies` builder consumed by the server
13//! when the response is converted.
14
15use std::sync::Mutex;
16
17use base64::Engine as _;
18use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
19use hmac::{Hmac, Mac as _};
20use mlua::{
21    ExternalResult as _, Function, Lua, MetaMethod, ObjectLike as _, Table, UserData,
22    UserDataMethods, Value,
23};
24use sha2::Sha256;
25
26type HmacSha256 = Hmac<Sha256>;
27
28/// Builds the skeleton of a helper response table: status, empty headers,
29/// and an attached [`ResponseCookies`] builder.
30pub(crate) fn response_table(lua: &Lua, status: u16) -> mlua::Result<Table> {
31    let table = lua.create_table()?;
32    table.set("status", status)?;
33    table.set("headers", lua.create_table()?)?;
34    table.set("cookies", ResponseCookies::default())?;
35    Ok(table)
36}
37
38fn set_content_type(table: &Table, value: &str) -> mlua::Result<()> {
39    table.get::<Table>("headers")?.set("Content-Type", value)
40}
41
42/// Registers the HTTP ergonomics helpers on the `nitr` namespace table:
43/// `nitr.text`, `nitr.html`, `nitr.redirect`, `nitr.status`,
44/// `nitr.negotiate`, `nitr.sse`, and `nitr.error`.
45pub(crate) fn register(lua: &Lua, nitr: &Table) -> mlua::Result<()> {
46    nitr.set(
47        "text",
48        lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
49            let table = response_table(lua, status.unwrap_or(200))?;
50            set_content_type(&table, "text/plain; charset=utf-8")?;
51            table.set("body", body)?;
52            Ok(table)
53        })?,
54    )?;
55
56    nitr.set(
57        "html",
58        lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
59            let table = response_table(lua, status.unwrap_or(200))?;
60            set_content_type(&table, "text/html; charset=utf-8")?;
61            table.set("body", body)?;
62            Ok(table)
63        })?,
64    )?;
65
66    nitr.set(
67        "redirect",
68        lua.create_function(|lua, (location, status): (String, Option<u16>)| {
69            let table = response_table(lua, status.unwrap_or(302))?;
70            table.get::<Table>("headers")?.set("Location", location)?;
71            Ok(table)
72        })?,
73    )?;
74
75    nitr.set(
76        "status",
77        lua.create_function(|lua, code: u16| response_table(lua, code))?,
78    )?;
79
80    // Server-Sent Events: `sse(function(send) ... end)` builds a streaming
81    // response whose body hands the user function a `send(event, data)`
82    // formatter over the raw stream writer.
83    nitr.set(
84        "sse",
85        lua.create_function(|lua, handler: Function| {
86            let table = response_table(lua, 200)?;
87            let headers = table.get::<Table>("headers")?;
88            headers.set("Content-Type", "text/event-stream")?;
89            headers.set("Cache-Control", "no-cache")?;
90
91            let body = lua.create_async_function(move |lua, writer: mlua::AnyUserData| {
92                let handler = handler.clone();
93                async move {
94                    let send =
95                        lua.create_async_function(move |_, (event, data): (String, Value)| {
96                            let writer = writer.clone();
97                            async move {
98                                writer
99                                    .call_async_method::<()>("write", format_event(&event, data)?)
100                                    .await
101                            }
102                        })?;
103                    handler.call_async::<()>(send).await
104                }
105            })?;
106            table.set("body", body)?;
107            Ok(table)
108        })?,
109    )?;
110
111    nitr.set(
112        "negotiate",
113        lua.create_async_function(|lua, (req, offers): (Value, Table)| async move {
114            negotiate(&lua, req, offers).await
115        })?,
116    )?;
117
118    nitr.set(
119        "error",
120        lua.create_function(|lua, (code, body): (u16, Option<Value>)| {
121            let table = response_table(lua, code)?;
122            match body {
123                None => {}
124                Some(Value::String(s)) => {
125                    set_content_type(&table, "text/plain; charset=utf-8")?;
126                    table.set("body", s)?;
127                }
128                // A table body renders as JSON, e.g. `{ code = "NOT_FOUND" }`.
129                Some(Value::Table(t)) => {
130                    let t = Value::Table(t);
131                    crate::utils::check_json_depth(&t)?;
132                    let body = serde_json::to_string(&t).into_lua_err()?;
133                    set_content_type(&table, "application/json")?;
134                    table.set("body", body)?;
135                }
136                Some(other) => {
137                    return Err(mlua::Error::RuntimeError(format!(
138                        "nitr.error body must be a string or a table, got {}",
139                        other.type_name()
140                    )));
141                }
142            }
143            Ok(table)
144        })?,
145    )?;
146
147    // nitr.etag(value) — a validator for a dynamic response.
148    //
149    // Static files get conditional requests for free; dynamic ones cannot,
150    // because only the application knows what identifies a resource. This
151    // turns whatever it names — a row version, an updated_at, a rendered
152    // body — into a well-formed entity tag, so `req:fresh()` has something
153    // exact to compare against.
154    nitr.set(
155        "etag",
156        lua.create_function(|lua, (value, weak): (Value, Option<bool>)| {
157            let bytes = match &value {
158                Value::String(s) => s.as_bytes().to_vec(),
159                Value::Integer(n) => n.to_string().into_bytes(),
160                Value::Number(n) => n.to_string().into_bytes(),
161                other => {
162                    crate::utils::check_json_depth(other)?;
163                    serde_json::to_vec(other).into_lua_err()?
164                }
165            };
166            // Hashed rather than embedded verbatim: the input may contain
167            // anything, and a header value may not.
168            let digest = <Sha256 as sha2::Digest>::digest(&bytes);
169            let tag = digest[..8].iter().fold(String::new(), |mut acc, byte| {
170                use std::fmt::Write as _;
171                let _ = write!(acc, "{byte:02x}");
172                acc
173            });
174            let prefix = if weak.unwrap_or(false) { "W/" } else { "" };
175            lua.create_string(format!("{prefix}\"{tag}\""))
176        })?,
177    )?;
178
179    Ok(())
180}
181
182/// Formats one Server-Sent Event: string data is taken verbatim (split
183/// into one `data:` line per newline, per the SSE wire format); any other
184/// value is JSON-encoded.
185fn format_event(event: &str, data: Value) -> mlua::Result<String> {
186    let data = match data {
187        Value::String(s) => s.to_string_lossy().to_string(),
188        other => {
189            crate::utils::check_json_depth(&other)?;
190            serde_json::to_string(&other).into_lua_err()?
191        }
192    };
193    let mut out = format!("event: {event}\n");
194    for line in data.split('\n') {
195        out.push_str("data: ");
196        out.push_str(line);
197        out.push('\n');
198    }
199    out.push('\n');
200    Ok(out)
201}
202
203/// Picks the entry of `offers` whose key best matches the request's
204/// `Accept` header. A function value is called with the request; any other
205/// value is returned as-is. No acceptable entry yields a plain 406.
206async fn negotiate(lua: &Lua, req: Value, offers: Table) -> mlua::Result<Value> {
207    // Read the Accept header through the request's `headers` field so any
208    // request-like object (userdata or plain table) works.
209    let headers: Option<Table> = match &req {
210        Value::UserData(ud) => ud.get("headers").ok(),
211        Value::Table(t) => t.get("headers").ok(),
212        _ => None,
213    };
214    let accept = headers
215        .and_then(|h| h.get::<Option<String>>("accept").ok().flatten())
216        .unwrap_or_else(|| "*/*".to_string());
217
218    let mut offered = Vec::new();
219    let mut values = Vec::new();
220    for pair in offers.pairs::<String, Value>() {
221        let (media_type, value) = pair?;
222        offered.push(media_type);
223        values.push(value);
224    }
225
226    let offered_refs: Vec<&str> = offered.iter().map(String::as_str).collect();
227    match best_match(&accept, &offered_refs) {
228        Some(i) => match values.swap_remove(i) {
229            Value::Function(f) => f.call_async(req).await,
230            value => Ok(value),
231        },
232        None => {
233            let table = response_table(lua, 406)?;
234            set_content_type(&table, "text/plain; charset=utf-8")?;
235            table.set("body", "Not Acceptable")?;
236            Ok(Value::Table(table))
237        }
238    }
239}
240
241/// Picks the best of `offered` media types for an `Accept` header value,
242/// honoring q-values and `type/*` / `*/*` wildcards. More specific ranges
243/// win at equal quality; ties go to the earlier offer.
244pub fn best_match(accept: &str, offered: &[&str]) -> Option<usize> {
245    // (index, quality, specificity)
246    let mut best: Option<(usize, f32, u8)> = None;
247    for item in accept.split(',') {
248        let mut parts = item.trim().split(';');
249        let range = match parts.next() {
250            Some(r) if !r.trim().is_empty() => r.trim(),
251            _ => continue,
252        };
253        let mut q = 1.0_f32;
254        for param in parts {
255            if let Some(v) = param.trim().strip_prefix("q=") {
256                q = v.trim().parse().unwrap_or(0.0);
257            }
258        }
259        if q <= 0.0 {
260            continue;
261        }
262        for (i, offer) in offered.iter().enumerate() {
263            let specificity = if range.eq_ignore_ascii_case(offer) {
264                2
265            } else if range == "*/*" {
266                0
267            } else if let Some(main) = range.strip_suffix("/*") {
268                match offer.split('/').next() {
269                    Some(offer_main) if offer_main.eq_ignore_ascii_case(main) => 1,
270                    _ => continue,
271                }
272            } else {
273                continue;
274            };
275            let better = match best {
276                None => true,
277                Some((bi, bq, bs)) => {
278                    q > bq || (q == bq && (specificity > bs || (specificity == bs && i < bi)))
279                }
280            };
281            if better {
282                best = Some((i, q, specificity));
283            }
284        }
285    }
286    best.map(|(i, _, _)| i)
287}
288
289/// Cookies parsed from a request's `Cookie` header: values via indexing
290/// (`req.cookies.session`) and signed-cookie verification via
291/// `req.cookies:verify(name, secret)`.
292pub struct RequestCookies(Vec<(String, String)>);
293
294impl RequestCookies {
295    /// Parses a `Cookie` request header (an empty string yields no cookies).
296    pub fn parse(header: &str) -> Self {
297        Self(
298            cookie::Cookie::split_parse(header)
299                .flatten()
300                .map(|c| (c.name().to_string(), c.value().to_string()))
301                .collect(),
302        )
303    }
304
305    pub(crate) fn get(&self, name: &str) -> Option<&str> {
306        self.0
307            .iter()
308            .find(|(n, _)| n == name)
309            .map(|(_, v)| v.as_str())
310    }
311}
312
313impl UserData for RequestCookies {
314    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
315        methods.add_meta_method(MetaMethod::Index, |lua, this, name: Value| {
316            let Value::String(name) = name else {
317                return Ok(Value::Nil);
318            };
319            match this.get(&name.to_string_lossy()) {
320                Some(v) => Ok(Value::String(lua.create_string(v)?)),
321                None => Ok(Value::Nil),
322            }
323        });
324
325        // Returns the verified value of a signed cookie, or nil when the
326        // cookie is missing, malformed, or its signature does not match.
327        methods.add_method(
328            "verify",
329            |lua, this, (name, secret): (String, String)| match this
330                .get(&name)
331                .and_then(|raw| verify(&name, raw, &secret))
332            {
333                Some(v) => Ok(Value::String(lua.create_string(v)?)),
334                None => Ok(Value::Nil),
335            },
336        );
337    }
338}
339
340/// Builder for response `Set-Cookie` headers, attached as the `cookies`
341/// field of helper-built response tables. The server serializes each entry
342/// into its own `Set-Cookie` header.
343#[derive(Default)]
344pub struct ResponseCookies(Mutex<Vec<String>>);
345
346impl ResponseCookies {
347    /// The serialized `Set-Cookie` values collected so far.
348    pub fn values(&self) -> Vec<String> {
349        self.0.lock().map(|v| v.clone()).unwrap_or_default()
350    }
351
352    fn push(&self, value: String) -> mlua::Result<()> {
353        self.0
354            .lock()
355            .map_err(|_| mlua::Error::RuntimeError("the cookie list lock is poisoned".into()))?
356            .push(value);
357        Ok(())
358    }
359}
360
361impl UserData for ResponseCookies {
362    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
363        methods.add_method(
364            "set",
365            |_, this, (name, value, opts): (String, String, Option<Table>)| {
366                this.push(build_cookie(&name, &value, opts.as_ref())?)
367            },
368        );
369
370        // Signs the value with HMAC-SHA256 so `req.cookies:verify(name,
371        // secret)` can authenticate it on later requests.
372        methods.add_method(
373            "set_signed",
374            |_, this, (name, value, secret, opts): (String, String, String, Option<Table>)| {
375                this.push(build_cookie(
376                    &name,
377                    &sign(&name, &value, &secret),
378                    opts.as_ref(),
379                )?)
380            },
381        );
382    }
383}
384
385/// Attaches a serialized `Set-Cookie` value to a handler response table:
386/// through its `cookies` builder when present (helper-built responses), or
387/// by creating one (hand-built plain tables), so the server's response
388/// conversion picks it up either way.
389pub(crate) fn attach_cookie(resp: &Table, cookie: String) -> mlua::Result<()> {
390    match resp.raw_get::<Value>("cookies")? {
391        Value::UserData(ud) => {
392            let cookies = ud.borrow::<ResponseCookies>().map_err(|_| {
393                mlua::Error::RuntimeError(
394                    "the response `cookies` field is not a cookie builder".into(),
395                )
396            })?;
397            cookies.push(cookie)
398        }
399        Value::Nil => {
400            let cookies = ResponseCookies::default();
401            cookies.push(cookie)?;
402            resp.set("cookies", cookies)
403        }
404        other => Err(mlua::Error::RuntimeError(format!(
405            "invalid `cookies` field of type `{}` in the response table",
406            other.type_name()
407        ))),
408    }
409}
410
411/// Serializes one cookie, applying the recognized options: `http_only`,
412/// `secure`, `path`, `domain`, `max_age` (seconds), `same_site`
413/// (`"Strict"` / `"Lax"` / `"None"`).
414pub(crate) fn build_cookie(name: &str, value: &str, opts: Option<&Table>) -> mlua::Result<String> {
415    let mut builder = cookie::Cookie::build((name.to_owned(), value.to_owned()));
416    if let Some(opts) = opts {
417        if opts.get::<Option<bool>>("http_only")?.unwrap_or(false) {
418            builder = builder.http_only(true);
419        }
420        if opts.get::<Option<bool>>("secure")?.unwrap_or(false) {
421            builder = builder.secure(true);
422        }
423        if let Some(path) = opts.get::<Option<String>>("path")? {
424            builder = builder.path(path);
425        }
426        if let Some(domain) = opts.get::<Option<String>>("domain")? {
427            builder = builder.domain(domain);
428        }
429        if let Some(secs) = opts.get::<Option<i64>>("max_age")? {
430            builder = builder.max_age(cookie::time::Duration::seconds(secs));
431        }
432        if let Some(same_site) = opts.get::<Option<String>>("same_site")? {
433            builder = builder.same_site(match same_site.to_ascii_lowercase().as_str() {
434                "strict" => cookie::SameSite::Strict,
435                "lax" => cookie::SameSite::Lax,
436                "none" => cookie::SameSite::None,
437                other => {
438                    return Err(mlua::Error::RuntimeError(format!(
439                        "invalid same_site value `{other}`: expected Strict, Lax or None"
440                    )));
441                }
442            });
443        }
444    }
445    Ok(builder.build().to_string())
446}
447
448/// Encodes and signs a cookie value: `b64(value) . b64(hmac)`, with the
449/// cookie name bound into the MAC so values cannot be swapped between
450/// cookies.
451pub fn sign(name: &str, value: &str, secret: &str) -> String {
452    let payload = B64.encode(value);
453    format!(
454        "{payload}.{}",
455        B64.encode(mac_bytes(name, &payload, secret))
456    )
457}
458
459/// Verifies a value produced by [`sign()`]; the MAC comparison is
460/// constant-time (`hmac::Mac::verify_slice`).
461pub fn verify(name: &str, signed: &str, secret: &str) -> Option<String> {
462    let (payload, sig) = signed.rsplit_once('.')?;
463    let sig = B64.decode(sig).ok()?;
464    new_mac(name, payload, secret).verify_slice(&sig).ok()?;
465    String::from_utf8(B64.decode(payload).ok()?).ok()
466}
467
468fn new_mac(name: &str, payload: &str, secret: &str) -> HmacSha256 {
469    let mut mac: HmacSha256 = crate::utils::new_hmac(secret.as_bytes());
470    mac.update(name.as_bytes());
471    mac.update(b"=");
472    mac.update(payload.as_bytes());
473    mac
474}
475
476fn mac_bytes(name: &str, payload: &str, secret: &str) -> Vec<u8> {
477    new_mac(name, payload, secret)
478        .finalize()
479        .into_bytes()
480        .to_vec()
481}
482
483#[cfg(test)]
484mod tests {
485    use super::*;
486
487    #[test]
488    fn signed_cookies_round_trip_and_reject_tampering() {
489        let signed = sign("session", "user-42", "s3cret");
490        assert_eq!(
491            verify("session", &signed, "s3cret").as_deref(),
492            Some("user-42")
493        );
494
495        // Wrong secret, wrong name (cookie swapping), tampered payload.
496        assert_eq!(verify("session", &signed, "other"), None);
497        assert_eq!(verify("tracking", &signed, "s3cret"), None);
498        let tampered = format!("x{signed}");
499        assert_eq!(verify("session", &tampered, "s3cret"), None);
500        assert_eq!(verify("session", "garbage", "s3cret"), None);
501    }
502
503    #[test]
504    fn cookies_serialize_their_options() {
505        let lua = mlua::Lua::new();
506        let opts: Table = lua
507            .load(r#"{ http_only = true, secure = true, same_site = "Lax", max_age = 3600, path = "/" }"#)
508            .eval()
509            .expect("opts table");
510        let cookie = build_cookie("session", "abc", Some(&opts)).expect("cookie");
511        for part in [
512            "session=abc",
513            "HttpOnly",
514            "Secure",
515            "SameSite=Lax",
516            "Max-Age=3600",
517            "Path=/",
518        ] {
519            assert!(cookie.contains(part), "`{cookie}` should contain `{part}`");
520        }
521    }
522
523    #[test]
524    fn accept_header_negotiation_honors_quality_and_wildcards() {
525        let offers = &["application/json", "text/html"];
526        // Explicit match wins over wildcard.
527        assert_eq!(best_match("text/html, */*;q=0.5", offers), Some(1));
528        // Quality ordering.
529        assert_eq!(
530            best_match("application/json;q=0.2, text/html;q=0.9", offers),
531            Some(1)
532        );
533        // type/* wildcard.
534        assert_eq!(best_match("text/*", offers), Some(1));
535        // */* falls back to the first offer.
536        assert_eq!(best_match("*/*", offers), Some(0));
537        // q=0 removes a candidate entirely.
538        assert_eq!(best_match("text/html;q=0", offers), None);
539        assert_eq!(best_match("image/png", offers), None);
540    }
541
542    proptest::proptest! {
543        /// Property: sign/verify round-trips arbitrary printable inputs,
544        /// and flipping any single character of the signed value breaks
545        /// it — as do the wrong secret and a swapped cookie name.
546        #[test]
547        fn prop_signed_cookies_round_trip_and_any_tamper_fails(
548            name in "[ -~]{1,16}",
549            value in "[ -~]{0,48}",
550            secret in "[ -~]{1,32}",
551            pos in proptest::prelude::any::<proptest::sample::Index>(),
552        ) {
553            let signed = sign(&name, &value, &secret);
554            let verified = verify(&name, &signed, &secret);
555            proptest::prop_assert_eq!(verified.as_deref(), Some(value.as_str()));
556
557            // One changed character anywhere — payload or MAC — must fail.
558            let pos = pos.index(signed.len());
559            let mut tampered: Vec<char> = signed.chars().collect();
560            tampered[pos] = if tampered[pos] == 'A' { 'B' } else { 'A' };
561            let tampered: String = tampered.into_iter().collect();
562            proptest::prop_assert_eq!(verify(&name, &tampered, &secret), None);
563
564            proptest::prop_assert_eq!(verify(&name, &signed, "other-secret"), None);
565            proptest::prop_assert_eq!(verify("other-name", &signed, &secret), None);
566        }
567    }
568}