Skip to main content

nitr_std/
utils.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
6use mlua::{Function, Lua, Value};
7
8/// Builds an HMAC instance from a key of any length.
9///
10/// The single home of the "HMAC accepts any key length" invariant:
11/// `new_from_slice` is fallible only for fixed-key-length algorithms,
12/// which HMAC is not, so the `expect` cannot fire. Every MAC in the crate
13/// (signed cookies, `nitr.crypto.hmac_sha256`, JWT) constructs through
14/// here so key handling has one auditable site.
15pub(crate) fn new_hmac<M: hmac::digest::KeyInit>(key: &[u8]) -> M {
16    // Invariant: `new_from_slice` fails only for fixed-key-length
17    // algorithms, which HMAC is not.
18    #[allow(clippy::expect_used)]
19    <M as hmac::digest::KeyInit>::new_from_slice(key).expect("HMAC accepts any key length")
20}
21
22/// The deepest nesting a Lua value may have before it is serialized to
23/// JSON, deliberately mirroring serde_json's *deserialization* recursion
24/// limit so the two directions share one documented bound.
25///
26/// The limit exists because serialization has none of its own: serde_json
27/// recurses once per nesting level, and a script can build a table chain
28/// deep enough to overflow the Rust stack well within its Lua memory
29/// budget (verified empirically: ~30,000 levels aborts the process with
30/// SIGABRT on a default tokio worker stack). A stack overflow is an
31/// abort, not a panic — the containment boundary cannot catch
32/// it, so the bound must hold *before* a serializer recurses.
33pub(crate) const MAX_JSON_DEPTH: usize = 128;
34
35/// Refuses a value nested deeper than [`MAX_JSON_DEPTH`] with an ordinary
36/// catchable error, before any serializer recurses over it.
37///
38/// Every Lua-value-to-JSON site in the crate calls this first.
39/// `nitr.json` encoding and the JSON response helper, `cache:set` /
40/// `cache:remember`, `fetch` JSON bodies, JWT claims, sessions, SSE data,
41/// `nitr.etag`, `nitr.error` table bodies, and log fields, so the bound
42/// has one auditable home. The walk itself recurses, but its depth is
43/// capped by the very bound it enforces; a cyclic table is infinitely
44/// deep and reports the same error instead of hanging.
45pub(crate) fn check_json_depth(value: &Value) -> mlua::Result<()> {
46    depth_walk(value, MAX_JSON_DEPTH)
47}
48
49fn depth_walk(value: &Value, remaining: usize) -> mlua::Result<()> {
50    let Value::Table(table) = value else {
51        return Ok(());
52    };
53    if remaining == 0 {
54        return Err(mlua::Error::RuntimeError(format!(
55            "json value nested deeper than {MAX_JSON_DEPTH} levels"
56        )));
57    }
58    // Raw iteration, matching what serialization will walk; keys can be
59    // tables too, and a deep key must not slip past the check.
60    table.for_each(|key: Value, item: Value| {
61        depth_walk(&key, remaining - 1)?;
62        depth_walk(&item, remaining - 1)
63    })
64}
65
66/// Debug function.
67pub(crate) fn create_debug_fn(lua: &Lua) -> mlua::Result<Function> {
68    lua.create_function(|_, value: Value| {
69        tracing::debug!("[lua] {value:#?}");
70        Ok(())
71    })
72}
73
74/// Builds the structured error value the error model hands to Lua: the
75/// table `on_error` receives and `nitr.errinfo` returns. A plain table (it
76/// serializes to JSON for free) that stringifies — and concatenates — as
77/// the concise `kind: message (source:line)` form via a cached metatable.
78pub fn error_lua_value(lua: &Lua, info: &nitr_core::ErrorInfo) -> mlua::Result<mlua::Table> {
79    let t = lua.create_table()?;
80    t.raw_set("message", info.message.as_str())?;
81    t.raw_set("kind", info.kind)?;
82    if let Some(source) = &info.source {
83        t.raw_set("source", source.as_str())?;
84    }
85    if let Some(line) = info.line {
86        t.raw_set("line", line)?;
87    }
88    if let Some(module) = &info.module {
89        t.raw_set("module", module.as_str())?;
90    }
91    if let Some(traceback) = &info.traceback {
92        t.raw_set("traceback", traceback.as_str())?;
93    }
94    if !info.cause.is_empty() {
95        let causes = lua.create_table_from(
96            info.cause
97                .iter()
98                .enumerate()
99                .map(|(i, c)| (i + 1, c.as_str())),
100        )?;
101        t.raw_set("cause", causes)?;
102    }
103    t.raw_set("__concise", info.concise())?;
104    // For console prints: ANSI-colored on a terminal, identical to the
105    // concise form otherwise. `tostring`/`..` stay plain deliberately —
106    // those strings may end up in HTTP bodies and log files.
107    let pretty = if console_wants_color() {
108        info.concise_colored()
109    } else {
110        info.concise()
111    };
112    t.raw_set("pretty", pretty)?;
113    t.set_metatable(Some(error_metatable(lua)?))?;
114    Ok(t)
115}
116
117/// Whether `print`-style console output should carry color: stdout is a
118/// terminal and `NO_COLOR` is unset.
119fn console_wants_color() -> bool {
120    use std::io::IsTerminal as _;
121    std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
122}
123
124/// The shared metatable for error values, built once per state:
125/// `__tostring` for `tostring(err)` and `__concat` so `"prefix: " .. err`
126/// works directly in a log line.
127fn error_metatable(lua: &Lua) -> mlua::Result<mlua::Table> {
128    if let Ok(mt) = lua.named_registry_value::<mlua::Table>("nitr.error_mt") {
129        return Ok(mt);
130    }
131    let mt = lua.create_table()?;
132    mt.set(
133        "__tostring",
134        lua.create_function(|_, t: mlua::Table| t.raw_get::<String>("__concise"))?,
135    )?;
136    // Either operand may be the error value; Lua's own `tostring` applies
137    // the `__tostring` above for whichever side is.
138    mt.set(
139        "__concat",
140        lua.create_function(|lua, (a, b): (Value, Value)| {
141            let tostring: Function = lua.globals().get("tostring")?;
142            let a: String = tostring.call(a)?;
143            let b: String = tostring.call(b)?;
144            Ok(a + &b)
145        })?,
146    )?;
147    lua.set_named_registry_value("nitr.error_mt", &mt)?;
148    Ok(mt)
149}
150
151/// `nitr.errinfo(err)`: classifies whatever `pcall` caught into the same
152/// structured error value `on_error` receives. A Rust-side error arrives
153/// with its full chain (`Value::Error`); a Lua error arrives as a
154/// position-prefixed string; anything else is stringified. Idempotent on
155/// values that are already structured.
156pub(crate) fn create_errinfo_fn(lua: &Lua) -> mlua::Result<Function> {
157    lua.create_function(|lua, value: Value| {
158        let info = match &value {
159            Value::Error(err) => {
160                nitr_core::ErrorInfo::from_error(&nitr_core::Error::Lua((**err).clone()))
161            }
162            Value::String(s) => nitr_core::ErrorInfo::from_message(&s.to_string_lossy()),
163            Value::Table(t) if t.raw_get::<Option<String>>("__concise")?.is_some() => {
164                return Ok(t.clone());
165            }
166            other => {
167                let tostring: Function = lua.globals().get("tostring")?;
168                let text: String = tostring.call(other)?;
169                nitr_core::ErrorInfo::from_message(&text)
170            }
171        };
172        error_lua_value(lua, &info)
173    })
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn error_values_stringify_and_concatenate_as_the_concise_form() {
182        let lua = Lua::new();
183        let info = nitr_core::ErrorInfo::from_message("app.lua:7: boom");
184        let err = error_lua_value(&lua, &info).expect("value");
185        lua.globals().set("err", err).expect("set");
186
187        let (text, concat, message, line): (String, String, String, u32) = lua
188            .load(r#"return tostring(err), "got: " .. err, err.message, err.line"#)
189            .eval()
190            .expect("eval");
191        assert!(text.contains("boom"), "tostring: {text}");
192        assert!(text.contains("app.lua:7"), "tostring: {text}");
193        assert_eq!(concat, format!("got: {text}"));
194        assert_eq!(message, "boom");
195        assert_eq!(line, 7);
196    }
197
198    #[test]
199    fn errinfo_classifies_and_is_idempotent() {
200        let lua = Lua::new();
201        lua.globals()
202            .set("errinfo", create_errinfo_fn(&lua).expect("fn"))
203            .expect("set");
204        let (message, kind, twice_same): (String, String, bool) = lua
205            .load(
206                // `error(msg, 0)`: no position prefix, so the message is
207                // exactly what the script raised.
208                r#"local ok, caught = pcall(function() error("nope", 0) end)
209                   assert(not ok)
210                   local info = errinfo(caught)
211                   local again = errinfo(info)
212                   return info.message, info.kind, rawequal(info, again)"#,
213            )
214            .eval()
215            .expect("eval");
216        assert_eq!(message, "nope");
217        assert_eq!(kind, "lua");
218        assert!(twice_same, "a structured value passes through unchanged");
219    }
220
221    /// A chain of `depth` nested tables (the root included).
222    fn deep_table(lua: &Lua, depth: usize) -> Value {
223        let root = lua.create_table().expect("table");
224        let mut cur = root.clone();
225        for _ in 1..depth {
226            let next = lua.create_table().expect("table");
227            cur.set("x", next.clone()).expect("set");
228            cur = next;
229        }
230        Value::Table(root)
231    }
232
233    #[test]
234    fn json_depth_boundary_is_exact() {
235        let lua = Lua::new();
236        assert!(check_json_depth(&deep_table(&lua, MAX_JSON_DEPTH)).is_ok());
237        let err = check_json_depth(&deep_table(&lua, MAX_JSON_DEPTH + 1)).expect_err("129 deep");
238        assert!(
239            err.to_string().contains("nested deeper than 128 levels"),
240            "got: {err}"
241        );
242        // Scalars and shallow values pass untouched.
243        assert!(check_json_depth(&Value::Integer(7)).is_ok());
244    }
245
246    /// A cyclic table is infinitely deep: the walk must report the depth
247    /// error, not hang or overflow.
248    #[test]
249    fn a_cyclic_table_reports_depth_instead_of_hanging() {
250        let lua = Lua::new();
251        let t = lua.create_table().expect("table");
252        t.set("me", t.clone()).expect("set");
253        let err = check_json_depth(&Value::Table(t)).expect_err("cycle");
254        assert!(err.to_string().contains("nested deeper"), "got: {err}");
255    }
256
257    /// Lua table keys can be tables too; a deep *key* must not slip past
258    /// the check and recurse in the serializer instead.
259    #[test]
260    fn deep_table_keys_are_bounded_too() {
261        let lua = Lua::new();
262        let outer = lua.create_table().expect("table");
263        outer
264            .set(deep_table(&lua, MAX_JSON_DEPTH), true)
265            .expect("set");
266        assert!(check_json_depth(&Value::Table(outer)).is_err());
267    }
268}