use mlua::{Function, Lua, Value};
pub(crate) fn new_hmac<M: hmac::digest::KeyInit>(key: &[u8]) -> M {
#[allow(clippy::expect_used)]
<M as hmac::digest::KeyInit>::new_from_slice(key).expect("HMAC accepts any key length")
}
pub(crate) const MAX_JSON_DEPTH: usize = 128;
pub(crate) const MAX_JSON_NODES: usize = 1_000_000;
pub fn check_json_bounds(value: &Value) -> mlua::Result<()> {
let mut budget = MAX_JSON_NODES;
depth_walk(value, MAX_JSON_DEPTH, &mut budget, true)
}
pub(crate) fn nodes_message() -> String {
format!(
"json value expands to more than {MAX_JSON_NODES} nodes (a shared subtree \
counts once per path to it)"
)
}
pub(crate) fn depth_message() -> String {
format!("json value nested deeper than {MAX_JSON_DEPTH} levels")
}
pub(crate) fn utf8_message() -> String {
"json value contains a string that is not valid UTF-8: encode binary data \
first (nitr.base64.encode)"
.into()
}
pub(crate) fn check_value_bounds(value: &Value) -> mlua::Result<()> {
let mut budget = MAX_JSON_NODES;
depth_walk(value, MAX_JSON_DEPTH, &mut budget, false)
}
fn depth_walk(
value: &Value,
remaining: usize,
budget: &mut usize,
strict_utf8: bool,
) -> mlua::Result<()> {
if *budget == 0 {
return Err(mlua::Error::RuntimeError(nodes_message()));
}
*budget -= 1;
if strict_utf8
&& let Value::String(s) = value
&& s.to_str().is_err()
{
return Err(mlua::Error::RuntimeError(utf8_message()));
}
let Value::Table(table) = value else {
return Ok(());
};
if remaining == 0 {
return Err(mlua::Error::RuntimeError(depth_message()));
}
table.for_each(|key: Value, item: Value| {
depth_walk(&key, remaining - 1, budget, strict_utf8)?;
depth_walk(&item, remaining - 1, budget, strict_utf8)
})
}
#[cfg(test)]
pub(crate) fn deep_table(lua: &Lua, depth: usize) -> Value {
let root = lua.create_table().expect("table");
let mut cur = root.clone();
for _ in 1..depth {
let next = lua.create_table().expect("table");
cur.set("x", next.clone()).expect("set");
cur = next;
}
Value::Table(root)
}
#[cfg(test)]
pub(crate) fn dag_table(lua: &Lua, levels: usize) -> Value {
let mut cur = lua.create_table().expect("table");
for _ in 0..levels {
let next = lua.create_table().expect("table");
next.set("a", cur.clone()).expect("set");
next.set("b", cur.clone()).expect("set");
cur = next;
}
Value::Table(cur)
}
pub(crate) fn create_debug_fn(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|_, value: Value| {
log_debug_value(&value);
Ok(value)
})
}
fn log_debug_value(value: &Value) {
if !tracing::enabled!(tracing::Level::DEBUG) {
return;
}
match check_value_bounds(value) {
Ok(()) => tracing::debug!("[lua] {value:#?}"),
Err(err) => tracing::debug!("[lua] <value not rendered: {err}>"),
}
}
pub fn error_lua_value(lua: &Lua, info: &nitr_core::ErrorInfo) -> mlua::Result<mlua::Table> {
let t = lua.create_table()?;
t.raw_set("message", info.message.as_str())?;
t.raw_set("kind", info.kind)?;
if let Some(source) = &info.source {
t.raw_set("source", source.as_str())?;
}
if let Some(line) = info.line {
t.raw_set("line", line)?;
}
if let Some(module) = &info.module {
t.raw_set("module", module.as_str())?;
}
if let Some(traceback) = &info.traceback {
t.raw_set("traceback", traceback.as_str())?;
}
if !info.cause.is_empty() {
let causes = lua.create_table_from(
info.cause
.iter()
.enumerate()
.map(|(i, c)| (i + 1, c.as_str())),
)?;
t.raw_set("cause", causes)?;
}
t.raw_set("__concise", info.concise())?;
let pretty = if console_wants_color() {
info.concise_colored()
} else {
info.concise()
};
t.raw_set("pretty", pretty)?;
t.set_metatable(Some(error_metatable(lua)?))?;
Ok(t)
}
fn console_wants_color() -> bool {
static WANTS_COLOR: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*WANTS_COLOR.get_or_init(|| {
use std::io::IsTerminal as _;
std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
})
}
fn error_metatable(lua: &Lua) -> mlua::Result<mlua::Table> {
if let Ok(mt) = lua.named_registry_value::<mlua::Table>("nitr.error_mt") {
return Ok(mt);
}
let mt = lua.create_table()?;
mt.set(
"__tostring",
lua.create_function(|_, t: mlua::Table| t.raw_get::<String>("__concise"))?,
)?;
mt.set(
"__concat",
lua.create_function(|lua, (a, b): (Value, Value)| {
let tostring: Function = lua.globals().get("tostring")?;
let a: String = tostring.call(a)?;
let b: String = tostring.call(b)?;
Ok(a + &b)
})?,
)?;
lua.set_named_registry_value("nitr.error_mt", &mt)?;
Ok(mt)
}
pub(crate) fn create_errinfo_fn(lua: &Lua) -> mlua::Result<Function> {
lua.create_function(|lua, value: Value| {
let info = match &value {
Value::Error(err) => {
nitr_core::ErrorInfo::from_error(&nitr_core::Error::Lua((**err).clone()))
}
Value::String(s) => nitr_core::ErrorInfo::from_message(&s.to_string_lossy()),
Value::Table(t) if t.raw_get::<Option<String>>("__concise")?.is_some() => {
return Ok(t.clone());
}
other => {
let tostring: Function = lua.globals().get("tostring")?;
let text: String = tostring.call(other)?;
nitr_core::ErrorInfo::from_message(&text)
}
};
error_lua_value(lua, &info)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_values_stringify_and_concatenate_as_the_concise_form() {
let lua = Lua::new();
let info = nitr_core::ErrorInfo::from_message("app.lua:7: boom");
let err = error_lua_value(&lua, &info).expect("value");
lua.globals().set("err", err).expect("set");
let (text, concat, message, line): (String, String, String, u32) = lua
.load(r#"return tostring(err), "got: " .. err, err.message, err.line"#)
.eval()
.expect("eval");
assert!(text.contains("boom"), "tostring: {text}");
assert!(text.contains("app.lua:7"), "tostring: {text}");
assert_eq!(concat, format!("got: {text}"));
assert_eq!(message, "boom");
assert_eq!(line, 7);
}
#[test]
fn errinfo_classifies_and_is_idempotent() {
let lua = Lua::new();
lua.globals()
.set("errinfo", create_errinfo_fn(&lua).expect("fn"))
.expect("set");
let (message, kind, twice_same): (String, String, bool) = lua
.load(
r#"local ok, caught = pcall(function() error("nope", 0) end)
assert(not ok)
local info = errinfo(caught)
local again = errinfo(info)
return info.message, info.kind, rawequal(info, again)"#,
)
.eval()
.expect("eval");
assert_eq!(message, "nope");
assert_eq!(kind, "lua");
assert!(twice_same, "a structured value passes through unchanged");
}
#[test]
fn binary_strings_are_refused_not_serialized_as_byte_arrays() {
let lua = Lua::new();
let raw = lua.create_string(b"\xff\xfe").expect("string");
let err = check_json_bounds(&Value::String(raw.clone())).expect_err("binary");
assert!(err.to_string().contains("UTF-8"), "got: {err}");
let nested = lua.create_table().expect("table");
nested.set("k", raw.clone()).expect("set");
assert!(check_json_bounds(&Value::Table(nested)).is_err());
let text = lua.create_string("caf\u{e9}").expect("string");
check_json_bounds(&Value::String(text)).expect("UTF-8 passes");
check_value_bounds(&Value::String(raw)).expect("dbg accepts binary");
}
#[test]
fn json_depth_boundary_is_exact() {
let lua = Lua::new();
assert!(check_json_bounds(&deep_table(&lua, MAX_JSON_DEPTH)).is_ok());
let err = check_json_bounds(&deep_table(&lua, MAX_JSON_DEPTH + 1)).expect_err("129 deep");
assert!(
err.to_string().contains("nested deeper than 128 levels"),
"got: {err}"
);
assert!(check_json_bounds(&Value::Integer(7)).is_ok());
}
#[test]
fn a_cyclic_table_reports_depth_instead_of_hanging() {
let lua = Lua::new();
let t = lua.create_table().expect("table");
t.set("me", t.clone()).expect("set");
let err = check_json_bounds(&Value::Table(t)).expect_err("cycle");
assert!(err.to_string().contains("nested deeper"), "got: {err}");
}
#[test]
fn a_shared_subtree_is_refused_by_node_count_not_depth() {
let lua = Lua::new();
let err = check_json_bounds(&dag_table(&lua, 21)).expect_err("21-level DAG");
assert!(
err.to_string().contains("expands to more than"),
"the node budget must be what refuses a DAG, not the depth bound: {err}"
);
check_json_bounds(&dag_table(&lua, 10)).expect("a 10-level DAG is ~2047 visits");
}
#[test]
fn dbg_returns_its_value() {
let lua = Lua::new();
lua.globals()
.set("dbg", create_debug_fn(&lua).expect("dbg"))
.expect("set");
let same: bool = lua
.load("local t = {} return dbg(t) == t and dbg(7) == 7")
.eval()
.expect("eval");
assert!(same);
}
#[test]
fn dbg_does_not_abort_on_a_deep_value() {
let lua = Lua::new();
let dbg = create_debug_fn(&lua).expect("dbg");
dbg.call::<Value>(deep_table(&lua, 30_000))
.expect("dbg must degrade, not abort and not raise");
dbg.call::<Value>(deep_table(&lua, 8))
.expect("an ordinary value still prints");
}
#[test]
fn deep_table_keys_are_bounded_too() {
let lua = Lua::new();
let outer = lua.create_table().expect("table");
outer
.set(deep_table(&lua, MAX_JSON_DEPTH), true)
.expect("set");
assert!(check_json_bounds(&Value::Table(outer)).is_err());
}
}