1use mlua::{Function, Lua, Value};
7
8pub(crate) fn new_hmac<M: hmac::digest::KeyInit>(key: &[u8]) -> M {
16 #[allow(clippy::expect_used)]
19 <M as hmac::digest::KeyInit>::new_from_slice(key).expect("HMAC accepts any key length")
20}
21
22pub(crate) const MAX_JSON_DEPTH: usize = 128;
34
35pub(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 table.for_each(|key: Value, item: Value| {
61 depth_walk(&key, remaining - 1)?;
62 depth_walk(&item, remaining - 1)
63 })
64}
65
66pub(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
74pub 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 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
117fn 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
124fn 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 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
151pub(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 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 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 assert!(check_json_depth(&Value::Integer(7)).is_ok());
244 }
245
246 #[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 #[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}