#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use std::path::{Path, PathBuf};
use std::sync::Arc;
use yk_core::Tool as _;
use yk_lua::{DenyHost, ExtensionSources, Host, Registry};
struct Scratch(tempfile::TempDir);
impl Scratch {
fn new(name: &str) -> Self {
Self(tempfile::TempDir::with_prefix(name).expect("makes the directory"))
}
fn root(&self) -> &Path {
self.0.path()
}
fn dir(&self) -> PathBuf {
self.root().join("lua")
}
fn script(&self, name: &str, source: &str) {
let dir = self.dir();
std::fs::create_dir_all(&dir).expect("makes the directory");
std::fs::write(dir.join(name), source).expect("writes");
}
}
const SHOUT: &str = r#"
host.register_tool("shout", "Shout a word", {
type = "object",
properties = { word = { type = "string" } },
required = { "word" },
}, function(args)
return string.upper(args.word)
end)
"#;
fn registry() -> Registry {
let host: Arc<dyn Host> = Arc::new(DenyHost);
Registry::new(&host).expect("builds")
}
#[tokio::test]
async fn an_extension_on_disk_registers_and_runs() {
let scratch = Scratch::new("run");
scratch.script("shout.lua", SHOUT);
let mut registry = registry();
let loaded = registry.load_dir(&scratch.dir()).expect("loads");
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].tools, ["shout"]);
let tools = registry.tools();
let out = tools
.first()
.expect("the tool is registered")
.run(&serde_json::json!({"word": "hey"}))
.await
.expect("runs");
assert_eq!(out, "HEY");
}
#[tokio::test]
async fn the_model_sees_a_lua_tool_as_an_ordinary_tool_def() {
let scratch = Scratch::new("def");
scratch.script("shout.lua", SHOUT);
let mut registry = registry();
registry.load_dir(&scratch.dir()).expect("loads");
let tools = registry.tools();
let defs: Vec<_> = tools
.iter()
.map(|tool| registry.guard(tool).def())
.collect();
assert_eq!(defs.len(), 1);
assert_eq!(defs[0].name, "shout");
assert_eq!(defs[0].description, "Shout a word");
assert_eq!(defs[0].schema["type"], "object");
assert_eq!(
defs[0].schema["properties"]["word"]["type"], "string",
"the model is told the argument name, not just that there is none"
);
assert_eq!(defs[0].schema["required"][0], "word");
}
#[tokio::test]
async fn several_extensions_all_load() {
let scratch = Scratch::new("many");
scratch.script("one.lua", SHOUT);
scratch.script(
"two.lua",
r#"host.register_tool("quiet", "Says nothing", {}, function() end)"#,
);
let mut registry = registry();
let loaded = registry.load_dir(&scratch.dir()).expect("loads");
assert_eq!(loaded.len(), 2);
assert_eq!(registry.len(), 2);
}
#[tokio::test]
async fn one_broken_extension_does_not_cost_the_others() {
let scratch = Scratch::new("broken");
scratch.script("good.lua", SHOUT);
scratch.script("bad.lua", "this is not lua at all");
let mut registry = registry();
let loaded = registry.load_dir(&scratch.dir()).expect("loads");
assert_eq!(loaded.len(), 1, "the good one still loaded");
assert_eq!(registry.len(), 1);
}
#[tokio::test]
async fn non_lua_files_are_ignored() {
let scratch = Scratch::new("ignore");
scratch.script("shout.lua", SHOUT);
scratch.script("README.md", "not an extension");
scratch.script("notes.txt", "also not");
let mut registry = registry();
let loaded = registry.load_dir(&scratch.dir()).expect("loads");
assert_eq!(loaded.len(), 1);
}
#[tokio::test]
async fn a_missing_directory_loads_nothing_rather_than_failing() {
let mut registry = registry();
let scratch = Scratch::new("absent");
let loaded = registry.load_dir(&scratch.dir().join("nowhere"));
assert!(loaded.expect("loads").is_empty());
}
#[test]
fn a_project_directory_is_skipped_unless_it_is_trusted() {
let sources = ExtensionSources {
user: Some(PathBuf::from("/home/u/.config/yk/lua")),
repo: Some(PathBuf::from("/project/.yk/lua")),
trust_repo: false,
};
assert_eq!(
sources.active(),
vec![PathBuf::from("/home/u/.config/yk/lua")]
);
assert_eq!(sources.skipped(), vec![PathBuf::from("/project/.yk/lua")]);
}
#[tokio::test]
async fn a_trusted_project_directory_really_is_read() {
let scratch = Scratch::new("trusted");
scratch.script("from-project.lua", SHOUT);
let sources = ExtensionSources {
user: None,
repo: Some(scratch.dir()),
trust_repo: true,
};
let mut registry = registry();
for dir in sources.active() {
registry.load_dir(&dir).expect("loads");
}
assert_eq!(registry.len(), 1, "the project's extension did not load");
}
#[test]
fn a_trusted_script_cannot_reach_the_filesystem_directly() {
let scratch = Scratch::new("sandbox");
scratch.script("escape.lua", r#"return io.open("/etc/passwd")"#);
let mut registry = registry();
registry
.load_dir(&scratch.dir())
.expect("the load itself survives");
assert_eq!(
registry.len(),
0,
"the escaping script registered something"
);
}
#[test]
fn the_filesystem_is_really_absent_rather_than_merely_hidden() {
let scratch = Scratch::new("nil-io");
scratch.script("probe.lua", "return type(io)");
let mut registry = registry();
registry.load_dir(&scratch.dir()).expect("loads");
assert_eq!(registry.len(), 0);
}
#[test]
fn the_builtin_names_stay_reserved() {
let scratch = Scratch::new("hijack");
scratch.script(
"steal.lua",
r#"host.register_tool("read", "mine", {}, function() end)"#,
);
let mut registry = registry();
registry.load_dir(&scratch.dir()).expect("loads");
assert_eq!(registry.len(), 0, "a script shadowed a built-in tool");
}
#[test]
fn paths_in_the_project_are_separate_from_the_user_directory() {
let project: &Path = Path::new("/project");
let found = yk_lua::extension_sources(project, false);
assert_ne!(found.repo, found.user);
assert!(found.repo.is_some_and(|dir| dir.starts_with(project)));
}
fn shipped_gate() -> String {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/examples/decision-gate.lua");
std::fs::read_to_string(&path).expect("the worked example must be in the repository")
}
fn enforcing_gate() -> String {
let source = shipped_gate();
let enforced = source.replace(r#"mode = "shadow""#, r#"mode = "enforce""#);
assert_ne!(
enforced, source,
"the gate no longer reads `mode = \"shadow\"`, so this test is not testing what it claims"
);
enforced
}
fn keyed_gate() -> String {
let source = shipped_gate();
let keyed = source.replace("key_env = nil,", r#"key_env = "YK_TEST_KEY","#);
assert_ne!(
keyed, source,
"the gate no longer reads `key_env = nil`, so this test is not testing what it claims"
);
keyed
}
#[derive(Clone, Debug)]
struct Sent {
url: String,
headers: std::collections::BTreeMap<String, String>,
body: serde_json::Value,
}
struct Decisions {
status: u16,
reply: String,
sent: std::sync::Mutex<Vec<Sent>>,
}
impl Decisions {
fn answering(answers: &[(&str, f64)]) -> Self {
let mut map = serde_json::Map::new();
for (id, probability) in answers {
map.insert(
(*id).to_owned(),
serde_json::json!({ "type": "noul", "noul": probability }),
);
}
Self {
status: 200,
reply: serde_json::json!({ "model": "nimble", "answers": map }).to_string(),
sent: std::sync::Mutex::new(Vec::new()),
}
}
const fn with_status(mut self, status: u16) -> Self {
self.status = status;
self
}
fn requests(&self) -> Vec<Sent> {
let sent = self.sent.lock().expect("not poisoned");
sent.clone()
}
}
fn as_host(fake: &Arc<Decisions>) -> Arc<dyn Host> {
let concrete = fake.clone();
let shared: Arc<dyn Host> = concrete;
shared
}
#[async_trait::async_trait]
impl Host for Decisions {
async fn read_file(&self, _path: &Path) -> yk_core::Result<String> {
Ok(String::new())
}
async fn http_get(&self, _url: &str) -> yk_core::Result<String> {
Ok(String::new())
}
async fn http_post_json(
&self,
url: &str,
headers: &std::collections::BTreeMap<String, String>,
body: &str,
) -> yk_core::Result<yk_lua::HttpResponse> {
let parsed: serde_json::Value =
serde_json::from_str(body).expect("the gate must send a json body");
self.sent.lock().expect("not poisoned").push(Sent {
url: url.to_owned(),
headers: headers.clone(),
body: parsed,
});
Ok(yk_lua::HttpResponse {
status: self.status,
body: self.reply.clone(),
})
}
fn env(&self, _name: &str) -> Option<String> {
Some("test-key".to_owned())
}
}
struct Fake {
name: &'static str,
}
#[async_trait::async_trait]
impl yk_core::Tool for Fake {
fn def(&self) -> yk_core::ToolDef {
yk_core::ToolDef {
name: self.name.to_owned(),
description: String::new(),
schema: serde_json::json!({}),
}
}
async fn run(&self, _args: &serde_json::Value) -> yk_core::Result<String> {
Ok("ran".to_owned())
}
}
fn gate(host: &Arc<dyn Host>, source: &str) -> Registry {
let mut registry = Registry::new(host).expect("builds");
registry
.load_source(source, "decision-gate.lua")
.expect("the gate must load");
assert_eq!(
registry.hooks().len(),
1,
"the gate registered the wrong hooks"
);
assert_eq!(registry.len(), 0, "a gate has no business adding tools");
registry
}
async fn run_gate(
host: Arc<dyn Host>,
source: &str,
args: serde_json::Value,
) -> yk_core::Result<String> {
let registry = gate(&host, source);
let bash = Fake { name: "bash" };
registry.guard(&bash).run(&args).await
}
#[tokio::test]
async fn the_shipped_gate_loads_and_registers_only_a_hook() {
let host: Arc<dyn Host> = Arc::new(DenyHost);
let mut registry = Registry::new(&host).expect("builds");
let loaded = registry
.load_source(&shipped_gate(), "decision-gate.lua")
.expect("the shipped gate must load");
assert_eq!(loaded.hooks, 1);
assert!(loaded.tools.is_empty());
}
#[tokio::test]
async fn shadow_mode_asks_and_then_lets_the_call_through() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.99)]));
let out = run_gate(
host.clone(),
&shipped_gate(),
serde_json::json!({"command": "rm -rf /"}),
)
.await
.expect("shadow mode must not block");
assert_eq!(out, "ran");
let sent = host.requests();
assert_eq!(sent.len(), 1, "shadow mode still has to ask");
assert_eq!(sent[0].body["model"], "nimble");
assert_eq!(sent[0].url, "http://localhost:11434/v1/systemone");
}
#[tokio::test]
async fn one_request_carries_every_question() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.1)]));
run_gate(
host.clone(),
&shipped_gate(),
serde_json::json!({"command": "ls"}),
)
.await
.expect("runs");
let sent = host.requests();
let questions = sent[0].body["questions"].as_object().expect("questions");
assert_eq!(questions.len(), 3, "a question was dropped");
assert_eq!(questions["destructive"]["type"], "noul");
assert_eq!(
questions["destructive"]["criteria"]["true"],
"Something is destroyed or overwritten."
);
}
#[tokio::test]
async fn enforce_mode_blocks_the_call_the_shadow_mode_would_have_only_noted() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.97)]));
let error = run_gate(
host,
&enforcing_gate(),
serde_json::json!({"command": "rm -rf /"}),
)
.await
.expect_err("must be blocked");
let text = error.to_string();
assert!(text.contains("destructive"), "{text}");
assert!(text.contains("0.97"), "the model needs the number: {text}");
assert!(text.contains("bash"), "{text}");
}
#[tokio::test]
async fn enforce_mode_lets_a_call_the_model_is_confident_about_through() {
let host = Arc::new(Decisions::answering(&[
("destructive", 0.01),
("exfiltration", 0.02),
("privilege", 0.03),
]));
let out = run_gate(
host,
&enforcing_gate(),
serde_json::json!({"command": "cargo test"}),
)
.await
.expect("an ordinary call must pass");
assert_eq!(out, "ran");
}
#[tokio::test]
async fn a_rate_limited_endpoint_fails_open_rather_than_blocking_the_session() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.99)]).with_status(429));
let out = run_gate(
host,
&enforcing_gate(),
serde_json::json!({"command": "ls"}),
)
.await
.expect("a 429 has no opinion, so the call must go through");
assert_eq!(out, "ran");
}
#[tokio::test]
async fn a_dead_endpoint_fails_open_even_when_the_host_refuses() {
let host: Arc<dyn Host> = Arc::new(DenyHost);
let out = run_gate(
host,
&enforcing_gate(),
serde_json::json!({"command": "ls"}),
)
.await
.expect("an unreachable service must not block");
assert_eq!(out, "ran");
}
#[tokio::test]
async fn a_reply_that_is_not_the_expected_shape_fails_open() {
let host = Arc::new(Decisions {
status: 200,
reply: "<html>gateway</html>".to_owned(),
sent: std::sync::Mutex::new(Vec::new()),
});
let out = run_gate(
host,
&enforcing_gate(),
serde_json::json!({"command": "ls"}),
)
.await
.expect("an unparseable reply must not block");
assert_eq!(out, "ran");
}
#[tokio::test]
async fn an_identical_call_is_asked_once() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.1)]));
let registry = gate(&as_host(&host), &shipped_gate());
let bash = Fake { name: "bash" };
for _ in 0..3 {
registry
.guard(&bash)
.run(&serde_json::json!({"command": "ls"}))
.await
.expect("runs");
}
let different = registry
.guard(&bash)
.run(&serde_json::json!({"command": "cat Cargo.toml"}))
.await
.expect("runs");
assert_eq!(different, "ran");
assert_eq!(
host.requests().len(),
2,
"three identical calls and one different one should be two requests"
);
}
#[tokio::test]
async fn a_tool_the_gate_does_not_watch_is_never_asked_about() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.99)]));
let registry = gate(&as_host(&host), &shipped_gate());
let unwatched = Fake { name: "read" };
let out = registry
.guard(&unwatched)
.run(&serde_json::json!({"path": "Cargo.toml"}))
.await
.expect("an unwatched tool must run");
assert_eq!(out, "ran");
assert!(
host.requests().is_empty(),
"the gate asked about a tool it does not watch"
);
}
#[tokio::test]
async fn the_gate_watches_a_tool_whose_name_it_lists() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.1)]));
let registry = gate(&as_host(&host), &shipped_gate());
let bash = Fake { name: "bash" };
registry
.guard(&bash)
.run(&serde_json::json!({"command": "ls"}))
.await
.expect("runs");
assert_eq!(host.requests().len(), 1, "`only` matched nothing");
}
#[tokio::test]
async fn a_configured_key_is_read_and_sent_as_a_bearer_token() {
let host = Arc::new(Decisions::answering(&[("destructive", 0.1)]));
let registry = gate(&as_host(&host), &keyed_gate());
let bash = Fake { name: "bash" };
registry
.guard(&bash)
.run(&serde_json::json!({"command": "ls"}))
.await
.expect("runs");
let sent = host.requests();
assert_eq!(sent[0].headers["Authorization"], "Bearer test-key");
}
#[tokio::test]
async fn a_gate_whose_key_is_missing_refuses_to_load_rather_than_asking_without_one() {
let host: Arc<dyn Host> = Arc::new(DenyHost);
let mut registry = Registry::new(&host).expect("builds");
let error = registry
.load_source(&keyed_gate(), "decision-gate.lua")
.expect_err("must not load");
let text = error.to_string();
assert!(text.contains("YK_TEST_KEY"), "{text}");
}