Skip to main content

nitr_std/http/
mod.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 mlua::{ExternalResult as _, Function, Lua, ObjectLike as _, Table, Value};
16use sha2::Sha256;
17
18mod cookies;
19
20pub use cookies::{
21    CookieDefaults, RequestCookies, ResponseCookies, SetCookie, parse_set_cookie, sign, verify,
22};
23pub(crate) use cookies::{attach_cookie, build_cookie, merge_cookie_opts};
24
25/// Builds the skeleton of a helper response table: status, empty headers,
26/// and an attached [`ResponseCookies`] builder.
27pub fn response_table(lua: &Lua, status: u16) -> mlua::Result<Table> {
28    let table = lua.create_table()?;
29    table.set("status", status)?;
30    table.set("headers", lua.create_table()?)?;
31    table.set("cookies", ResponseCookies::default())?;
32    Ok(table)
33}
34
35fn set_content_type(table: &Table, value: &str) -> mlua::Result<()> {
36    table.get::<Table>("headers")?.set("Content-Type", value)
37}
38
39/// Registers the HTTP ergonomics helpers on the `nitr` namespace table:
40/// `nitr.text`, `nitr.html`, `nitr.redirect`, `nitr.status`,
41/// `nitr.negotiate`, `nitr.sse`, and `nitr.error`.
42pub(crate) fn register(lua: &Lua, nitr: &Table) -> mlua::Result<()> {
43    nitr.set(
44        "text",
45        lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
46            let table = response_table(lua, status.unwrap_or(200))?;
47            set_content_type(&table, "text/plain; charset=utf-8")?;
48            table.set("body", body)?;
49            Ok(table)
50        })?,
51    )?;
52
53    nitr.set(
54        "html",
55        lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
56            let table = response_table(lua, status.unwrap_or(200))?;
57            set_content_type(&table, "text/html; charset=utf-8")?;
58            table.set("body", body)?;
59            Ok(table)
60        })?,
61    )?;
62
63    nitr.set(
64        "redirect",
65        lua.create_function(|lua, (location, status): (String, Option<u16>)| {
66            let table = response_table(lua, status.unwrap_or(302))?;
67            table.get::<Table>("headers")?.set("Location", location)?;
68            Ok(table)
69        })?,
70    )?;
71
72    nitr.set(
73        "status",
74        lua.create_function(|lua, code: u16| response_table(lua, code))?,
75    )?;
76
77    // Server-Sent Events: `sse(function(send) ... end)` builds a streaming
78    // response whose body hands the user function a `send(event, data)`
79    // formatter over the raw stream writer.
80    nitr.set(
81        "sse",
82        lua.create_function(|lua, handler: Function| {
83            let table = response_table(lua, 200)?;
84            let headers = table.get::<Table>("headers")?;
85            headers.set("Content-Type", "text/event-stream")?;
86            headers.set("Cache-Control", "no-cache")?;
87
88            let body = lua.create_async_function(move |lua, writer: mlua::AnyUserData| {
89                let handler = handler.clone();
90                async move {
91                    let send =
92                        lua.create_async_function(move |_, (event, data): (String, Value)| {
93                            let writer = writer.clone();
94                            async move {
95                                writer
96                                    .call_async_method::<()>("write", format_event(&event, data)?)
97                                    .await
98                            }
99                        })?;
100                    handler.call_async::<()>(send).await
101                }
102            })?;
103            table.set("body", body)?;
104            Ok(table)
105        })?,
106    )?;
107
108    nitr.set(
109        "negotiate",
110        lua.create_async_function(|lua, (req, offers): (Value, Table)| async move {
111            negotiate(&lua, req, offers).await
112        })?,
113    )?;
114
115    nitr.set(
116        "error",
117        lua.create_function(|lua, (code, body): (u16, Option<Value>)| {
118            let table = response_table(lua, code)?;
119            match body {
120                None => {}
121                Some(Value::String(s)) => {
122                    set_content_type(&table, "text/plain; charset=utf-8")?;
123                    table.set("body", s)?;
124                }
125                // A table body renders as JSON, e.g. `{ code = "NOT_FOUND" }`.
126                Some(Value::Table(t)) => {
127                    let t = Value::Table(t);
128                    let body = crate::bounded::to_json_string(&t).into_lua_err()?;
129                    set_content_type(&table, "application/json")?;
130                    table.set("body", body)?;
131                }
132                Some(other) => {
133                    return Err(mlua::Error::RuntimeError(format!(
134                        "nitr.error body must be a string or a table, got {}",
135                        other.type_name()
136                    )));
137                }
138            }
139            Ok(table)
140        })?,
141    )?;
142
143    // nitr.etag(value) — a validator for a dynamic response.
144    //
145    // Static files get conditional requests for free; dynamic ones cannot,
146    // because only the application knows what identifies a resource. This
147    // turns whatever it names — a row version, an updated_at, a rendered
148    // body — into a well-formed entity tag, so `req:fresh()` has something
149    // exact to compare against.
150    nitr.set(
151        "etag",
152        lua.create_function(|lua, (value, weak): (Value, Option<bool>)| {
153            let bytes = match &value {
154                Value::String(s) => s.as_bytes().to_vec(),
155                Value::Integer(n) => n.to_string().into_bytes(),
156                Value::Number(n) => n.to_string().into_bytes(),
157                other => crate::bounded::to_json_vec(other).into_lua_err()?,
158            };
159            // Hashed rather than embedded verbatim: the input may contain
160            // anything, and a header value may not.
161            let digest = <Sha256 as sha2::Digest>::digest(&bytes);
162            let tag = digest[..8].iter().fold(String::new(), |mut acc, byte| {
163                use std::fmt::Write as _;
164                let _ = write!(acc, "{byte:02x}");
165                acc
166            });
167            let prefix = if weak.unwrap_or(false) { "W/" } else { "" };
168            lua.create_string(format!("{prefix}\"{tag}\""))
169        })?,
170    )?;
171
172    // nitr.cookie.sign / verify — the HMAC-SHA256 signing behind
173    // `res.cookies:set_signed` and `req.cookies:verify`, as plain
174    // functions: for a signed value that travels outside a cookie header,
175    // and for a test that forges a cookie (or a session) for a client jar.
176    let cookie = lua.create_table()?;
177    cookie.set(
178        "sign",
179        lua.create_function(|_, (name, value, secret): (String, String, String)| {
180            Ok(sign(&name, &value, &secret))
181        })?,
182    )?;
183    cookie.set(
184        "verify",
185        lua.create_function(
186            |lua, (name, signed, secret): (String, String, String)| match verify(
187                &name, &signed, &secret,
188            ) {
189                Some(value) => Ok(Value::String(lua.create_string(value)?)),
190                None => Ok(Value::Nil),
191            },
192        )?,
193    )?;
194    nitr.set("cookie", cookie)?;
195
196    Ok(())
197}
198
199/// Formats one Server-Sent Event: string data is taken verbatim (split
200/// into one `data:` line per line break, per the SSE wire format); any
201/// other value is JSON-encoded.
202///
203/// The event stream grammar ends a line at `\r\n`, `\n` *or a bare `\r`*,
204/// so data is split on all three — a `\r` left inside a `data:` line would
205/// let request text start a `retry:` or `event:` field of its own. The
206/// event name is one line by definition and is refused if it is not.
207fn format_event(event: &str, data: Value) -> mlua::Result<String> {
208    if event.contains(['\r', '\n']) {
209        return Err(mlua::Error::RuntimeError(
210            "an SSE event name cannot contain a line break".into(),
211        ));
212    }
213    let data = match data {
214        Value::String(s) => s.to_string_lossy().to_string(),
215        other => crate::bounded::to_json_string(&other).into_lua_err()?,
216    };
217    let mut out = format!("event: {event}\n");
218    for line in data.replace("\r\n", "\n").split(['\r', '\n']) {
219        out.push_str("data: ");
220        out.push_str(line);
221        out.push('\n');
222    }
223    out.push('\n');
224    Ok(out)
225}
226
227/// Picks the entry of `offers` whose key best matches the request's
228/// `Accept` header. A function value is called with the request; any other
229/// value is returned as-is. No acceptable entry yields a plain 406.
230async fn negotiate(lua: &Lua, req: Value, offers: Table) -> mlua::Result<Value> {
231    // Read the Accept header through the request's `headers` field so any
232    // request-like object (userdata or plain table) works.
233    let headers: Option<Table> = match &req {
234        Value::UserData(ud) => ud.get("headers").ok(),
235        Value::Table(t) => t.get("headers").ok(),
236        _ => None,
237    };
238    let accept = headers
239        .and_then(|h| h.get::<Option<String>>("accept").ok().flatten())
240        .unwrap_or_else(|| "*/*".to_string());
241
242    let (offered, mut values) = offer_list(&offers)?;
243
244    let offered_refs: Vec<&str> = offered.iter().map(String::as_str).collect();
245    match best_match(&accept, &offered_refs) {
246        Some(i) => match values.swap_remove(i) {
247            Value::Function(f) => f.call_async(req).await,
248            value => Ok(value),
249        },
250        None => {
251            let table = response_table(lua, 406)?;
252            set_content_type(&table, "text/plain; charset=utf-8")?;
253            table.set("body", "Not Acceptable")?;
254            Ok(Value::Table(table))
255        }
256    }
257}
258
259/// The offers in tie-breaking order, from either shape: a list
260/// `{ { type, value }, ... }` keeps its order; a map `{ [type] = value }`
261/// is sorted by type, because Lua seeds its string hashes per state and a
262/// map's own order would differ between pooled states.
263fn offer_list(offers: &Table) -> mlua::Result<(Vec<String>, Vec<Value>)> {
264    let mut pairs = Vec::new();
265    if offers.raw_len() > 0 {
266        for offer in offers.sequence_values::<Table>() {
267            let offer = offer?;
268            pairs.push((offer.raw_get::<String>(1)?, offer.raw_get::<Value>(2)?));
269        }
270    } else {
271        for pair in offers.pairs::<String, Value>() {
272            pairs.push(pair?);
273        }
274        pairs.sort_by(|a, b| a.0.cmp(&b.0));
275    }
276    Ok(pairs.into_iter().unzip())
277}
278
279/// Picks the best of `offered` media types for an `Accept` header value,
280/// honoring q-values and `type/*` / `*/*` wildcards. More specific ranges
281/// win at equal quality; ties go to the earlier offer.
282pub fn best_match(accept: &str, offered: &[&str]) -> Option<usize> {
283    // (index, quality, specificity)
284    let mut best: Option<(usize, f32, u8)> = None;
285    for item in accept.split(',') {
286        let mut parts = item.trim().split(';');
287        let range = match parts.next() {
288            Some(r) if !r.trim().is_empty() => r.trim(),
289            _ => continue,
290        };
291        let mut q = 1.0_f32;
292        for param in parts {
293            if let Some(v) = param.trim().strip_prefix("q=") {
294                q = v.trim().parse().unwrap_or(0.0);
295            }
296        }
297        if q <= 0.0 {
298            continue;
299        }
300        for (i, offer) in offered.iter().enumerate() {
301            let specificity = if range.eq_ignore_ascii_case(offer) {
302                2
303            } else if range == "*/*" {
304                0
305            } else if let Some(main) = range.strip_suffix("/*") {
306                match offer.split('/').next() {
307                    Some(offer_main) if offer_main.eq_ignore_ascii_case(main) => 1,
308                    _ => continue,
309                }
310            } else {
311                continue;
312            };
313            let better = match best {
314                None => true,
315                Some((bi, bq, bs)) => {
316                    q > bq || (q == bq && (specificity > bs || (specificity == bs && i < bi)))
317                }
318            };
319            if better {
320                best = Some((i, q, specificity));
321            }
322        }
323    }
324    best.map(|(i, _, _)| i)
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    /// Every line terminator the SSE grammar knows splits data, so no
332    /// value can inject a field; the event name is a single line.
333    #[test]
334    fn sse_framing_cannot_be_broken_out_of() {
335        let lua = Lua::new();
336        let data = |s: &str| Value::String(lua.create_string(s).expect("string"));
337        assert_eq!(
338            format_event("msg", data("hi\rretry: 1\revent: admin")).expect("event"),
339            "event: msg\ndata: hi\ndata: retry: 1\ndata: event: admin\n\n"
340        );
341        assert_eq!(
342            format_event("msg", data("a\r\nb\nc")).expect("event"),
343            "event: msg\ndata: a\ndata: b\ndata: c\n\n"
344        );
345        assert!(format_event("x\nretry: 1", data("d")).is_err());
346        assert!(format_event("x\r", data("d")).is_err());
347    }
348
349    /// Lua seeds its string hashes per state, so a map's key order differs
350    /// between pooled states: a tie must not depend on it. Offers given as
351    /// a list keep their order, and ties go to the earlier one.
352    #[tokio::test]
353    async fn negotiation_ties_are_the_same_in_every_state() {
354        for _ in 0..32 {
355            let lua = Lua::new();
356            let req: Value = lua
357                .load("{ headers = { accept = '*/*' } }")
358                .eval()
359                .expect("req");
360            let map: Table = lua
361                .load("{ ['text/html'] = 'html', ['application/json'] = 'json', ['text/plain'] = 'text' }")
362                .eval()
363                .expect("offers");
364            let picked = negotiate(&lua, req.clone(), map).await.expect("negotiate");
365            assert_eq!(picked.as_string().expect("string"), "json");
366
367            let list: Table = lua
368                .load("{ { 'text/html', 'html' }, { 'application/json', 'json' } }")
369                .eval()
370                .expect("offers");
371            let picked = negotiate(&lua, req, list).await.expect("negotiate");
372            assert_eq!(picked.as_string().expect("string"), "html");
373        }
374    }
375
376    #[test]
377    fn accept_header_negotiation_honors_quality_and_wildcards() {
378        let offers = &["application/json", "text/html"];
379        // Explicit match wins over wildcard.
380        assert_eq!(best_match("text/html, */*;q=0.5", offers), Some(1));
381        // Quality ordering.
382        assert_eq!(
383            best_match("application/json;q=0.2, text/html;q=0.9", offers),
384            Some(1)
385        );
386        // type/* wildcard.
387        assert_eq!(best_match("text/*", offers), Some(1));
388        // */* falls back to the first offer.
389        assert_eq!(best_match("*/*", offers), Some(0));
390        // q=0 removes a candidate entirely.
391        assert_eq!(best_match("text/html;q=0", offers), None);
392        assert_eq!(best_match("image/png", offers), None);
393    }
394}