mod host;
mod runner;
mod tool;
use std::collections::BTreeMap;
use std::ops::BitOr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use mlua::{Lua, LuaSerdeExt, MultiValue, StdLib, VmState};
use yk_core::{Error, Result};
pub use host::{
DenyHost, ExtensionSources, Host, HttpResponse, extension_sources, session_dir, user_dir,
};
pub use tool::{HookGuardedTool, LuaTool, is_builtin};
const MEMORY_LIMIT: usize = 64 * 1024 * 1024;
const INSTRUCTION_LIMIT: u64 = 1_000_000;
fn safe_libs() -> StdLib {
StdLib::COROUTINE
.bitor(StdLib::TABLE)
.bitor(StdLib::STRING)
.bitor(StdLib::MATH)
.bitor(StdLib::UTF8)
.bitor(StdLib::BIT)
.bitor(StdLib::BUFFER)
}
pub const TOOL_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone, Debug)]
pub struct ToolInfo {
pub name: String,
pub description: String,
pub schema: serde_json::Value,
pub callback: mlua::Function,
}
#[derive(Clone, Debug)]
pub struct Hook {
pub source: String,
pub callback: mlua::Function,
}
pub struct Registry {
lua: Lua,
tools: BTreeMap<String, ToolInfo>,
hooks: Vec<Hook>,
budget: Arc<Mutex<ExecutionBudget>>,
}
#[derive(Default)]
pub struct ExecutionBudget {
deadline: Option<Instant>,
instructions: u64,
}
impl ExecutionBudget {
pub(crate) fn arm(&mut self, timeout: Duration) {
self.deadline = Instant::now().checked_add(timeout);
self.instructions = 0;
}
pub(crate) const fn clear(&mut self) {
self.deadline = None;
self.instructions = 0;
}
}
impl Registry {
pub fn new(host: &Arc<dyn Host>) -> Result<Self> {
let lua = Lua::new_with(safe_libs(), mlua::LuaOptions::default())
.map_err(|e| Error::Malformed(format!("could not create the luau vm: {e}")))?;
lua.sandbox(true)
.map_err(|e| Error::Malformed(format!("could not sandbox the vm: {e}")))?;
let _ = lua.set_memory_limit(MEMORY_LIMIT);
let budget = Arc::new(Mutex::new(ExecutionBudget::default()));
{
let flag = Arc::clone(&budget);
lua.set_interrupt(move |_lua| {
let mut guard = flag.lock().map_err(|_| {
mlua::Error::RuntimeError("the execution lock was poisoned".to_owned())
})?;
if guard.deadline.is_some() {
guard.instructions = guard.instructions.saturating_add(1);
if guard.instructions > INSTRUCTION_LIMIT {
return Err(mlua::Error::RuntimeError(format!(
"the script exceeded the instruction limit of {INSTRUCTION_LIMIT}"
)));
}
}
if guard.deadline.is_some_and(|at| Instant::now() >= at) {
return Err(mlua::Error::RuntimeError("the script timed out".to_owned()));
}
drop(guard);
Ok(VmState::Continue)
});
}
let registry = Self {
lua,
tools: BTreeMap::new(),
hooks: Vec::new(),
budget,
};
registry.install_host(host)?;
Ok(registry)
}
fn register_tool_function(&self) -> Result<mlua::Function> {
let lua = &self.lua;
lua.create_function(|lua, passed: MultiValue| {
let mut it = passed.into_iter();
let first = it.next().ok_or_else(|| {
mlua::Error::RuntimeError("register_tool needs a name".to_owned())
})?;
let (name, description, raw_schema, callback) = match &first {
mlua::Value::Table(table) => (
table.get::<String>("name").map_err(|_| {
mlua::Error::RuntimeError("register_tool needs a name".to_owned())
})?,
table.get::<String>("description").unwrap_or_default(),
table
.get::<mlua::Value>("schema")
.unwrap_or(mlua::Value::Nil),
table.get::<mlua::Function>("callback").map_err(|_| {
mlua::Error::RuntimeError("register_tool needs a callback".to_owned())
})?,
),
mlua::Value::String(name) => {
let name = name.to_string_lossy();
let description = it
.next()
.map_or_else(String::new, |value| value.to_string().unwrap_or_default());
let raw_schema = it.next().unwrap_or(mlua::Value::Nil);
let callback = it
.next()
.and_then(|value| value.as_function().cloned())
.ok_or_else(|| {
mlua::Error::RuntimeError("register_tool needs a callback".to_owned())
})?;
(name, description, raw_schema, callback)
}
_ => {
return Err(mlua::Error::RuntimeError(
"register_tool takes a name, or a table with one".to_owned(),
));
}
};
let schema = if raw_schema.is_nil() {
serde_json::json!({"type": "object"})
} else {
lua.from_value(raw_schema)
.map_err(|e| mlua::Error::RuntimeError(format!("register_tool schema: {e}")))?
};
stage(
&STAGED,
ToolInfo {
name,
description,
schema,
callback,
},
);
Ok::<(), mlua::Error>(())
})
.map_err(|e| lua_error(&e))
}
fn on_tool_call_function(&self) -> Result<mlua::Function> {
let lua = &self.lua;
lua.create_function(|_, callback: mlua::Function| {
stage(&STAGED_HOOKS, callback);
Ok::<(), mlua::Error>(())
})
.map_err(|e| lua_error(&e))
}
fn install_host(&self, host: &Arc<dyn Host>) -> Result<()> {
let lua = &self.lua;
let table = lua.create_table().map_err(|e| lua_error(&e))?;
{
let host = Arc::clone(host);
let read_file = lua
.create_async_function(move |_, path: String| {
let host = Arc::clone(&host);
async move {
host.read_file(Path::new(&path))
.await
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))
}
})
.map_err(|e| lua_error(&e))?;
set_capability(&table, "read_file", read_file)?;
}
{
let host = Arc::clone(host);
let http_get = lua
.create_async_function(move |_, url: String| {
let host = Arc::clone(&host);
async move {
host.http_get(&url)
.await
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))
}
})
.map_err(|e| lua_error(&e))?;
table.set("http_get", http_get).map_err(|e| lua_error(&e))?;
}
{
let post = self.post_json_function(host)?;
set_capability(&table, "http_post_json", post)?;
}
{
let env = self.env_function(host)?;
set_capability(&table, "env", env)?;
}
{
let parse = lua
.create_function(move |lua, text: String| {
let parsed: serde_json::Value = serde_json::from_str(&text)
.map_err(|e| mlua::Error::RuntimeError(format!("bad json: {e}")))?;
lua.to_value(&parsed)
})
.map_err(|e| lua_error(&e))?;
set_capability(&table, "json", parse)?;
}
{
let encode = self.json_encode_function()?;
set_capability(&table, "json_encode", encode)?;
}
set_capability(&table, "register_tool", self.register_tool_function()?)?;
let globals = lua.globals();
globals
.set("host", table)
.map_err(|e| Error::Malformed(format!("could not install host: {e}")))?;
globals
.set("on_tool_call", self.on_tool_call_function()?)
.map_err(|e| Error::Malformed(format!("could not install on_tool_call: {e}")))?;
let runner = lua
.create_userdata(crate::runner::ProcessRunner)
.map_err(|e| lua_error(&e))?;
globals
.set("runner", runner)
.map_err(|e| Error::Malformed(format!("could not install runner: {e}")))
}
fn post_json_function(&self, host: &Arc<dyn Host>) -> Result<mlua::Function> {
let host = Arc::clone(host);
let lua = &self.lua;
lua.create_async_function(
move |lua: mlua::Lua, (url, headers, body): (String, mlua::Table, String)| {
let host = Arc::clone(&host);
async move {
let sent = lua
.from_value::<BTreeMap<String, String>>(mlua::Value::Table(headers))
.map_err(|e| {
mlua::Error::RuntimeError(format!("headers are not all strings: {e}"))
})?;
let reply = host
.http_post_json(&url, &sent, &body)
.await
.map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
let out = lua.create_table()?;
out.set("status", reply.status)?;
out.set("body", reply.body)?;
Ok(out)
}
},
)
.map_err(|e| lua_error(&e))
}
fn env_function(&self, host: &Arc<dyn Host>) -> Result<mlua::Function> {
let host = Arc::clone(host);
let lua = &self.lua;
lua.create_function(move |_, name: String| Ok(host.env(&name)))
.map_err(|e| lua_error(&e))
}
fn json_encode_function(&self) -> Result<mlua::Function> {
let lua = &self.lua;
lua.create_function(move |lua, value: mlua::Value| {
let as_json: serde_json::Value = lua.from_value(value).map_err(|e| {
mlua::Error::RuntimeError(format!("value is not representable as json: {e}"))
})?;
serde_json::to_string(&as_json)
.map_err(|e| mlua::Error::RuntimeError(format!("could not encode: {e}")))
})
.map_err(|e| lua_error(&e))
}
pub fn load_dir(&mut self, dir: &Path) -> Result<Vec<LoadedScript>> {
if !dir.is_dir() {
return Ok(Vec::new());
}
let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
.map_err(|source| Error::Read {
path: dir.display().to_string(),
source,
})?
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "lua"))
.collect();
files.sort();
let mut loaded = Vec::new();
for file in files {
match self.load_file(&file) {
Ok(entry) => loaded.push(entry),
Err(error) => eprintln!("yk: skipping {}: {error}", file.display()),
}
}
Ok(loaded)
}
pub fn load_file(&mut self, path: &Path) -> Result<LoadedScript> {
let source = std::fs::read_to_string(path).map_err(|source| Error::Read {
path: path.display().to_string(),
source,
})?;
self.load_source(&source, &path.display().to_string())
}
pub fn load_source(&mut self, source: &str, name: &str) -> Result<LoadedScript> {
let chunk = self
.lua
.load(source)
.set_name(name)
.set_mode(mlua::chunk::ChunkMode::Text)
.into_function()
.map_err(|e| Error::Malformed(format!("{name}: {e}")))?;
let hooks_before = self.hooks.len();
take_staged_items(&STAGED);
take_staged_items(&STAGED_HOOKS);
{
let mut guard = self.budget.lock().map_err(|_| {
Error::Malformed(format!("{name}: the execution lock was poisoned"))
})?;
guard.arm(TOOL_TIMEOUT);
}
let called = chunk.call::<MultiValue>(MultiValue::new());
{
let mut guard = self.budget.lock().map_err(|_| {
Error::Malformed(format!("{name}: the execution lock was poisoned"))
})?;
guard.clear();
}
called.map_err(|e| Error::Malformed(format!("{name}: {e}")))?;
for callback in take_staged_items(&STAGED_HOOKS) {
self.hooks.push(Hook {
source: name.to_owned(),
callback,
});
}
let mut tools: Vec<String> = Vec::new();
for manifest in take_staged_items(&STAGED) {
tools.push(manifest.name.clone());
if let Err(error) = self.register(manifest) {
return Err(Error::Malformed(format!("{name}: {error}")));
}
}
Ok(LoadedScript {
file: PathBuf::from(name),
tools,
hooks: self.hooks.len().saturating_sub(hooks_before),
})
}
#[must_use]
pub fn guard<'a>(&'a self, inner: &'a dyn yk_core::Tool) -> HookGuardedTool<'a> {
HookGuardedTool {
inner,
lua: &self.lua,
hooks: &self.hooks,
budget: &self.budget,
}
}
#[must_use]
pub fn hooks(&self) -> &[Hook] {
&self.hooks
}
#[must_use]
pub fn tools(&self) -> Vec<LuaTool<'_>> {
self.tools
.values()
.map(|manifest| {
LuaTool::new(
&self.lua,
manifest.name.clone(),
manifest.description.clone(),
manifest.schema.clone(),
&manifest.callback,
&self.budget,
)
})
.collect()
}
pub fn register(&mut self, manifest: ToolInfo) -> Result<()> {
if manifest.name.is_empty() {
return Err(Error::BadArgs {
tool: "register_tool".to_owned(),
reason: "a tool needs a name".to_owned(),
});
}
if is_builtin(&manifest.name) {
return Err(Error::Malformed(format!(
"`{}` is a built-in tool and cannot be replaced",
manifest.name
)));
}
self.tools.insert(manifest.name.clone(), manifest);
Ok(())
}
#[must_use]
pub fn len(&self) -> usize {
self.tools.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
#[must_use]
pub const fn lua(&self) -> &Lua {
&self.lua
}
}
thread_local! {
static STAGED: std::cell::RefCell<Vec<ToolInfo>> =
const { std::cell::RefCell::new(Vec::new()) };
static STAGED_HOOKS: std::cell::RefCell<Vec<mlua::Function>> =
const { std::cell::RefCell::new(Vec::new()) };
}
fn stage<T>(slot: &'static std::thread::LocalKey<std::cell::RefCell<Vec<T>>>, item: T) {
slot.with(|cell| cell.borrow_mut().push(item));
}
fn take_staged_items<T>(
slot: &'static std::thread::LocalKey<std::cell::RefCell<Vec<T>>>,
) -> Vec<T> {
slot.with(|cell| std::mem::take(&mut *cell.borrow_mut()))
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LoadedScript {
pub file: PathBuf,
pub tools: Vec<String>,
pub hooks: usize,
}
fn set_capability(table: &mlua::Table, name: &str, function: mlua::Function) -> Result<()> {
table.set(name, function).map_err(|e| lua_error(&e))
}
fn lua_error(error: &mlua::Error) -> Error {
Error::Malformed(error.to_string())
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use std::sync::Arc;
use yk_core::Tool as _;
use crate::{DenyHost, Host, Registry};
fn denying() -> Arc<dyn Host> {
Arc::new(DenyHost)
}
fn registry() -> Registry {
Registry::new(&denying()).expect("builds a vm")
}
#[test]
fn a_fresh_registry_has_no_tools() {
let registry = registry();
assert!(registry.is_empty());
assert!(registry.tools().is_empty());
}
#[test]
fn io_is_not_reachable_from_a_script() {
let mut registry = registry();
let error = registry
.load_source(r#"return io.open("/etc/passwd")"#, "escape.lua")
.expect_err("must fail");
assert!(error.to_string().contains("escape.lua"), "{error}");
}
#[test]
fn os_is_not_reachable_from_a_script() {
let registry = registry();
let kind: String = registry
.lua()
.load(r"return type(os)")
.eval()
.expect("evaluates");
assert_eq!(kind, "nil");
}
#[test]
fn package_is_not_reachable_from_a_script() {
let mut registry = registry();
assert!(
registry
.load_source(r#"return package.loadlib("x", "y")"#, "escape.lua")
.is_err()
);
}
#[test]
fn debug_is_not_reachable_from_a_script() {
let registry = registry();
let kind: String = registry
.lua()
.load(r"return type(debug)")
.eval()
.expect("evaluates");
assert_eq!(kind, "nil");
}
#[test]
fn ffi_is_not_reachable_from_a_script() {
let registry = registry();
let kind: String = registry
.lua()
.load(r"return type(ffi)")
.eval()
.expect("evaluates");
assert_eq!(kind, "nil");
}
#[test]
fn rawset_cannot_reach_inside_a_sandboxed_library() {
let mut registry = registry();
assert!(
registry
.load_source(r#"rawset(string, "upper", nil)"#, "escape.lua")
.is_err()
);
}
#[test]
fn bytecode_is_refused() {
let mut registry = registry();
let error = registry
.load_source("\u{1b}Lua\x52\x00", "chunk")
.expect_err("must fail");
assert!(error.to_string().contains("chunk"), "{error}");
}
#[test]
fn a_syntax_error_names_the_script() {
let mut registry = registry();
let error = registry
.load_source("this is not lua", "broken.lua")
.expect_err("must fail");
assert!(error.to_string().contains("broken.lua"), "{error}");
}
#[test]
fn a_denying_host_reaches_the_script_as_an_error() {
let mut registry = registry();
let error = registry
.load_source(r#"return host.read_file("/etc/passwd")"#, "read.lua")
.expect_err("must fail");
assert!(error.to_string().contains("read.lua"), "{error}");
}
#[test]
fn the_host_table_has_exactly_the_members_the_records_name() {
let registry = registry();
let host = registry
.lua()
.globals()
.get::<mlua::Table>("host")
.expect("host table");
let mut names = Vec::new();
host.for_each(|name: String, _: mlua::Value| {
names.push(name);
Ok::<(), mlua::Error>(())
})
.expect("iterates");
names.sort();
assert_eq!(
names,
[
"env",
"http_get",
"http_post_json",
"json",
"json_encode",
"read_file",
"register_tool",
]
);
}
#[test]
fn the_runner_global_is_installed() {
let registry = registry();
let runner = registry
.lua()
.globals()
.get::<mlua::Value>("runner")
.expect("runner global");
assert!(
matches!(runner, mlua::Value::UserData(_)),
"runner is userdata"
);
}
#[test]
fn json_round_trips_through_the_host() {
let registry = registry();
let encoded: String = registry
.lua()
.load(r#"return host.json_encode({ a = 1, b = { c = "x" } })"#)
.eval()
.expect("evaluates");
assert_eq!(encoded, r#"{"a":1,"b":{"c":"x"}}"#);
}
#[test]
fn a_denying_host_reaches_a_post_as_an_error() {
let mut registry = registry();
let error = registry
.load_source(
r#"return host.http_post_json("https://example.com", {}, "{}")"#,
"post.lua",
)
.expect_err("must fail");
assert!(error.to_string().contains("post.lua"), "{error}");
}
#[test]
fn an_unset_environment_variable_is_nil_rather_than_an_error() {
let registry = registry();
let kind: String = registry
.lua()
.load(r#"return type(host.env("YK_DEFINITELY_NOT_SET_12345"))"#)
.eval()
.expect("evaluates");
assert_eq!(kind, "nil");
}
#[test]
fn json_decodes_into_a_lua_table() {
let registry = registry();
let decoded: String = registry
.lua()
.load(r#"return type(host.json('{"a":1}'))"#)
.eval()
.expect("evaluates");
assert_eq!(decoded, "table");
}
#[test]
fn a_missing_directory_loads_nothing_rather_than_failing() {
let mut registry = registry();
let loaded = registry
.load_dir(Path::new("/nonexistent/yk/lua"))
.expect("loads");
assert!(loaded.is_empty());
}
#[tokio::test]
async fn a_script_under_the_instruction_limit_runs_to_completion() {
let mut registry = registry();
registry
.load_source(
r#"host.register_tool("count", "Counts", {}, function()
local sum = 0
for i = 1, 100 do sum = sum + i end
return tostring(sum)
end)"#,
"count.lua",
)
.expect("loads");
let tools = registry.tools();
let counting = tools
.iter()
.find(|tool| tool.name() == "count")
.expect("the tool is registered");
let out = counting
.clone()
.with_timeout(std::time::Duration::from_secs(5))
.run(&serde_json::json!({}))
.await
.expect("runs");
assert_eq!(out, "5050");
}
#[tokio::test]
async fn a_script_spawns_a_process_through_the_runner() {
let mut registry = registry();
registry
.load_source(
r#"host.register_tool("echo", "Echo", {}, function()
local result = runner.spawn_tool("echo", { "hi" })
return result.stdout
end)"#,
"echo.lua",
)
.expect("loads");
let tools = registry.tools();
let echoing = tools
.iter()
.find(|tool| tool.name() == "echo")
.expect("the tool is registered");
let out = echoing
.clone()
.with_timeout(std::time::Duration::from_secs(5))
.run(&serde_json::json!({}))
.await
.expect("runs");
assert_eq!(out.trim(), "hi");
}
#[tokio::test]
async fn a_non_coercible_argument_to_spawn_tool_is_an_error() {
let mut registry = registry();
registry
.load_source(
r#"host.register_tool("bad", "Bad", {}, function()
return runner.spawn_tool("echo", { true })
end)"#,
"bad.lua",
)
.expect("loads");
let tools = registry.tools();
let bad = tools
.iter()
.find(|tool| tool.name() == "bad")
.expect("the tool is registered");
let error = bad
.clone()
.run(&serde_json::json!({}))
.await
.expect_err("must fail");
assert!(error.to_string().contains("args"), "{error}");
}
use std::path::Path;
}