Skip to main content

yk_lua/
lib.rs

1//! The embedded Luau VM, and the sandbox around it.
2//!
3//! Everything here follows Roblox's published guidance for embedding Luau with
4//! untrusted code, because Roblox runs millions of hostile scripts on this
5//! exact VM and has written down what it took.
6//!
7//! **Library globals are read-only at the VM level.** `sandbox(true)` marks the
8//! library tables, the string metatable, and the global table readonly in a way
9//! that blocks `rawset` and `setmetatable` too, not just assignment. PUC Lua
10//! has no equivalent primitive, which is one reason yk chose Luau.
11//!
12//! **The unsafe libraries are never loaded.** Seven libraries are requested:
13//! `coroutine`, `table`, `string`, `math`, `utf8`, `bit32`, and `buffer`, so
14//! `os`, `io`, `package`, `debug`, and `ffi` do not exist. That is a whitelist:
15//! a blacklist leaves `package.loadlib` reachable, which is the documented
16//! escape. `os` is not on the list: Luau's `os` registers exactly `clock`,
17//! `date`, `difftime`, and `time`, with no `execute`, but the requirement is a
18//! whitelist with no dangerous library in it and `os` is on the list. It comes
19//! out.
20//!
21//! **Bytecode is never loaded.** `set_mode("t")` refuses binary chunks, which is
22//! the escape Lua workshop documented for 5.1.
23//!
24//! **A runaway script is stopped by an instruction limit.** The interrupt
25//! fires at any function call or loop iteration, and a counter bounds how many
26//! firings one execution may have. `while true do end` returns an error
27//! rather than wedging the agent. This is the other reason for Luau: `mlua`
28//! exposes no equivalent on PUC Lua.
29//!
30//! **Memory is capped.** The interrupt does not stop a script that allocates
31//! without calling anything.
32//!
33//! **The process gateway is `runner`.** An extension that needs a file, a
34//! network service, or another binary asks the host to run a process. The
35//! child is a separate OS process: isolated by the kernel, killable by the
36//! host, and unable to touch agent memory. There is no FFI, no `ffi` library,
37//! and no native module loading, in any dialect, ever.
38//!
39//! What this is *not*: a memory-isolated process. There is one heap per
40//! `lua_State`, not per script. The session survives a crash because it is
41//! append-only.
42
43mod host;
44mod runner;
45mod tool;
46
47use std::collections::BTreeMap;
48use std::ops::BitOr;
49use std::path::{Path, PathBuf};
50use std::sync::{Arc, Mutex};
51use std::time::{Duration, Instant};
52
53use mlua::{Lua, LuaSerdeExt, MultiValue, StdLib, VmState};
54use yk_core::{Error, Result};
55
56pub use host::{
57    DenyHost, ExtensionSources, Host, HttpResponse, extension_sources, session_dir, user_dir,
58};
59pub use tool::{HookGuardedTool, LuaTool, is_builtin};
60
61/// Cap on the Lua heap. The interrupt does not stop an allocating loop.
62const MEMORY_LIMIT: usize = 64 * 1024 * 1024;
63
64/// How many interrupt firings one execution may have.
65///
66/// The interrupt fires on every function call and loop iteration, so this is
67/// not a true instruction count. It is a work limit: each firing is a call or
68/// an iteration, and the count bounds how much of either a script can do
69/// between checks. `while true do end` hits it in milliseconds; a script
70/// that does real work does not.
71///
72/// The wall-clock deadline stays as a backstop for long-running native calls,
73/// which the interrupt cannot reach. The instruction limit is the guarantee.
74const INSTRUCTION_LIMIT: u64 = 1_000_000;
75
76/// The libraries an extension may use.
77///
78/// Named one at a time rather than derived from `ALL_SAFE`, which under Luau is
79/// `StdLib(u32::MAX)`: every flag, `debug` included. A derived set would hand a
80/// script the debug library, which is the one omission here that is a real
81/// capability rather than a build fact.
82///
83/// What is loaded and why:
84///
85/// - `utf8`, `bit32`, and `buffer` are pure.
86/// - `os` is out. Luau's `os` registers exactly `clock`, `date`, `difftime`,
87///   and `time`, with no `execute`, but the requirement is a whitelist with no
88///   dangerous library in it and `os` is on the list. Redis reached the same
89///   place from the other direction, running with no `os` at all until version
90///   7.4 exposed `os.clock` alone.
91/// - `debug` is out because Luau trims it to `traceback` and `info`, and the
92///   reason is partly memory safety rather than reach.
93/// - `io`, `package`, and `ffi` are not choices. `StdLib::IO` and
94///   `StdLib::PACKAGE` are `#[cfg(not(feature = "luau"))]` and `StdLib::FFI` is
95///   `LuaJIT`'s, so under the `luau` feature they are not constants at all.
96///
97/// None of this is an authority boundary. `bash` already reaches anything the
98/// user can reach, and the docs say so plainly.
99fn safe_libs() -> StdLib {
100    StdLib::COROUTINE
101        .bitor(StdLib::TABLE)
102        .bitor(StdLib::STRING)
103        .bitor(StdLib::MATH)
104        .bitor(StdLib::UTF8)
105        .bitor(StdLib::BIT)
106        .bitor(StdLib::BUFFER)
107}
108
109/// The deadline a single execution gets by default.
110///
111/// The interrupt fires at any call or loop iteration, so the deadline is
112/// checked when the script next runs; a native call already in progress is not
113/// aborted. `runner` bounds its child at the same value, so a stuck child is
114/// killed rather than waiting for the script to resume.
115pub const TOOL_TIMEOUT: Duration = Duration::from_secs(10);
116
117/// What an extension declared. Kept whole so the tool can borrow its callback.
118#[derive(Clone, Debug)]
119pub struct ToolInfo {
120    pub name: String,
121    pub description: String,
122    pub schema: serde_json::Value,
123    pub callback: mlua::Function,
124}
125
126/// A hook an extension registered through `on_tool_call`.
127///
128/// `source` is the script that registered it, so a hook that raises blocks the
129/// call with a message naming the file rather than saying "a hook failed".
130#[derive(Clone, Debug)]
131pub struct Hook {
132    pub source: String,
133    pub callback: mlua::Function,
134}
135
136/// The embedded VM and everything registered against it.
137pub struct Registry {
138    lua: Lua,
139    tools: BTreeMap<String, ToolInfo>,
140    hooks: Vec<Hook>,
141    budget: Arc<Mutex<ExecutionBudget>>,
142}
143
144/// The per-execution budget, shared between the registry and its tools.
145///
146/// One execution is one budget: a script load, a tool call, or a hook. The
147/// budget is armed before the execution and cleared after, so the limits apply
148/// to a single execution and not to the sum of every execution a script has
149/// made.
150///
151/// There is one `ExecutionBudget` per registry, so exactly one execution may be
152/// armed at a time. The agent loop dispatches tool calls one at a time, and
153/// nothing else runs Lua concurrently, so that holds today. Two overlapping
154/// executions would share the counter and the later `clear` would disarm the
155/// earlier one; a stack of budgets would make overlap safe if the loop ever
156/// runs calls in parallel.
157#[derive(Default)]
158pub struct ExecutionBudget {
159    /// Wall-clock deadline, armed for one execution.
160    deadline: Option<Instant>,
161    /// How many times the interrupt has fired this budget. Each firing is a
162    /// function call or loop iteration, so the count bounds the work a script
163    /// can do between checks.
164    instructions: u64,
165}
166
167impl ExecutionBudget {
168    /// Arm the budget for one execution: a fresh deadline and a fresh count.
169    pub(crate) fn arm(&mut self, timeout: Duration) {
170        self.deadline = Instant::now().checked_add(timeout);
171        self.instructions = 0;
172    }
173
174    /// Clear the budget after one execution.
175    pub(crate) const fn clear(&mut self) {
176        self.deadline = None;
177        self.instructions = 0;
178    }
179}
180
181impl Registry {
182    /// Build a sandboxed VM. The `host` table is installed after this returns.
183    ///
184    /// # Errors
185    ///
186    /// [`Error::Malformed`] when the VM cannot be created or sandboxed, which
187    /// in practice means the Luau build is broken rather than anything here.
188    pub fn new(host: &Arc<dyn Host>) -> Result<Self> {
189        // `new_with` is the safe constructor: it cannot load C modules at all.
190        let lua = Lua::new_with(safe_libs(), mlua::LuaOptions::default())
191            .map_err(|e| Error::Malformed(format!("could not create the luau vm: {e}")))?;
192
193        // VM-level readonly tables. This is the primitive PUC Lua does not have.
194        lua.sandbox(true)
195            .map_err(|e| Error::Malformed(format!("could not sandbox the vm: {e}")))?;
196
197        // Best effort. A VM that refuses the cap is still correct, just less
198        // bounded, so this must not be a hard failure.
199        let _ = lua.set_memory_limit(MEMORY_LIMIT);
200
201        let budget = Arc::new(Mutex::new(ExecutionBudget::default()));
202
203        {
204            let flag = Arc::clone(&budget);
205            lua.set_interrupt(move |_lua| {
206                let mut guard = flag.lock().map_err(|_| {
207                    mlua::Error::RuntimeError("the execution lock was poisoned".to_owned())
208                })?;
209
210                // Only count when the budget is armed, which is during a load,
211                // a tool call, or a hook. The interrupt fires at those points
212                // and nowhere else.
213                if guard.deadline.is_some() {
214                    guard.instructions = guard.instructions.saturating_add(1);
215                    if guard.instructions > INSTRUCTION_LIMIT {
216                        return Err(mlua::Error::RuntimeError(format!(
217                            "the script exceeded the instruction limit of {INSTRUCTION_LIMIT}"
218                        )));
219                    }
220                }
221
222                // An error, not a yield. A yield only happens at yieldable
223                // points, and in a coroutine the async future wakes itself and
224                // re-polls, resuming the loop, which hits the interrupt again.
225                // That is an infinite poll loop, not a stop. An error
226                // propagates through the Lua code and violently terminates
227                // the script.
228                if guard.deadline.is_some_and(|at| Instant::now() >= at) {
229                    return Err(mlua::Error::RuntimeError("the script timed out".to_owned()));
230                }
231
232                drop(guard);
233                Ok(VmState::Continue)
234            });
235        }
236
237        let registry = Self {
238            lua,
239            tools: BTreeMap::new(),
240            hooks: Vec::new(),
241            budget,
242        };
243        registry.install_host(host)?;
244        Ok(registry)
245    }
246
247    /// The one host member that is not a capability: `register_tool`.
248    ///
249    /// The documented form is positional. A table is also accepted, because
250    /// it reads better when one script registers several tools.
251    ///
252    /// # Errors
253    ///
254    /// [`Error::Malformed`] when the closure cannot be built.
255    fn register_tool_function(&self) -> Result<mlua::Function> {
256        let lua = &self.lua;
257        lua.create_function(|lua, passed: MultiValue| {
258            let mut it = passed.into_iter();
259            let first = it.next().ok_or_else(|| {
260                mlua::Error::RuntimeError("register_tool needs a name".to_owned())
261            })?;
262
263            // Positional is the documented form. A table is also accepted, because it
264            // reads better when one script registers several tools.
265            let (name, description, raw_schema, callback) = match &first {
266                mlua::Value::Table(table) => (
267                    table.get::<String>("name").map_err(|_| {
268                        mlua::Error::RuntimeError("register_tool needs a name".to_owned())
269                    })?,
270                    table.get::<String>("description").unwrap_or_default(),
271                    table
272                        .get::<mlua::Value>("schema")
273                        .unwrap_or(mlua::Value::Nil),
274                    table.get::<mlua::Function>("callback").map_err(|_| {
275                        mlua::Error::RuntimeError("register_tool needs a callback".to_owned())
276                    })?,
277                ),
278                mlua::Value::String(name) => {
279                    let name = name.to_string_lossy();
280                    let description = it
281                        .next()
282                        .map_or_else(String::new, |value| value.to_string().unwrap_or_default());
283                    let raw_schema = it.next().unwrap_or(mlua::Value::Nil);
284                    let callback = it
285                        .next()
286                        .and_then(|value| value.as_function().cloned())
287                        .ok_or_else(|| {
288                            mlua::Error::RuntimeError("register_tool needs a callback".to_owned())
289                        })?;
290                    (name, description, raw_schema, callback)
291                }
292                _ => {
293                    return Err(mlua::Error::RuntimeError(
294                        "register_tool takes a name, or a table with one".to_owned(),
295                    ));
296                }
297            };
298
299            let schema = if raw_schema.is_nil() {
300                serde_json::json!({"type": "object"})
301            } else {
302                lua.from_value(raw_schema)
303                    .map_err(|e| mlua::Error::RuntimeError(format!("register_tool schema: {e}")))?
304            };
305
306            stage(
307                &STAGED,
308                ToolInfo {
309                    name,
310                    description,
311                    schema,
312                    callback,
313                },
314            );
315            Ok::<(), mlua::Error>(())
316        })
317        .map_err(|e| lua_error(&e))
318    }
319
320    /// The one capability that is not: `on_tool_call`, which lets an extension
321    /// refuse a call rather than only add one.
322    ///
323    /// A separate global rather than a fourth `host` member, because `host` is
324    /// frozen at six capabilities plus `register_tool` and this is a different
325    /// kind of thing: it is not reach, it is the absence of reach.
326    ///
327    /// # Errors
328    ///
329    /// [`Error::Malformed`] when the closure cannot be built.
330    fn on_tool_call_function(&self) -> Result<mlua::Function> {
331        let lua = &self.lua;
332        lua.create_function(|_, callback: mlua::Function| {
333            stage(&STAGED_HOOKS, callback);
334            Ok::<(), mlua::Error>(())
335        })
336        .map_err(|e| lua_error(&e))
337    }
338
339    /// Put the `host` table in front of scripts.
340    ///
341    /// Each of these is a capability the built-in tools can already do. Adding
342    /// one is cheap and expected; renaming or repurposing one is a breaking
343    /// change to every script ever written. Three of them, added later, turn
344    /// a script from a reader into a participant.
345    ///
346    /// # Errors
347    ///
348    /// [`Error::Malformed`] when the table cannot be built.
349    fn install_host(&self, host: &Arc<dyn Host>) -> Result<()> {
350        let lua = &self.lua;
351        let table = lua.create_table().map_err(|e| lua_error(&e))?;
352        // The closures capture the `Arc` directly. `mlua` requires them to be
353        // `'static`, and an owned handle is both that and simpler than any
354        // out-of-band lookup.
355        {
356            let host = Arc::clone(host);
357            let read_file = lua
358                // A plain closure that *returns* a future, not an `async`
359                // closure: an async closure is not `Fn`, and mlua's bound is `Fn`.
360                .create_async_function(move |_, path: String| {
361                    let host = Arc::clone(&host);
362                    async move {
363                        host.read_file(Path::new(&path))
364                            .await
365                            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))
366                    }
367                })
368                .map_err(|e| lua_error(&e))?;
369            set_capability(&table, "read_file", read_file)?;
370        }
371
372        {
373            let host = Arc::clone(host);
374            let http_get = lua
375                .create_async_function(move |_, url: String| {
376                    let host = Arc::clone(&host);
377                    async move {
378                        host.http_get(&url)
379                            .await
380                            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))
381                    }
382                })
383                .map_err(|e| lua_error(&e))?;
384            table.set("http_get", http_get).map_err(|e| lua_error(&e))?;
385        }
386
387        {
388            let post = self.post_json_function(host)?;
389            set_capability(&table, "http_post_json", post)?;
390        }
391
392        {
393            let env = self.env_function(host)?;
394            set_capability(&table, "env", env)?;
395        }
396
397        {
398            let parse = lua
399                .create_function(move |lua, text: String| {
400                    let parsed: serde_json::Value = serde_json::from_str(&text)
401                        .map_err(|e| mlua::Error::RuntimeError(format!("bad json: {e}")))?;
402                    lua.to_value(&parsed)
403                })
404                .map_err(|e| lua_error(&e))?;
405            set_capability(&table, "json", parse)?;
406        }
407
408        {
409            let encode = self.json_encode_function()?;
410            set_capability(&table, "json_encode", encode)?;
411        }
412
413        set_capability(&table, "register_tool", self.register_tool_function()?)?;
414
415        let globals = lua.globals();
416        globals
417            .set("host", table)
418            .map_err(|e| Error::Malformed(format!("could not install host: {e}")))?;
419
420        globals
421            .set("on_tool_call", self.on_tool_call_function()?)
422            .map_err(|e| Error::Malformed(format!("could not install on_tool_call: {e}")))?;
423
424        // The process gateway. A separate global rather than a seventh `host`
425        // member, because the requirement names a UserData struct and moving
426        // it to `host` later is a small change in either direction.
427        let runner = lua
428            .create_userdata(crate::runner::ProcessRunner)
429            .map_err(|e| lua_error(&e))?;
430        globals
431            .set("runner", runner)
432            .map_err(|e| Error::Malformed(format!("could not install runner: {e}")))
433    }
434
435    /// `host.http_post_json(url, headers, body)`, returning `{status, body}`.
436    ///
437    /// A non-2xx status is a value rather than an error, because a script
438    /// gating a tool call has to tell "the model answered" apart from "the
439    /// vendor is rate-limiting you", and the second one is the case where
440    /// failing open is correct.
441    ///
442    /// # Errors
443    ///
444    /// [`Error::Malformed`] when the closure cannot be built.
445    fn post_json_function(&self, host: &Arc<dyn Host>) -> Result<mlua::Function> {
446        let host = Arc::clone(host);
447        let lua = &self.lua;
448        // `Lua` arrives by value and the future must be `'static`, so the VM
449        // handle is moved in rather than borrowed. The argument is one tuple
450        // because `create_async_function` is `Fn(Lua, FromLuaMulti)`, which is
451        // not variadic.
452        lua.create_async_function(
453            move |lua: mlua::Lua, (url, headers, body): (String, mlua::Table, String)| {
454                let host = Arc::clone(&host);
455                async move {
456                    let sent = lua
457                        .from_value::<BTreeMap<String, String>>(mlua::Value::Table(headers))
458                        .map_err(|e| {
459                            mlua::Error::RuntimeError(format!("headers are not all strings: {e}"))
460                        })?;
461
462                    let reply = host
463                        .http_post_json(&url, &sent, &body)
464                        .await
465                        .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
466
467                    let out = lua.create_table()?;
468                    out.set("status", reply.status)?;
469                    out.set("body", reply.body)?;
470                    Ok(out)
471                }
472            },
473        )
474        .map_err(|e| lua_error(&e))
475    }
476
477    /// `host.env(name)`, returning a string or nil.
478    ///
479    /// Synchronous because the environment is already in memory. Making it
480    /// `await`able would buy nothing and would cost every caller a `pcall`
481    /// around a call that cannot fail.
482    ///
483    /// # Errors
484    ///
485    /// [`Error::Malformed`] when the closure cannot be built.
486    fn env_function(&self, host: &Arc<dyn Host>) -> Result<mlua::Function> {
487        let host = Arc::clone(host);
488        let lua = &self.lua;
489        lua.create_function(move |_, name: String| Ok(host.env(&name)))
490            .map_err(|e| lua_error(&e))
491    }
492
493    /// `host.json_encode(value)`, the mirror of `host.json`.
494    ///
495    /// `host.json` decodes and nothing encodes, which made every HTTP API
496    /// unreachable without a hand-rolled serializer in the extension. This is
497    /// not new reach; it is the other direction of a member that already exists.
498    ///
499    /// # Errors
500    ///
501    /// [`Error::Malformed`] when the closure cannot be built.
502    fn json_encode_function(&self) -> Result<mlua::Function> {
503        let lua = &self.lua;
504        lua.create_function(move |lua, value: mlua::Value| {
505            let as_json: serde_json::Value = lua.from_value(value).map_err(|e| {
506                mlua::Error::RuntimeError(format!("value is not representable as json: {e}"))
507            })?;
508            serde_json::to_string(&as_json)
509                .map_err(|e| mlua::Error::RuntimeError(format!("could not encode: {e}")))
510        })
511        .map_err(|e| lua_error(&e))
512    }
513
514    /// Load every `.lua` file in `dir`, in name order.
515    ///
516    /// # Errors
517    ///
518    /// [`Error::Read`] when the directory cannot be read. A failing script inside
519    /// it is reported by [`Registry::load_dir`] rather than aborting the rest.
520    pub fn load_dir(&mut self, dir: &Path) -> Result<Vec<LoadedScript>> {
521        if !dir.is_dir() {
522            return Ok(Vec::new());
523        }
524
525        let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
526            .map_err(|source| Error::Read {
527                path: dir.display().to_string(),
528                source,
529            })?
530            .filter_map(Result::ok)
531            .map(|entry| entry.path())
532            .filter(|path| path.extension().is_some_and(|ext| ext == "lua"))
533            .collect();
534        files.sort();
535
536        let mut loaded = Vec::new();
537        for file in files {
538            // One broken extension must not cost the user every extension.
539            match self.load_file(&file) {
540                Ok(entry) => loaded.push(entry),
541                Err(error) => eprintln!("yk: skipping {}: {error}", file.display()),
542            }
543        }
544        Ok(loaded)
545    }
546
547    /// Load one script and register whatever it declared.
548    ///
549    /// # Errors
550    ///
551    /// [`Error::Read`] when the file cannot be read, and [`Error::Malformed`] when
552    /// the script itself is bad.
553    pub fn load_file(&mut self, path: &Path) -> Result<LoadedScript> {
554        let source = std::fs::read_to_string(path).map_err(|source| Error::Read {
555            path: path.display().to_string(),
556            source,
557        })?;
558
559        self.load_source(&source, &path.display().to_string())
560    }
561
562    /// Load a script from memory.
563    ///
564    /// # Errors
565    ///
566    /// [`Error::Malformed`] when the script fails to load or registers something
567    /// malformed. The script's name is in the message, so a model that wrote it
568    /// can be told which one.
569    pub fn load_source(&mut self, source: &str, name: &str) -> Result<LoadedScript> {
570        // `set_mode("t")` refuses binary chunks. Without it a crafted bytecode
571        // file is a way past every other control in this file.
572        let chunk = self
573            .lua
574            .load(source)
575            .set_name(name)
576            .set_mode(mlua::chunk::ChunkMode::Text)
577            .into_function()
578            .map_err(|e| Error::Malformed(format!("{name}: {e}")))?;
579
580        let hooks_before = self.hooks.len();
581
582        take_staged_items(&STAGED);
583        take_staged_items(&STAGED_HOOKS);
584
585        // A load runs the script's top level, so it is an execution and gets
586        // the same bounds as a tool call. Without this, a top-level
587        // `while true do end` wedges startup.
588        {
589            let mut guard = self.budget.lock().map_err(|_| {
590                Error::Malformed(format!("{name}: the execution lock was poisoned"))
591            })?;
592            guard.arm(TOOL_TIMEOUT);
593        }
594        let called = chunk.call::<MultiValue>(MultiValue::new());
595        {
596            let mut guard = self.budget.lock().map_err(|_| {
597                Error::Malformed(format!("{name}: the execution lock was poisoned"))
598            })?;
599            guard.clear();
600        }
601        called.map_err(|e| Error::Malformed(format!("{name}: {e}")))?;
602
603        for callback in take_staged_items(&STAGED_HOOKS) {
604            self.hooks.push(Hook {
605                source: name.to_owned(),
606                callback,
607            });
608        }
609
610        let mut tools: Vec<String> = Vec::new();
611        for manifest in take_staged_items(&STAGED) {
612            tools.push(manifest.name.clone());
613            if let Err(error) = self.register(manifest) {
614                return Err(Error::Malformed(format!("{name}: {error}")));
615            }
616        }
617
618        Ok(LoadedScript {
619            file: PathBuf::from(name),
620            tools,
621            hooks: self.hooks.len().saturating_sub(hooks_before),
622        })
623    }
624
625    /// Wrap a tool so this registry's hooks see every call to it.
626    ///
627    /// The guard is what makes an extension able to *reduce* the agent's power
628    /// rather than only add to it. `yk-core` knows nothing about Lua, so the
629    /// check arrives as an ordinary `Tool` and the loop is unchanged.
630    #[must_use]
631    pub fn guard<'a>(&'a self, inner: &'a dyn yk_core::Tool) -> HookGuardedTool<'a> {
632        HookGuardedTool {
633            inner,
634            lua: &self.lua,
635            hooks: &self.hooks,
636            budget: &self.budget,
637        }
638    }
639
640    /// The hooks an extension registered, in load order.
641    #[must_use]
642    pub fn hooks(&self) -> &[Hook] {
643        &self.hooks
644    }
645
646    /// The tools, borrowed from this registry.
647    ///
648    /// This is what the loop is given, so the manifest's description and schema
649    /// travel with the tool rather than being read off the registry here. A
650    /// second path that built a `ToolDef` from the same manifest is a second
651    /// answer to the same question, and it is the one that went unread.
652    #[must_use]
653    pub fn tools(&self) -> Vec<LuaTool<'_>> {
654        self.tools
655            .values()
656            .map(|manifest| {
657                LuaTool::new(
658                    &self.lua,
659                    manifest.name.clone(),
660                    manifest.description.clone(),
661                    manifest.schema.clone(),
662                    &manifest.callback,
663                    &self.budget,
664                )
665            })
666            .collect()
667    }
668
669    /// Register a tool, called from `Lua` by a script.
670    ///
671    /// # Errors
672    ///
673    /// [`Error::BadArgs`] when the four fields are missing, and
674    /// [`Error::Malformed`] when a script tries to take over a built-in.
675    pub fn register(&mut self, manifest: ToolInfo) -> Result<()> {
676        if manifest.name.is_empty() {
677            return Err(Error::BadArgs {
678                tool: "register_tool".to_owned(),
679                reason: "a tool needs a name".to_owned(),
680            });
681        }
682
683        if is_builtin(&manifest.name) {
684            return Err(Error::Malformed(format!(
685                "`{}` is a built-in tool and cannot be replaced",
686                manifest.name
687            )));
688        }
689
690        self.tools.insert(manifest.name.clone(), manifest);
691        Ok(())
692    }
693
694    #[must_use]
695    pub fn len(&self) -> usize {
696        self.tools.len()
697    }
698
699    #[must_use]
700    pub fn is_empty(&self) -> bool {
701        self.tools.is_empty()
702    }
703
704    /// The VM, for a caller that needs to read a value out.
705    #[must_use]
706    pub const fn lua(&self) -> &Lua {
707        &self.lua
708    }
709}
710
711thread_local! {
712    /// Tool registrations a script registered, not yet in the registry.
713    ///
714    /// A Lua closure cannot borrow `&mut self`, and `register_tool` has to reach
715    /// the same map the provider reads. Staging and draining after the script
716    /// returns is the smallest thing that reconciles those two facts, and it has
717    /// the useful side effect that a script which registers and then crashes
718    /// leaves nothing behind.
719    static STAGED: std::cell::RefCell<Vec<ToolInfo>> =
720        const { std::cell::RefCell::new(Vec::new()) };
721
722    /// Hooks a script registered, not yet in the registry. Same reconciliation
723    /// as `STAGED`, and the same reason.
724    static STAGED_HOOKS: std::cell::RefCell<Vec<mlua::Function>> =
725        const { std::cell::RefCell::new(Vec::new()) };
726}
727
728/// Stage one item for the script's own thread to pick up when it returns.
729fn stage<T>(slot: &'static std::thread::LocalKey<std::cell::RefCell<Vec<T>>>, item: T) {
730    slot.with(|cell| cell.borrow_mut().push(item));
731}
732
733/// Take everything staged on this thread.
734fn take_staged_items<T>(
735    slot: &'static std::thread::LocalKey<std::cell::RefCell<Vec<T>>>,
736) -> Vec<T> {
737    slot.with(|cell| std::mem::take(&mut *cell.borrow_mut()))
738}
739
740/// A loaded script, for the startup message.
741#[derive(Clone, Debug, Eq, PartialEq)]
742pub struct LoadedScript {
743    pub file: PathBuf,
744    pub tools: Vec<String>,
745    /// How many `on_tool_call` hooks the script registered.
746    pub hooks: usize,
747}
748
749/// Put one host capability on the table, mapping a failure the same way.
750fn set_capability(table: &mlua::Table, name: &str, function: mlua::Function) -> Result<()> {
751    table.set(name, function).map_err(|e| lua_error(&e))
752}
753
754/// Turn a yk error into a Lua-facing one.
755fn lua_error(error: &mlua::Error) -> Error {
756    Error::Malformed(error.to_string())
757}
758
759#[cfg(test)]
760mod tests {
761    #![allow(
762        clippy::unwrap_used,
763        clippy::expect_used,
764        clippy::indexing_slicing,
765        clippy::as_conversions,
766        clippy::arithmetic_side_effects
767    )]
768
769    use std::sync::Arc;
770
771    use yk_core::Tool as _;
772
773    use crate::{DenyHost, Host, Registry};
774
775    fn denying() -> Arc<dyn Host> {
776        Arc::new(DenyHost)
777    }
778
779    fn registry() -> Registry {
780        Registry::new(&denying()).expect("builds a vm")
781    }
782
783    #[test]
784    fn a_fresh_registry_has_no_tools() {
785        let registry = registry();
786        assert!(registry.is_empty());
787        assert!(registry.tools().is_empty());
788    }
789
790    #[test]
791    fn io_is_not_reachable_from_a_script() {
792        // Structural, not policy: `StdLib::IO` is `#[cfg(not(feature = "luau"))]`
793        // in mlua and Luau's `linit.cpp` registers no `luaopen_io`. This asserts
794        // something about the dependency, which is worth knowing and is not a
795        // restriction yk applies.
796        let mut registry = registry();
797        let error = registry
798            .load_source(r#"return io.open("/etc/passwd")"#, "escape.lua")
799            .expect_err("must fail");
800        assert!(error.to_string().contains("escape.lua"), "{error}");
801    }
802
803    #[test]
804    fn os_is_not_reachable_from_a_script() {
805        // `os` is not in the whitelist. Luau's `os` registers exactly `clock`,
806        // `date`, `difftime`, and `time`, with no `execute`, but the requirement
807        // is a whitelist with no dangerous library in it and `os` is on the
808        // list. It comes out.
809        let registry = registry();
810        let kind: String = registry
811            .lua()
812            .load(r"return type(os)")
813            .eval()
814            .expect("evaluates");
815        assert_eq!(kind, "nil");
816    }
817
818    #[test]
819    fn package_is_not_reachable_from_a_script() {
820        // Structural for the same reason as `io`: `StdLib::PACKAGE` is
821        // `#[cfg(not(feature = "luau"))]`.
822        let mut registry = registry();
823        assert!(
824            registry
825                .load_source(r#"return package.loadlib("x", "y")"#, "escape.lua")
826                .is_err()
827        );
828    }
829
830    #[test]
831    fn debug_is_not_reachable_from_a_script() {
832        // Luau trims `debug` to `traceback` and `info`, and the whitelist does
833        // not ask for it at all, so the table is nil rather than a reduced one.
834        let registry = registry();
835        let kind: String = registry
836            .lua()
837            .load(r"return type(debug)")
838            .eval()
839            .expect("evaluates");
840        assert_eq!(kind, "nil");
841    }
842
843    #[test]
844    fn ffi_is_not_reachable_from_a_script() {
845        // `ffi` is LuaJIT's, so under the `luau` feature the global does not
846        // exist. This is the capability #131 wanted and #132 refuses.
847        let registry = registry();
848        let kind: String = registry
849            .lua()
850            .load(r"return type(ffi)")
851            .eval()
852            .expect("evaluates");
853        assert_eq!(kind, "nil");
854    }
855
856    #[test]
857    fn rawset_cannot_reach_inside_a_sandboxed_library() {
858        // The primitive PUC Lua does not have, and the reason a blacklisted
859        // global table would not have been enough.
860        let mut registry = registry();
861        assert!(
862            registry
863                .load_source(r#"rawset(string, "upper", nil)"#, "escape.lua")
864                .is_err()
865        );
866    }
867
868    #[test]
869    fn bytecode_is_refused() {
870        let mut registry = registry();
871        let error = registry
872            .load_source("\u{1b}Lua\x52\x00", "chunk")
873            .expect_err("must fail");
874        assert!(error.to_string().contains("chunk"), "{error}");
875    }
876
877    #[test]
878    fn a_syntax_error_names_the_script() {
879        let mut registry = registry();
880        let error = registry
881            .load_source("this is not lua", "broken.lua")
882            .expect_err("must fail");
883        assert!(error.to_string().contains("broken.lua"), "{error}");
884    }
885
886    #[test]
887    fn a_denying_host_reaches_the_script_as_an_error() {
888        let mut registry = registry();
889        let error = registry
890            .load_source(r#"return host.read_file("/etc/passwd")"#, "read.lua")
891            .expect_err("must fail");
892        assert!(error.to_string().contains("read.lua"), "{error}");
893    }
894
895    #[test]
896    fn the_host_table_has_exactly_the_members_the_records_name() {
897        let registry = registry();
898        let host = registry
899            .lua()
900            .globals()
901            .get::<mlua::Table>("host")
902            .expect("host table");
903
904        let mut names = Vec::new();
905        host.for_each(|name: String, _: mlua::Value| {
906            names.push(name);
907            Ok::<(), mlua::Error>(())
908        })
909        .expect("iterates");
910        names.sort();
911
912        // Six capability members plus the registration function.
913        // freezes the set: adding a capability is cheap and expected, renaming
914        // or repurposing one is a breaking change to every script ever written.
915        // adds `env`, `http_post_json`, and `json_encode`.
916        assert_eq!(
917            names,
918            [
919                "env",
920                "http_get",
921                "http_post_json",
922                "json",
923                "json_encode",
924                "read_file",
925                "register_tool",
926            ]
927        );
928    }
929
930    #[test]
931    fn the_runner_global_is_installed() {
932        let registry = registry();
933        let runner = registry
934            .lua()
935            .globals()
936            .get::<mlua::Value>("runner")
937            .expect("runner global");
938        assert!(
939            matches!(runner, mlua::Value::UserData(_)),
940            "runner is userdata"
941        );
942    }
943
944    #[test]
945    fn json_round_trips_through_the_host() {
946        // `json` without its mirror is a one-way door: any extension talking to
947        // an HTTP API has to write a request body, and there was no way to do
948        // it that did not mean hand-rolling an encoder.
949        let registry = registry();
950        let encoded: String = registry
951            .lua()
952            .load(r#"return host.json_encode({ a = 1, b = { c = "x" } })"#)
953            .eval()
954            .expect("evaluates");
955        assert_eq!(encoded, r#"{"a":1,"b":{"c":"x"}}"#);
956    }
957
958    #[test]
959    fn a_denying_host_reaches_a_post_as_an_error() {
960        let mut registry = registry();
961        let error = registry
962            .load_source(
963                r#"return host.http_post_json("https://example.com", {}, "{}")"#,
964                "post.lua",
965            )
966            .expect_err("must fail");
967        assert!(error.to_string().contains("post.lua"), "{error}");
968    }
969
970    #[test]
971    fn an_unset_environment_variable_is_nil_rather_than_an_error() {
972        // A script asking for a key it was not given has to be able to find that
973        // out without handling an error.
974        let registry = registry();
975        let kind: String = registry
976            .lua()
977            .load(r#"return type(host.env("YK_DEFINITELY_NOT_SET_12345"))"#)
978            .eval()
979            .expect("evaluates");
980        assert_eq!(kind, "nil");
981    }
982
983    #[test]
984    fn json_decodes_into_a_lua_table() {
985        let registry = registry();
986        let decoded: String = registry
987            .lua()
988            .load(r#"return type(host.json('{"a":1}'))"#)
989            .eval()
990            .expect("evaluates");
991        assert_eq!(decoded, "table");
992    }
993
994    #[test]
995    fn a_missing_directory_loads_nothing_rather_than_failing() {
996        let mut registry = registry();
997        let loaded = registry
998            .load_dir(Path::new("/nonexistent/yk/lua"))
999            .expect("loads");
1000        assert!(loaded.is_empty());
1001    }
1002
1003    #[tokio::test]
1004    async fn a_script_under_the_instruction_limit_runs_to_completion() {
1005        let mut registry = registry();
1006        registry
1007            .load_source(
1008                r#"host.register_tool("count", "Counts", {}, function()
1009                    local sum = 0
1010                    for i = 1, 100 do sum = sum + i end
1011                    return tostring(sum)
1012                end)"#,
1013                "count.lua",
1014            )
1015            .expect("loads");
1016
1017        let tools = registry.tools();
1018        let counting = tools
1019            .iter()
1020            .find(|tool| tool.name() == "count")
1021            .expect("the tool is registered");
1022
1023        let out = counting
1024            .clone()
1025            .with_timeout(std::time::Duration::from_secs(5))
1026            .run(&serde_json::json!({}))
1027            .await
1028            .expect("runs");
1029        assert_eq!(out, "5050");
1030    }
1031
1032    #[tokio::test]
1033    async fn a_script_spawns_a_process_through_the_runner() {
1034        // The wiring, not just the Rust function: `runner` is a UserData global
1035        // and `spawn_tool` is an async method the script calls without await,
1036        // because mlua drives the future while the tool call is polled.
1037        let mut registry = registry();
1038        registry
1039            .load_source(
1040                r#"host.register_tool("echo", "Echo", {}, function()
1041                    local result = runner.spawn_tool("echo", { "hi" })
1042                    return result.stdout
1043                end)"#,
1044                "echo.lua",
1045            )
1046            .expect("loads");
1047
1048        let tools = registry.tools();
1049        let echoing = tools
1050            .iter()
1051            .find(|tool| tool.name() == "echo")
1052            .expect("the tool is registered");
1053
1054        let out = echoing
1055            .clone()
1056            .with_timeout(std::time::Duration::from_secs(5))
1057            .run(&serde_json::json!({}))
1058            .await
1059            .expect("runs");
1060        assert_eq!(out.trim(), "hi");
1061    }
1062
1063    #[tokio::test]
1064    async fn a_non_coercible_argument_to_spawn_tool_is_an_error() {
1065        let mut registry = registry();
1066        registry
1067            .load_source(
1068                r#"host.register_tool("bad", "Bad", {}, function()
1069                    return runner.spawn_tool("echo", { true })
1070                end)"#,
1071                "bad.lua",
1072            )
1073            .expect("loads");
1074
1075        let tools = registry.tools();
1076        let bad = tools
1077            .iter()
1078            .find(|tool| tool.name() == "bad")
1079            .expect("the tool is registered");
1080
1081        let error = bad
1082            .clone()
1083            .run(&serde_json::json!({}))
1084            .await
1085            .expect_err("must fail");
1086        assert!(error.to_string().contains("args"), "{error}");
1087    }
1088
1089    use std::path::Path;
1090}