yk-lua 0.1.0

Extensions written in Lua, running in an embedded Luau VM
Documentation
//! The process gateway: the one way an extension reaches the system.
//!
//! An extension that needs a file, a network service, or another binary asks
//! the host to run a process. The child is a separate OS process: isolated by
//! the kernel, killable by the host, and unable to touch agent memory no matter
//! what it does.
//!
//! This is the sanctioned replacement for everything FFI was going to provide.
//! An extension that needs a library writes a small CLI that speaks over stdio
//! and the host runs it. The extension is still plain Lua you can read, plus a
//! list of processes it asked the host to run.

use std::process::Stdio;
use std::time::Duration;

use mlua::{Lua, UserData, UserDataMethods};

use crate::TOOL_TIMEOUT;

/// How long a child process may run before it is killed.
///
/// The same deadline a tool call gets, so the documented containment holds: a
/// child cannot outlive the call that started it. The interrupt cannot fire
/// while the Lua coroutine is awaiting the child, so the child's own timer is
/// the only thing that ends the wait; a longer one would let the tool call
/// outlive its deadline by that much.
const CHILD_TIMEOUT: Duration = TOOL_TIMEOUT;

/// The most output a child may produce, in bytes.
///
/// A CLI that prints a runaway log should not turn one tool call into a
/// permanent storage problem. The cap is generous enough for any real CLI
/// result and small enough that a session file stays a session file.
const MAX_OUTPUT: usize = 1024 * 1024;

/// The process gateway, installed as the `runner` global.
///
/// One function: `spawn_tool(command, args)`, returning
/// `{code, stdout, stderr, truncated}`. A non-zero exit is a value, not an
/// error. A spawn failure or timeout is an error. No shell, no string
/// interpolation into a shell command.
#[derive(Clone, Copy, Debug)]
pub struct ProcessRunner;

impl ProcessRunner {
    /// Run a child process and return its output.
    ///
    /// `command` is a program name, `args` a list of arguments. The child
    /// runs on the Tokio runtime, not on the executor thread the Lua call is
    /// waiting on, so capturing and transferring do not block the main
    /// executor thread pool.
    ///
    /// # Errors
    ///
    /// [`mlua::Error`] when the command cannot be started, exceeds its
    /// deadline, or produces output that is not valid UTF-8.
    async fn spawn_tool(lua: &Lua, command: &str, args: &[String]) -> mlua::Result<mlua::Table> {
        Self::spawn_tool_within(lua, command, args, CHILD_TIMEOUT).await
    }

    /// The same, with the deadline passed in rather than fixed, so a test can
    /// exercise the timeout without waiting the production 30 seconds.
    async fn spawn_tool_within(
        lua: &Lua,
        command: &str,
        args: &[String],
        timeout: Duration,
    ) -> mlua::Result<mlua::Table> {
        let child = tokio::process::Command::new(command)
            .args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| mlua::Error::RuntimeError(format!("could not start `{command}`: {e}")))?;

        // Dropping the future on timeout drops the child, and `kill_on_drop`
        // kills it, so a child that runs long is stopped rather than leaked.
        let output = tokio::time::timeout(timeout, child.wait_with_output())
            .await
            .map_err(|_| mlua::Error::RuntimeError(format!("`{command}` exceeded {timeout:?}")))?
            .map_err(|e| mlua::Error::RuntimeError(format!("`{command}`: {e}")))?;

        let stdout = String::from_utf8(output.stdout).map_err(|_| {
            mlua::Error::RuntimeError(format!("`{command}` stdout is not valid UTF-8"))
        })?;
        let stderr = String::from_utf8(output.stderr).map_err(|_| {
            mlua::Error::RuntimeError(format!("`{command}` stderr is not valid UTF-8"))
        })?;

        let truncated = stdout.len() > MAX_OUTPUT || stderr.len() > MAX_OUTPUT;

        let table = lua
            .create_table()
            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
        table
            // `-1` when a signal killed the child, which has no exit code. A
            // signal kill is a value the script can inspect, like any other
            // non-zero exit.
            .set("code", output.status.code().unwrap_or(-1))
            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
        table
            .set("stdout", truncate(&stdout, MAX_OUTPUT))
            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
        table
            .set("stderr", truncate(&stderr, MAX_OUTPUT))
            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
        // Set when either stream was cut at `MAX_OUTPUT`, so a script is not
        // silently handed a prefix of its output.
        table
            .set("truncated", truncated)
            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
        Ok(table)
    }
}

impl UserData for ProcessRunner {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        // A function rather than a method, so a script calls it as
        // `runner.spawn_tool(...)` and not `runner:spawn_tool(...)`. There is
        // one runner and it holds no state, so a colon would be a lie.
        methods.add_async_function(
            "spawn_tool",
            |lua, (command, args): (String, mlua::Table)| async move {
                let mut argv = Vec::new();
                for arg in args.sequence_values::<String>() {
                    argv.push(arg.map_err(|e| mlua::Error::RuntimeError(format!("args: {e}")))?);
                }
                Self::spawn_tool(&lua, &command, &argv).await
            },
        );
    }
}

/// Truncate a string to at most `max` bytes, on a UTF-8 boundary.
fn truncate(text: &str, max: usize) -> &str {
    if text.len() <= max {
        return text;
    }
    let mut end = max;
    while end > 0 && !text.is_char_boundary(end) {
        end = end.saturating_sub(1);
    }
    text.get(..end).unwrap_or(text)
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::indexing_slicing,
        clippy::as_conversions,
        clippy::arithmetic_side_effects
    )]

    use mlua::Lua;

    use super::{ProcessRunner, truncate};

    #[test]
    fn truncate_cuts_on_a_utf8_boundary() {
        assert_eq!(truncate("hello", 10), "hello");
        assert_eq!(truncate("hello", 3), "hel");
        // A multi-byte character at the cut point is not split.
        assert_eq!(truncate("héllo", 3), "hé");
        assert_eq!(truncate("héllo", 2), "h");
    }

    #[tokio::test]
    async fn spawn_tool_runs_a_real_process_and_returns_its_stdout() {
        let lua = Lua::new();
        let table = ProcessRunner::spawn_tool(&lua, "echo", &["hello".to_owned()])
            .await
            .expect("runs");
        let code: i64 = table.get("code").expect("code");
        let stdout: String = table.get("stdout").expect("stdout");
        assert_eq!(code, 0);
        assert_eq!(stdout.trim(), "hello");
    }

    #[tokio::test]
    async fn a_non_zero_exit_is_a_value_carrying_the_code() {
        let lua = Lua::new();
        let table = ProcessRunner::spawn_tool(&lua, "sh", &["-c".to_owned(), "exit 3".to_owned()])
            .await
            .expect("runs");
        let code: i64 = table.get("code").expect("code");
        assert_eq!(code, 3);
    }

    #[tokio::test]
    async fn an_unknown_command_is_an_error() {
        let lua = Lua::new();
        let error = ProcessRunner::spawn_tool(&lua, "yk-definitely-not-a-real-binary-12345", &[])
            .await
            .expect_err("must fail");
        assert!(error.to_string().contains("could not start"), "{error}");
    }

    #[tokio::test]
    async fn stderr_is_captured() {
        let lua = Lua::new();
        let table =
            ProcessRunner::spawn_tool(&lua, "sh", &["-c".to_owned(), "echo oops >&2".to_owned()])
                .await
                .expect("runs");
        let stderr: String = table.get("stderr").expect("stderr");
        assert!(stderr.contains("oops"), "{stderr}");
    }

    #[tokio::test]
    async fn a_child_that_outruns_its_deadline_is_killed_and_reported() {
        let lua = Lua::new();
        let error = ProcessRunner::spawn_tool_within(
            &lua,
            "sleep",
            &["30".to_owned()],
            std::time::Duration::from_millis(100),
        )
        .await
        .expect_err("must time out");
        assert!(error.to_string().contains("exceeded"), "{error}");
    }

    #[tokio::test]
    async fn output_over_the_cap_is_truncated_and_flagged() {
        let lua = Lua::new();
        let table = ProcessRunner::spawn_tool(
            &lua,
            "sh",
            &["-c".to_owned(), "yes | head -c 2000000".to_owned()],
        )
        .await
        .expect("runs");
        let stdout: String = table.get("stdout").expect("stdout");
        let truncated: bool = table.get("truncated").expect("truncated");
        assert_eq!(stdout.len(), super::MAX_OUTPUT);
        assert!(truncated);
    }

    #[tokio::test]
    async fn a_signal_killed_child_reports_minus_one() {
        let lua = Lua::new();
        let table =
            ProcessRunner::spawn_tool(&lua, "sh", &["-c".to_owned(), "kill -9 $$".to_owned()])
                .await
                .expect("runs");
        let code: i64 = table.get("code").expect("code");
        assert_eq!(code, -1);
    }
}