Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,130 @@
//! Execution requests — `test` commands and `debug` launches judged by the Bash rules.
//!
//! Both tools start a process the model chose, so they get the same deny/ask rules and guards a
//! `bash` call would. The tool's own key stays checked too, so a rule written for `test` or
//! `debug` still holds.
use std::path::Path;
use super::{build_request, permission_key, primary_input, rule, Check, PermissionRequest};
use crate::permission::wildcard::command_segments;
use crate::permission::PermissionAction;
/// Shells whose `-c` argument is a script of its own.
const SHELLS: [&str; 6] = ["sh", "bash", "zsh", "dash", "ksh", "fish"];
/// Programs that run their first argument, so the shell may be the word after them.
const WRAPPERS: [&str; 5] = ["env", "busybox", "exec", "command", "nohup"];
/// The request for a call that runs a command, or `None` when this call runs nothing new.
pub(super) fn request(
tool: &str,
args: &serde_json::Value,
root: &Path,
) -> Option<PermissionRequest> {
let (command, script, rememberable) = match tool {
"test" => {
let (command, rememberable) = test_command(args)?;
(command, None, rememberable)
}
"debug" if args.get("action").and_then(serde_json::Value::as_str) == Some("launch") => {
let (command, script) = launch_command(args)?;
let rememberable = script.is_none();
(command, script, rememberable)
}
_ => return None,
};
let mut request = build_request("bash", &serde_json::json!({"command": command}), root);
if let Some(script) = &script {
let inner = build_request("bash", &serde_json::json!({"command": script}), root);
request.checks.extend(inner.checks);
}
request.permission = permission_key(tool).into();
request.tool = tool.into();
let input = primary_input(tool, args);
request
.checks
.insert(0, Check { permission: request.permission.clone(), input: input.clone() });
// Exact rules only: approving `cargo test` here must not allow `cargo publish` through bash
request.always = match (rememberable && !request.always.is_empty(), exact(&command)) {
(true, Some(command)) => vec![
rule("bash", command, PermissionAction::Allow),
rule(&request.permission, &input, PermissionAction::Allow),
],
_ => Vec::new(),
};
Some(request)
}
/// The command a `test` call runs, and whether approving it may be remembered.
///
/// The filter is appended unquoted, so `unit; rm -rf /` is two commands. Without an explicit
/// command the detected one is not known here, so only what follows the filter's first segment is
/// judged, and never remembered; a plain filter adds nothing.
fn test_command(args: &serde_json::Value) -> Option<(String, bool)> {
let filter = args
.get("filter")
.and_then(serde_json::Value::as_str)
// untrimmed, as the runner appends it: a leading newline is a separator
.filter(|filter| !filter.trim().is_empty());
match (args.get("command").and_then(serde_json::Value::as_str), filter) {
(Some(command), Some(filter)) => Some((format!("{command} {filter}"), true)),
(Some(command), None) => Some((command.into(), true)),
(None, Some(filter)) => smuggled(filter).map(|tail| (tail, false)),
(None, None) => None,
}
}
fn smuggled(filter: &str) -> Option<String> {
// behind a stand-in head, as it runs: a filter that opens with `;` still starts a new command
let segments = command_segments(&format!("test {filter}"));
let tail = segments.get(1..).filter(|tail| !tail.is_empty())?;
let tail: Vec<String> = tail.iter().map(|segment| segment.join(" ")).collect();
// the fork bomb is spotted on the raw text, which splitting into segments would destroy
Some(if super::is_fork_bomb(filter) { filter.into() } else { tail.join(" ; ") })
}
/// The command line a `debug launch` runs, and the script a shell launched with `-c` would run.
fn launch_command(args: &serde_json::Value) -> Option<(String, Option<String>)> {
let program = args.get("program")?.as_str()?;
let arguments: Vec<&str> = args
.get("args")
.and_then(serde_json::Value::as_array)
.into_iter()
.flatten()
.filter_map(serde_json::Value::as_str)
.collect();
let command = std::iter::once(program).chain(arguments.iter().copied()).collect::<Vec<_>>();
Some((command.join(" "), shell_script(program, &arguments)))
}
fn shell_script(program: &str, arguments: &[&str]) -> Option<String> {
let words: Vec<&str> = std::iter::once(program).chain(arguments.iter().copied()).collect();
let mut index = 0;
while WRAPPERS.contains(&program_name(words.get(index)?)) {
index += 1;
// a wrapper's own flags and `env`'s assignments come before the program it runs
while words.get(index).is_some_and(|word| word.starts_with('-') || word.contains('=')) {
index += 1;
}
}
if !SHELLS.contains(&program_name(words[index])) {
return None;
}
let rest = &words[index + 1..];
let flag = rest
.iter()
.position(|arg| arg.starts_with('-') && !arg.starts_with("--") && arg.contains('c'))?;
rest.get(flag + 1).map(|script| (*script).to_string())
}
/// A program's bare name, whichever separator its path uses and with any `.exe` dropped.
fn program_name(word: &str) -> &str {
let name = word.rsplit(['/', '\\']).next().unwrap_or(word);
name.strip_suffix(".exe").unwrap_or(name)
}
/// `command` as a rule matching only itself, or `None` when a wildcard in it would widen the rule.
fn exact(command: &str) -> Option<&str> {
(!command.contains(['*', '?'])).then_some(command)
}

View File

@@ -0,0 +1,123 @@
//! Search scopes — read-policy and external-directory checks for tool search roots.
use std::path::Path;
use super::{is_external, normalize, rule, Check, Rule, EXTERNAL_DIRECTORY};
use crate::permission::PermissionAction;
pub(super) fn search_roots(tool: &str, args: &serde_json::Value) -> Vec<String> {
if tool == "ast_grep" {
return ast_grep_roots(args);
}
if matches!(tool, "module_report" | "read_symbol" | "lsp_navigation") {
return lsp_file_roots(args);
}
if tool == "lsp_diagnostics" {
return diagnostics_roots(args);
}
if !matches!(tool, "grep" | "glob") {
return Vec::new();
}
let path = args
.get("path")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|path| !path.is_empty())
.unwrap_or(".");
vec![path.into()]
}
pub(super) fn ast_grep_roots(args: &serde_json::Value) -> Vec<String> {
let mut paths = match args.get("paths").or_else(|| args.get("path")) {
Some(serde_json::Value::String(path)) => vec![path.clone()],
Some(serde_json::Value::Array(paths)) => {
paths.iter().filter_map(|path| path.as_str().map(str::to_string)).collect()
}
_ => Vec::new(),
};
if paths.is_empty() {
paths.push(".".into());
}
paths
}
pub(super) fn lsp_file_roots(args: &serde_json::Value) -> Vec<String> {
["path", "file", "file_path", "filePath"]
.into_iter()
.find_map(|key| args.get(key).and_then(serde_json::Value::as_str))
.filter(|path| !path.is_empty())
.map(str::to_string)
.into_iter()
.collect()
}
fn diagnostics_roots(args: &serde_json::Value) -> Vec<String> {
if let Some(paths) = args.get("paths").and_then(serde_json::Value::as_array) {
return paths.iter().filter_map(|path| path.as_str().map(str::to_string)).collect();
}
lsp_file_roots(args)
}
pub(super) fn grep_selector_checks(
tool: &str,
args: &serde_json::Value,
paths: &[String],
) -> Vec<Check> {
if tool != "grep" {
return Vec::new();
}
let Some(selector) = args.get("glob").and_then(serde_json::Value::as_str) else {
return Vec::new();
};
if selector.is_empty()
|| matches!(selector, "." | "..")
|| selector.contains(['*', '?', '[', ']', '{', '}', '!', '/', '\\'])
{
return Vec::new();
}
paths
.iter()
.map(|path| Check {
permission: "read".into(),
input: exact_selector_target(path, selector),
})
.collect()
}
fn exact_selector_target(scope: &str, selector: &str) -> String {
let scope_path = Path::new(scope);
if scope_path.file_name().and_then(|name| name.to_str()) == Some(selector) {
return scope.into();
}
crate::paths::display(&scope_path.join(selector))
}
pub(super) fn root_checks(paths: &[String], root: &Path) -> Vec<Check> {
let mut checks = Vec::new();
for path in paths {
checks.push(Check { permission: "read".into(), input: path.clone() });
if is_external(path, root) {
checks.push(Check {
permission: EXTERNAL_DIRECTORY.into(),
input: crate::paths::display(&normalize(path, root)),
});
}
}
checks
}
/// The rules that remember one out-of-project scope: the scope itself and everything under it.
///
/// Only the `external_directory` guard; a pattern-wide rule on the tool could not honestly cover
/// every file the scope holds.
pub(super) fn external_scope_rules(scope: &str, root: &Path) -> Vec<Rule> {
if !is_external(scope, root) {
return Vec::new();
}
let absolute = crate::paths::display(&normalize(scope, root));
let subtree = format!("{}/*", absolute.trim_end_matches('/'));
[absolute, subtree]
.iter()
.map(|pattern| rule(EXTERNAL_DIRECTORY, pattern, PermissionAction::Allow))
.collect()
}

View File

@@ -0,0 +1,430 @@
use super::*;
use serde_json::json;
mod ast_grep_apply;
mod bash_segments;
mod debug_launch;
mod lsp_apply;
mod search_roots;
mod test_commands;
fn root() -> PathBuf {
PathBuf::from("/home/dev/project")
}
#[test]
fn bash_request_has_command_check_and_family_always() {
let req = build_request("bash", &json!({"command": "cargo build --release"}), &root());
assert_eq!(req.permission, "bash");
assert_eq!(req.checks[0].input, "cargo build --release");
assert!(req.always.iter().any(|r| r.pattern == "cargo *"));
}
/// Every file a multi-path read names is judged, so a secret anywhere in the list is denied
/// and a file outside the project anywhere in it asks — the same answers as reading it alone.
#[test]
fn a_read_of_several_files_is_judged_file_by_file() {
let engine = crate::permission::PermissionEngine::new(
crate::permission::defaults::default_ruleset(),
Default::default(),
false,
);
let decide = |args: serde_json::Value| engine.decide(&build_request("read", &args, &root()));
assert_eq!(
decide(json!({"paths": ["src/a.rs", "src/b.rs"]})),
crate::permission::PermissionAction::Allow
);
assert_eq!(
decide(json!({"paths": ["src/a.rs", ".env"]})),
crate::permission::PermissionAction::Deny,
"a secret second in the list"
);
assert_eq!(
decide(json!({"path": "src/a.rs", "paths": ["config/.env"]})),
crate::permission::PermissionAction::Deny,
"or beside a path"
);
assert_eq!(
decide(json!({"paths": ["src/a.rs", "/etc/hosts"]})),
crate::permission::PermissionAction::Ask,
"outside the project, wherever it sits"
);
let several = build_request("read", &json!({"paths": ["a.rs", "b.rs", "c.rs"]}), &root());
assert_eq!(several.summary, "Read a.rs and 2 more");
assert!(several.always.is_empty(), "no single rule covers them all");
}
#[test]
fn write_maps_to_edit_key() {
let req = build_request("write", &json!({"path": "src/x.rs"}), &root());
assert_eq!(req.permission, "edit");
}
#[test]
fn external_path_adds_the_guard_check() {
let inside = build_request("edit", &json!({"path": "src/x.rs"}), &root());
assert!(!inside.checks.iter().any(|c| c.permission == EXTERNAL_DIRECTORY));
let outside = build_request("edit", &json!({"path": "/etc/hosts"}), &root());
assert!(outside.checks.iter().any(|c| c.permission == EXTERNAL_DIRECTORY));
let escape = build_request("read", &json!({"path": "../../../etc/passwd"}), &root());
assert!(escape.checks.iter().any(|c| c.permission == EXTERNAL_DIRECTORY));
}
#[test]
fn an_external_path_offers_directory_scoped_always_rules() {
// Approving one file in someone else's directory must cover the rest of it — and must
// cover the guard that actually fired, not just the tool's own key.
let request = build_request("read", &json!({"path": "/home/dev/notes/one.md"}), &root());
let guard = request
.always
.iter()
.find(|rule| rule.permission == EXTERNAL_DIRECTORY)
.expect("an external read offers an external_directory rule");
assert_eq!(guard.pattern, "/home/dev/notes/*");
assert!(
request
.always
.iter()
.any(|rule| rule.permission == "read" && rule.pattern == "/home/dev/notes/*"),
"the tool key is generalized to the same directory: {:?}",
request.always
);
// Approving it allows the next file in that directory without another prompt.
let mut engine = super::super::PermissionEngine::permissive();
engine.approve(request.always.clone());
let next = build_request("read", &json!({"path": "/home/dev/notes/two.md"}), &root());
assert_eq!(engine.decide(&next), super::super::PermissionAction::Allow);
// A different external directory still asks.
let elsewhere = build_request("read", &json!({"path": "/etc/hosts"}), &root());
assert_eq!(engine.decide(&elsewhere), super::super::PermissionAction::Ask);
}
#[test]
fn a_relative_escape_scopes_both_the_written_and_resolved_directory() {
let request = build_request("edit", &json!({"path": "../sibling/src/x.rs"}), &root());
let patterns = request.always.iter().map(|rule| rule.pattern.as_str()).collect::<Vec<_>>();
assert!(patterns.contains(&"/home/dev/sibling/src/*"), "resolved dir: {patterns:?}");
assert!(patterns.contains(&"../sibling/src/*"), "written dir: {patterns:?}");
}
#[test]
fn an_in_project_path_still_offers_only_that_file() {
let request = build_request("edit", &json!({"path": "src/x.rs"}), &root());
assert_eq!(request.always.len(), 1);
assert_eq!(request.always[0].pattern, "src/x.rs");
}
/// The ledger of work done outside the project and the guard that prompts about it must agree
/// on what "outside" means, so they share this one answer rather than each having their own.
#[test]
fn the_external_target_matches_the_guard_that_fires_on_it() {
for (tool, path) in
[("edit", "/etc/hosts"), ("write", "../sibling/x.rs"), ("read", "~nope/../../etc/x")]
{
let args = json!({ "path": path });
let fired = build_request(tool, &args, &root())
.checks
.iter()
.any(|check| check.permission == EXTERNAL_DIRECTORY);
assert_eq!(
fired,
external_target(tool, &args, &root()).is_some(),
"{tool} {path}: the guard and the ledger disagree"
);
}
// Resolved, not as written: a ledger keyed on the written path would record the same file
// twice under two spellings.
assert_eq!(
external_target("edit", &json!({"path": "../sibling/src/x.rs"}), &root()),
Some(PathBuf::from("/home/dev/sibling/src/x.rs"))
);
assert_eq!(external_target("edit", &json!({"path": "src/x.rs"}), &root()), None);
// Not a path tool: a grep pattern that looks like one is not a file anybody touched.
assert_eq!(external_target("grep", &json!({"pattern": "/etc/hosts"}), &root()), None);
}
/// Reading a file outside the project is worth a prompt but is not a change, so only the
/// mutating tools reach the ledger.
#[test]
fn only_mutating_tools_count_as_work() {
for tool in ["write", "edit", "patch", "apply_patch"] {
assert!(is_mutating_path_tool(tool), "{tool} changes the file it names");
}
for tool in ["read", "grep", "glob", "bash"] {
assert!(!is_mutating_path_tool(tool), "{tool} does not");
}
}
#[test]
fn fork_bomb_adds_the_guard_check() {
let req = build_request("bash", &json!({"command": ":(){ :|:& };:"}), &root());
assert!(req.checks.iter().any(|c| c.permission == FORKBOMB));
let normal = build_request("bash", &json!({"command": "echo hi"}), &root());
assert!(!normal.checks.iter().any(|c| c.permission == FORKBOMB));
}
/// The guard is three independent patterns, and the canonical bomb satisfies all three at
/// once — so testing only that one proves nothing about any of them. Each spelling here trips
/// a different `contains`.
#[test]
fn each_fork_bomb_spelling_trips_the_guard_on_its_own() {
for command in [
":(){ :|:& };:", // the canonical form
": ( ) { : | : & } ; :", // spaced out; whitespace is stripped before matching
"bomb(){ :|:& };bomb", // renamed function, same body
"x() { :|:& }", // the body alone, no invocation yet
] {
let request = build_request("bash", &json!({ "command": command }), &root());
assert!(
request.checks.iter().any(|check| check.permission == FORKBOMB),
"not recognized as a fork bomb: {command:?}"
);
}
}
/// Ordinary shell that happens to contain braces, pipes or backgrounding must not trip it — a
/// guardrail that cries wolf is one people learn to approve without reading.
#[test]
fn ordinary_commands_do_not_trip_the_fork_bomb_guard() {
for command in [
"echo hi",
"cargo test --workspace",
"find . -name '*.rs' | xargs wc -l",
"sleep 10 &",
"awk '{ print $1 }' file",
"git log --format='%h %s'",
] {
let request = build_request("bash", &json!({ "command": command }), &root());
assert!(
!request.checks.iter().any(|check| check.permission == FORKBOMB),
"false positive on ordinary shell: {command:?}"
);
}
}
/// The guard is bash-only: another tool carrying the same text is not running it as shell.
#[test]
fn the_fork_bomb_guard_is_scoped_to_bash() {
let written = build_request("write", &json!({"path": ":(){ :|:& };:"}), &root());
assert!(!written.checks.iter().any(|check| check.permission == FORKBOMB));
}
#[test]
fn mcp_call_is_keyed_by_its_server_tool_target() {
// A call carries a target + args → gated by `server/name`.
let call = build_request("mcp", &json!({"tool": "github/create_issue", "args": "{}"}), &root());
assert_eq!(call.checks[0].permission, "mcp");
assert_eq!(call.checks[0].input, "github/create_issue");
// Discovery (no args) has no target, so it isn't gated by a specific tool.
let search = build_request("mcp", &json!({"search": "issue"}), &root());
assert_eq!(search.checks[0].input, "");
}
/// The summary is the consent surface: it is the whole of what a person reads before deciding.
/// Nothing asserted on it, so it could have returned an empty string and every test still
/// passed — which is an approval prompt that says nothing.
#[test]
fn the_prompt_says_what_is_about_to_happen() {
// Whole strings, not `contains`. Every arm's fallback also embeds the input, so a
// containment check still passes when a guard is inverted and the prompt silently drops
// to the generic `tool: input` form — the verb is most of what the reader is deciding on.
let cases = [
("bash", json!({"command": "rm -rf build"}), "Run: rm -rf build"),
("read", json!({"path": "src/main.rs"}), "Read src/main.rs"),
("write", json!({"path": "src/new.rs"}), "Modify src/new.rs"),
("edit", json!({"path": "src/old.rs"}), "Modify src/old.rs"),
("git", json!({"action": "push", "args": ["--force"]}), "git push --force"),
("web_fetch", json!({"url": "https://example.com"}), "Fetch https://example.com"),
(
"mcp",
json!({"tool": "github/create_issue", "args": "{}"}),
"MCP call: github/create_issue",
),
("screenshot", json!({"url": "http://localhost:3000"}), "Capture http://localhost:3000"),
];
for (tool, args, expected) in cases {
assert_eq!(build_request(tool, &args, &root()).summary, expected, "{tool}'s prompt");
}
}
/// "git commit" describes every commit ever made, so it is not what the reader is deciding on.
#[test]
fn a_commit_prompt_carries_the_subject_being_committed() {
let request = build_request(
"git",
&json!({"action": "commit", "message": "Recognize Insert chords\n\nlong body…"}),
&root(),
);
assert_eq!(request.summary, "git commit — Recognize Insert chords", "body stays out");
// Bounded: a prompt is one line, whatever the model wrote.
let long =
build_request("git", &json!({"action": "commit", "message": "s".repeat(200)}), &root());
assert!(long.summary.chars().count() < 90, "got {:?}", long.summary);
assert!(long.summary.ends_with('…'));
// Only for a commit, and only when there is a subject to carry.
assert_eq!(build_request("git", &json!({"action": "commit"}), &root()).summary, "git commit");
assert_eq!(
build_request("git", &json!({"action": "log", "message": "x"}), &root()).summary,
"git log"
);
}
/// Approving a delegation without seeing the task is approving nothing in particular — and the
/// "always" rule this card offers is scoped to the tool, so the arguments are the only part of
/// the decision that is about *this* call.
#[test]
fn an_mcp_prompt_carries_the_arguments_it_is_about_to_send() {
let request = build_request(
"mcp",
&json!({
"tool": "delegate/delegate",
"args": "{\n \"task\": \"review src/parser.rs\",\n \"role\": \"reviewer\"\n}"
}),
&root(),
);
assert_eq!(
request.summary,
"MCP call: delegate/delegate {\"task\":\"review src/parser.rs\",\"role\":\"reviewer\"}",
"one line, in the order the model wrote it"
);
// Bounded, like the commit subject: a card is one line whatever the model wrote.
let long = build_request(
"mcp",
&json!({
"tool": "fs/write_file",
"args": format!("{{\"text\":\"{}\"}}", "x".repeat(400)),
}),
&root(),
);
assert!(long.summary.chars().count() < 140, "got {} chars", long.summary.chars().count());
assert!(long.summary.ends_with('\u{2026}'));
// A secret in an argument must not be put on screen — or into the denial message and the
// RPC frame that carry the same summary.
let secret = build_request(
"mcp",
&json!({
"tool": "deploy/run",
"args": "{\"key\": \"sk-abcdefghijklmnopqrstuvwxyz0123\"}"
}),
&root(),
);
assert!(!secret.summary.contains("sk-abcdefghijklmnopqrstuvwxyz0123"), "{}", secret.summary);
assert!(secret.summary.contains("REDACTED"), "{}", secret.summary);
// Arguments the proxy itself would refuse are still what the server would be sent, so they
// are shown rather than dropped.
let unparseable = build_request("mcp", &json!({"tool": "x/y", "args": "not json"}), &root());
assert_eq!(unparseable.summary, "MCP call: x/y not json");
// And a call that takes no arguments says so by having none, not by drawing `{}`.
assert_eq!(
build_request("mcp", &json!({"tool": "github/list", "args": "{}"}), &root()).summary,
"MCP call: github/list"
);
}
/// A tool with no input still has to say which tool is asking, or the prompt is a bare verb.
#[test]
fn a_prompt_with_no_input_still_names_its_tool() {
let summary = build_request("activate_tools", &json!({}), &root()).summary;
assert!(summary.contains("activate_tools"), "got {summary:?}");
}
/// The verb is the difference between reading a file and rewriting it, and it is the only part
/// of the prompt that says which one this is.
#[test]
fn the_prompt_distinguishes_reading_from_modifying() {
let read = build_request("read", &json!({"path": "notes.md"}), &root()).summary;
let write = build_request("write", &json!({"path": "notes.md"}), &root()).summary;
assert_ne!(read, write, "read and write must not read alike");
assert!(read.starts_with("Read"), "got {read:?}");
assert!(write.starts_with("Modify"), "got {write:?}");
}
/// The desktop modes have to be *nameable*, or the only rule that reaches them also gates the
/// browser. Keying on the URL alone gave `mode=fullscreen` an empty target, which the
/// permissive base allows outright — so photographing the screen was ungated and unwritable at
/// the same time. An omitted mode is `fullscreen`, so it must not fall through to empty either.
#[test]
fn photographing_the_screen_is_a_target_a_rule_can_name() {
let target = |args: serde_json::Value| {
build_request("screenshot", &args, &root()).checks[0].input.clone()
};
assert_eq!(target(json!({"mode": "fullscreen"})), "fullscreen");
assert_eq!(target(json!({"mode": "window", "window": "luxe"})), "window");
assert_eq!(target(json!({})), "fullscreen", "an omitted mode is the desktop, not nothing");
assert_eq!(
target(json!({"mode": "fullscreen", "url": "http://localhost:3000"})),
"fullscreen",
"a url beside a desktop mode does not make it a page"
);
assert_eq!(
target(json!({"url": "http://localhost:3000"})),
"http://localhost:3000",
"a url with no mode is a page, as the tool reads it"
);
assert_eq!(
target(json!({"mode": "url", "url": "http://localhost:3000"})),
"http://localhost:3000",
"a rendered page is still gated on the page"
);
}
/// Each tool names the argument a rule is written against. Without its own arm a tool falls to
/// the generic "first string value" case, which sorts the object and picks whichever key comes
/// first alphabetically — that is how `screenshot` rules once matched the literal word "url".
#[test]
fn each_tool_is_gated_on_the_argument_worth_a_rule() {
let cases = [
("bash", json!({"command": "ls", "timeout": 5}), "ls"),
("read", json!({"path": "a.rs", "limit": 10}), "a.rs"),
("read", json!({"file_path": "b.rs"}), "b.rs"),
("glob", json!({"pattern": "**/*.rs"}), "**/*.rs"),
("grep", json!({"pattern": "TODO", "glob": "*.rs"}), "TODO"),
("web_fetch", json!({"url": "https://x.dev", "format": "text"}), "https://x.dev"),
("web_search", json!({"query": "rust", "count": 3}), "rust"),
// `mode` sorts before `url`, so the generic case picks the wrong one.
("screenshot", json!({"mode": "url", "url": "http://localhost"}), "http://localhost"),
];
for (tool, args, expected) in cases {
let request = build_request(tool, &args, &root());
assert_eq!(request.checks[0].input, expected, "{tool} is gated on the wrong argument");
}
}
/// The external-directory guard is for tools that take a path. A `grep` pattern or a search
/// query is not a path, and treating one as a path asks the user to approve a directory that
/// was never touched.
#[test]
fn only_path_tools_get_the_external_directory_guard() {
let path_tool = build_request("read", &json!({"path": "/etc/hosts"}), &root());
assert!(path_tool.checks.iter().any(|check| check.permission == EXTERNAL_DIRECTORY));
for (tool, args) in [
("bash", json!({"command": "/etc/hosts"})),
("grep", json!({"pattern": "/etc/hosts"})),
("web_search", json!({"query": "/etc/hosts"})),
] {
let request = build_request(tool, &args, &root());
assert!(
!request.checks.iter().any(|check| check.permission == EXTERNAL_DIRECTORY),
"{tool} is not a path tool but got the external-directory guard"
);
}
}
#[test]
fn git_input_joins_action_and_args() {
let req =
build_request("git", &json!({"action": "push", "args": ["--force", "origin"]}), &root());
assert_eq!(req.checks[0].input, "push --force origin");
}

View File

@@ -0,0 +1,103 @@
use super::*;
use crate::permission::{
PermissionAction::{Allow, Ask, Deny},
PermissionEngine, PermissionMode,
};
fn replacement(extra: serde_json::Value) -> PermissionRequest {
let mut args =
json!({"action": "replace", "pattern": "foo($A)", "rewrite": "bar($A)", "lang": "rust"});
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
build_request("ast_grep", &args, &root())
}
/// Applied structural replacements must be denied in read-only mode and ask in strict mode.
#[test]
fn an_applied_ast_grep_replacement_is_a_mutating_edit() {
let request = replacement(json!({"apply": true, "paths": ["src"]}));
for (mode, expected) in [(PermissionMode::ReadOnly, Deny), (PermissionMode::Strict, Ask)] {
let engine = PermissionEngine::assemble(mode, vec![], vec![], false);
assert_eq!(engine.decide(&request), expected, "{mode:?}");
}
assert!(request.checks.iter().any(|check| check.permission == "edit" && check.input == "src"));
assert_eq!(request.tool, "ast_grep");
}
/// Previewing a replacement must not acquire a write check or lose the tool's read mode.
#[test]
fn ast_grep_previews_are_not_mutating_edits() {
for extra in [json!({}), json!({"apply": false}), json!({"apply": "true"})] {
let request = replacement(extra);
assert!(!request.checks.iter().any(|check| check.permission == "edit"));
for mode in [PermissionMode::ReadOnly, PermissionMode::Strict] {
let engine = PermissionEngine::assemble(mode, vec![], vec![], false);
assert_eq!(engine.decide(&request), Allow, "{mode:?}");
}
}
}
/// The search action ignores apply, so a stray apply field must not turn search into an edit.
#[test]
fn ast_grep_search_does_not_acquire_edit_checks() {
let request = build_request(
"ast_grep",
&json!({"action": "search", "apply": true, "paths": ["src"]}),
&root(),
);
assert!(!request.checks.iter().any(|check| check.permission == "edit"));
}
/// Every supplied root needs its own edit check; judging only the first loses later denials.
#[test]
fn applied_ast_grep_checks_every_supplied_path() {
let request = replacement(json!({"apply": true, "paths": ["src", "tests"]}));
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("edit", "tests", Deny)],
vec![],
false,
);
assert_eq!(engine.decide(&request), Deny);
let paths: Vec<_> = request
.checks
.iter()
.filter(|check| check.permission == "edit")
.map(|check| check.input.as_str())
.collect();
assert_eq!(paths, ["src", "tests"]);
}
/// The actual tool accepts a single path alias and a default whole-project scope.
#[test]
fn applied_ast_grep_accepts_path_aliases_and_defaults() {
for (extra, target) in [
(json!({"apply": true, "path": "src/a.rs"}), "src/a.rs"),
(json!({"apply": true, "paths": "src/b.rs"}), "src/b.rs"),
(json!({"apply": true}), "."),
(json!({"apply": true, "paths": []}), "."),
] {
let request = replacement(extra);
assert!(
request.checks.iter().any(|check| check.permission == "edit" && check.input == target),
"{target}"
);
}
}
/// Adding edit policy must not discard an existing ast-grep tool-specific refusal.
#[test]
fn ast_grep_specific_denials_still_apply() {
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("ast_grep", "replace", Deny)],
vec![],
false,
);
assert_eq!(engine.decide(&replacement(json!({"apply": true}))), Deny);
}
/// A bulk replacement's eventual files are unknown before scanning, so no action-wide Always rule is honest.
#[test]
fn applied_ast_grep_offers_no_action_wide_remembering_rule() {
assert!(replacement(json!({"apply": true, "paths": ["src", "tests"]})).always.is_empty());
}

View File

@@ -0,0 +1,156 @@
use super::*;
use crate::permission::{PermissionAction, PermissionEngine, PermissionMode};
use PermissionAction::{Allow, Ask, Deny};
const SEPARATORS: [&str; 6] = ["&&", "||", ";", "|", "\n", "&"];
fn bash_decision(engine: &PermissionEngine, command: &str) -> PermissionAction {
engine.decide(&build_request("bash", &json!({"command": command}), &root()))
}
fn allow_git(fallback: PermissionAction) -> PermissionEngine {
PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("bash", "*", fallback), rule("bash", "git *", Allow)],
vec![],
false,
)
}
/// A git allowance must not authorize a different command before or after any shell separator.
#[test]
fn an_allow_rule_does_not_cover_a_chain_it_only_starts() {
let engine = allow_git(Ask);
for separator in SEPARATORS {
for (first, second) in
[("git status", "curl example.invalid"), ("curl example.invalid", "git status")]
{
let command = format!("{first} {separator} {second}");
assert_eq!(bash_decision(&engine, &command), Ask, "{command:?}");
}
}
}
/// A specific allowance for one segment must not hide the catch-all denial of another.
#[test]
fn an_unallowed_segment_is_denied_even_beside_an_allowed_one() {
let engine = allow_git(Deny);
for command in ["git status && curl example.invalid", "curl example.invalid && git status"] {
assert_eq!(bash_decision(&engine, command), Deny, "{command}");
}
}
/// A chain remains allowed when every segment independently has an allowance.
#[test]
fn a_chain_of_individually_allowed_commands_is_allowed() {
let mut engine = allow_git(Ask);
engine.approve([rule("bash", "cargo *", Allow)]);
for separator in SEPARATORS {
for (first, second) in [("git status", "cargo test"), ("cargo test", "git status")] {
let command = format!("{first} {separator} {second}");
assert_eq!(bash_decision(&engine, &command), Allow, "{command:?}");
}
}
}
/// An explicit ask on any segment survives a more specific allowance on a different segment.
#[test]
fn an_explicit_segment_ask_is_not_hidden_by_an_allowance() {
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("bash", "curl *", Ask), rule("bash", "git status *", Allow)],
vec![],
false,
);
for command in ["git status && curl example.invalid", "curl example.invalid && git status"] {
assert_eq!(bash_decision(&engine, command), Ask, "{command}");
}
}
/// Per-segment checking must not make ordinary chains prompt under the permissive defaults.
#[test]
fn permissive_chains_remain_allowed() {
let engine = PermissionEngine::permissive();
for command in ["echo ok && cargo test", "cargo test && echo ok"] {
assert_eq!(bash_decision(&engine, command), Allow, "{command}");
}
}
/// The whole-line input remains first for display and guards, with a check for each chained command.
#[test]
fn bash_requests_keep_the_whole_line_and_check_each_segment() {
let command = "git status && cargo test";
let request = build_request("bash", &json!({"command": command}), &root());
let inputs: Vec<_> = request.checks.iter().map(|check| check.input.as_str()).collect();
assert_eq!(inputs, [command, "git status", "cargo test"]);
assert!(request.checks.iter().all(|check| check.permission == "bash"));
}
/// A single command needs only its original check, not a duplicate tokenized check.
#[test]
fn a_single_segment_keeps_one_check() {
let request = build_request("bash", &json!({"command": "git status"}), &root());
assert_eq!(request.checks.len(), 1);
assert_eq!(request.checks[0].input, "git status");
}
/// A chained command must not offer a remembering rule for just its first command family.
#[test]
fn always_for_a_chain_offers_no_rule() {
for separator in SEPARATORS {
for (first, second) in [("cd app", "cargo test"), ("cargo test", "cd app")] {
let command = format!("{first} {separator} {second}");
let request = build_request("bash", &json!({"command": command}), &root());
assert!(request.always.is_empty(), "a chain offered an Always rule: {command:?}");
}
}
}
/// Single commands, redirects and a trailing background marker still offer their command family.
#[test]
fn a_single_segment_still_offers_a_command_family_rule() {
for command in [
"cargo test",
" cargo test ",
"cargo test &",
"cargo test 2>&1",
"cargo test &>log",
"cargo test <&3",
] {
let request = build_request("bash", &json!({"command": command}), &root());
assert_eq!(request.always.len(), 1, "{command}");
assert_eq!(request.always[0].permission, "bash", "{command}");
assert_eq!(request.always[0].pattern, "cargo *", "{command}");
assert_eq!(request.always[0].action, Allow, "{command}");
}
}
/// Empty input and separator-only input have no command family worth approving.
#[test]
fn a_command_with_no_segments_offers_no_rule() {
for command in ["", " ", ";", "&&", "|", "&"] {
let request = build_request("bash", &json!({"command": command}), &root());
assert!(request.always.is_empty(), "an empty command offered a rule: {command:?}");
}
}
/// Remembering cd must allow cd alone without letting a later curl ride along in strict mode.
#[test]
fn strict_plus_always_cd_does_not_allow_a_later_curl() {
let mut engine = PermissionEngine::assemble(PermissionMode::Strict, vec![], vec![], false);
let request = build_request("bash", &json!({"command": "cd app"}), &root());
engine.approve(request.always);
assert_eq!(bash_decision(&engine, "cd app"), Allow);
for command in ["cd app && curl example.invalid", "curl example.invalid && cd app"] {
assert_eq!(bash_decision(&engine, command), Ask, "{command}");
}
}
/// Shell separators in another tool's input must not manufacture bash permission checks.
#[test]
fn non_bash_inputs_are_not_split_into_commands() {
let request = build_request("web_search", &json!({"query": "git && curl"}), &root());
assert_eq!(request.checks.len(), 1);
assert_eq!(request.checks[0].permission, "web_search");
assert_eq!(request.checks[0].input, "git && curl");
}

View File

@@ -0,0 +1,115 @@
use super::*;
use crate::permission::{
PermissionAction::{Allow, Ask, Deny},
PermissionEngine, PermissionMode,
};
fn launch(program: &str, arguments: &[&str]) -> PermissionRequest {
build_request(
"debug",
&json!({"action": "launch", "program": program, "args": arguments}),
&root(),
)
}
/// A debugger must not bypass a Bash rule refusing a shell program.
#[test]
fn a_debug_shell_launch_obeys_the_bash_denial() {
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("bash", "/bin/sh *", Deny)],
vec![],
false,
);
let request = launch("/bin/sh", &["-c", "echo ok"]);
assert_eq!(engine.decide(&request), Deny);
assert_eq!(request.tool, "debug");
assert!(request
.checks
.iter()
.any(|check| check.permission == "bash" && check.input == "/bin/sh -c echo ok"));
}
/// Launch arguments must participate in Bash pattern matching, not just the program name.
#[test]
fn debug_launch_arguments_are_checked_by_bash_rules() {
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("bash", "app --dangerous *", Deny)],
vec![],
false,
);
assert_eq!(engine.decide(&launch("app", &["--dangerous", "value"])), Deny);
assert_eq!(engine.decide(&launch("app", &["--safe"])), Allow);
}
/// A launch must not discard the existing debug-key policy when adding execution checks.
#[test]
fn debug_specific_launch_denials_still_apply() {
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("debug", "launch", Deny)],
vec![],
false,
);
assert_eq!(engine.decide(&launch("app", &[])), Deny);
}
/// Inspecting or attaching to a session must not manufacture Bash execution checks.
#[test]
fn debug_non_launch_actions_keep_their_existing_checks() {
for action in ["attach", "stack_trace", "variables", "output", "sessions"] {
let request =
build_request("debug", &json!({"action": action, "program": "/bin/sh"}), &root());
assert!(!request.checks.iter().any(|check| check.permission == "bash"), "{action}");
assert_eq!(PermissionEngine::permissive().decide(&request), Allow, "{action}");
}
}
/// A missing program cannot be launched and should retain the tool's normal validation path.
#[test]
fn a_launch_without_a_program_does_not_add_bash_checks() {
let request = build_request("debug", &json!({"action": "launch"}), &root());
assert!(!request.checks.iter().any(|check| check.permission == "bash"));
}
/// A remembered launch relaxes exactly that launch, never the program's whole Bash family.
#[test]
fn a_debug_launch_is_remembered_exactly() {
let mut engine = PermissionEngine::assemble(PermissionMode::Strict, vec![], vec![], false);
let request = launch("app", &["--safe"]);
assert_eq!(engine.decide(&request), Ask);
assert!(request
.always
.iter()
.any(|rule| rule.permission == "bash" && rule.pattern == "app --safe"));
engine.approve(request.always.clone());
assert_eq!(engine.decide(&request), Allow);
assert_eq!(engine.decide(&launch("app", &["--other"])), Ask);
assert_eq!(engine.decide(&launch("other-app", &[])), Ask);
}
/// The default recursive-delete guard applies to a launched program with no user rules at all.
#[test]
fn a_debug_launch_hits_the_default_rm_guard() {
assert_eq!(PermissionEngine::permissive().decide(&launch("rm", &["-rf", "/"])), Deny);
}
/// A shell launched with `-c` runs its script, so the script is judged as a command of its own.
#[test]
fn a_debug_shell_script_is_judged_as_a_command() {
for (program, arguments) in [
("/bin/sh", &["-c", "rm -rf ~"][..]),
("bash", &["-lc", "rm -rf /"][..]),
("/usr/bin/zsh", &["-c", ":(){ :|:& };:"][..]),
("/usr/bin/env", &["sh", "-c", "rm -rf /"][..]),
("env", &["FOO=1", "-i", "bash", "-c", "rm -rf ~"][..]),
("busybox", &["sh", "-c", "rm -rf /"][..]),
("C:\\Windows\\bash.exe", &["-c", "rm -rf /"][..]),
] {
let request = launch(program, arguments);
assert_eq!(PermissionEngine::permissive().decide(&request), Deny, "{program}");
assert!(request.always.is_empty(), "{program}");
}
assert_eq!(PermissionEngine::permissive().decide(&launch("/bin/sh", &["-c", "ls"])), Allow);
}

View File

@@ -0,0 +1,100 @@
use super::*;
use crate::permission::{
PermissionAction::{Allow, Ask, Deny},
PermissionEngine, PermissionMode,
};
fn navigation(action: &str, extra: serde_json::Value) -> PermissionRequest {
let mut args = json!({"action": action, "path": "src/a.rs"});
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
build_request("lsp_navigation", &args, &root())
}
/// Applying either LSP write action must deny in read-only and ask in strict mode.
#[test]
fn applied_lsp_write_actions_follow_the_edit_modes() {
for action in ["rename", "code_action"] {
let request = navigation(action, json!({"apply": true}));
for (mode, expected) in [(PermissionMode::ReadOnly, Deny), (PermissionMode::Strict, Ask)] {
let engine = PermissionEngine::assemble(mode, vec![], vec![], false);
assert_eq!(engine.decide(&request), expected, "{mode:?}: {action}");
}
assert!(request
.checks
.iter()
.any(|check| check.permission == "edit" && check.input == "src/a.rs"));
assert_eq!(request.tool, "lsp_navigation");
}
}
/// Previewing a rename or code action must not remove the tool's nonmutating modes.
#[test]
fn lsp_write_previews_are_not_edit_checks() {
for action in ["rename", "code_action"] {
for extra in [json!({}), json!({"apply": false}), json!({"apply": "true"})] {
let request = navigation(action, extra);
assert!(!request.checks.iter().any(|check| check.permission == "edit"));
let engine =
PermissionEngine::assemble(PermissionMode::ReadOnly, vec![], vec![], false);
assert_eq!(engine.decide(&request), Allow, "{action}");
}
}
}
/// Read-only actions ignore apply; a stray flag must not become a blanket LSP deny.
#[test]
fn lsp_read_actions_do_not_acquire_edit_checks() {
for action in
["go_to_definition", "hover", "find_references", "document_symbols", "workspace_symbol"]
{
let request = navigation(action, json!({"apply": true}));
assert!(!request.checks.iter().any(|check| check.permission == "edit"), "{action}");
}
}
/// The edit target must honor the same ordered file aliases the LSP tool accepts.
#[test]
fn lsp_apply_uses_the_actual_file_aliases() {
for key in ["path", "file", "file_path", "filePath"] {
let args = json!({"action": "rename", "apply": true, key: "src/b.rs"});
let request = build_request("lsp_navigation", &args, &root());
assert!(
request
.checks
.iter()
.any(|check| check.permission == "edit" && check.input == "src/b.rs"),
"{key}"
);
}
}
/// User edit rules must target the path, while original LSP-specific denials still hold.
#[test]
fn applied_lsp_changes_keep_both_tool_and_path_policy() {
let request = navigation("rename", json!({"apply": true}));
for denial in [rule("edit", "src/a.rs", Deny), rule("lsp_navigation", "rename", Deny)] {
let engine =
PermissionEngine::assemble(PermissionMode::Default, vec![denial], vec![], false);
assert_eq!(engine.decide(&request), Deny);
}
}
/// The server's eventual target files are unknown before the call, so no action-wide Always rule is offered.
#[test]
fn applied_lsp_changes_offer_no_action_wide_remembering_rule() {
for action in ["rename", "code_action"] {
assert!(navigation(action, json!({"apply": true})).always.is_empty());
}
}
/// Missing or empty file input cannot execute an LSP action and retains normal tool validation.
#[test]
fn lsp_apply_without_a_usable_file_does_not_add_an_edit_check() {
for args in [
json!({"action": "rename", "apply": true}),
json!({"action": "rename", "apply": true, "path": "", "file": "src/a.rs"}),
] {
let request = build_request("lsp_navigation", &args, &root());
assert!(!request.checks.iter().any(|check| check.permission == "edit"));
}
}

View File

@@ -0,0 +1,489 @@
use super::*;
use crate::permission::{
PermissionAction::{Allow, Ask, Deny},
PermissionEngine, PermissionMode,
};
fn grep_request(extra: serde_json::Value) -> PermissionRequest {
let mut args = json!({"pattern": "needle"});
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
build_request("grep", &args, &root())
}
/// A grep scope outside the project must ask just like a read of that scope.
#[test]
fn grep_outside_the_project_asks() {
let request = grep_request(json!({"path": "/etc"}));
assert_eq!(PermissionEngine::permissive().decide(&request), Ask);
assert!(request
.checks
.iter()
.any(|check| check.permission == EXTERNAL_DIRECTORY && check.input == "/etc"));
assert_eq!(request.checks[0].permission, "grep");
assert_eq!(request.checks[0].input, "needle");
}
/// Enabling ignored files must not make a named env file readable through grep.
#[test]
fn grep_of_a_named_env_file_is_denied_even_with_all() {
for path in [".env", "config/.env.local", "../outside/.env"] {
let request = grep_request(json!({"path": path, "all": true}));
assert_eq!(PermissionEngine::permissive().decide(&request), Deny, "{path}");
}
assert_eq!(
PermissionEngine::permissive()
.decide(&grep_request(json!({"path": ".env.example", "all": true}))),
Allow
);
}
/// An internal scope remains allowed, and missing or blank path follows grep's cwd default.
#[test]
fn grep_internal_and_default_roots_remain_allowed() {
for (extra, expected) in [
(json!({"path": "src"}), "src"),
(json!({}), "."),
(json!({"path": " "}), "."),
(json!({"path": " src "}), "src"),
] {
let request = grep_request(extra);
assert_eq!(PermissionEngine::permissive().decide(&request), Allow);
assert!(
request
.checks
.iter()
.any(|check| check.permission == "read" && check.input == expected),
"{expected}"
);
}
}
/// A pattern that resembles a path is not a scope and must not prompt for that directory.
#[test]
fn grep_patterns_are_not_treated_as_search_roots() {
let request = build_request("grep", &json!({"pattern": "/etc/hosts", "path": "src"}), &root());
assert!(!request.checks.iter().any(|check| check.permission == EXTERNAL_DIRECTORY));
assert_eq!(PermissionEngine::permissive().decide(&request), Allow);
}
/// Adding read checks must retain existing grep-pattern denials and honor new read-path rules.
#[test]
fn grep_keeps_both_its_own_rules_and_read_scope_policy() {
let request = grep_request(json!({"path": "private"}));
for denial in [rule("grep", "needle", Deny), rule("read", "private", Deny)] {
let engine =
PermissionEngine::assemble(PermissionMode::Default, vec![denial], vec![], false);
assert_eq!(engine.decide(&request), Deny);
}
}
/// File discovery outside the project must ask even though its primary input is only a glob.
#[test]
fn glob_outside_the_project_asks_without_changing_its_pattern_check() {
let request = build_request("glob", &json!({"pattern": "*.rs", "path": "/etc"}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), Ask);
assert_eq!(request.checks[0].permission, "glob");
assert_eq!(request.checks[0].input, "*.rs");
assert!(request.checks.iter().any(|check| check.permission == EXTERNAL_DIRECTORY));
assert!(request.always.iter().all(|rule| rule.permission == EXTERNAL_DIRECTORY));
}
/// A glob selector that resembles an absolute path must not become a search root.
#[test]
fn glob_selectors_are_not_mistaken_for_roots() {
let request = build_request("glob", &json!({"pattern": "/etc/*.rs", "path": "src"}), &root());
assert!(!request.checks.iter().any(|check| check.permission == EXTERNAL_DIRECTORY));
assert_eq!(PermissionEngine::permissive().decide(&request), Allow);
}
/// Missing, empty and whitespace glob scopes must match the real tool's cwd fallback.
#[test]
fn glob_default_and_trimmed_roots_are_read_checks() {
for (path, expected) in
[(None, "."), (Some(""), "."), (Some(" "), "."), (Some(" src "), "src")]
{
let mut args = json!({"pattern": "*.rs"});
if let Some(path) = path {
args["path"] = json!(path);
}
let request = build_request("glob", &args, &root());
assert!(
request
.checks
.iter()
.any(|check| check.permission == "read" && check.input == expected),
"{expected}"
);
assert_eq!(PermissionEngine::permissive().decide(&request), Allow);
}
}
/// Scope-read denials must not replace the original glob-specific pattern policy.
#[test]
fn glob_keeps_both_pattern_and_scope_rules() {
let request = build_request("glob", &json!({"pattern": "*.rs", "path": "private"}), &root());
for denial in [rule("glob", "*.rs", Deny), rule("read", "private", Deny)] {
let engine =
PermissionEngine::assemble(PermissionMode::Default, vec![denial], vec![], false);
assert_eq!(engine.decide(&request), Deny);
}
}
/// An explicitly named secret scope stays denied even when ignored-file discovery is enabled.
#[test]
fn glob_of_a_named_env_scope_obeys_read_policy() {
for (path, expected) in [(".env", Deny), ("config/.env.local", Deny), (".env.example", Allow)] {
let request =
build_request("glob", &json!({"pattern": "*", "path": path, "all": true}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), expected, "{path}");
}
}
/// Structural search and replace preview must not bypass an external-directory prompt.
#[test]
fn ast_grep_search_and_preview_outside_the_project_ask() {
for action in ["search", "replace"] {
let request = build_request(
"ast_grep",
&json!({"action": action, "paths": ["/etc"], "apply": false}),
&root(),
);
assert_eq!(PermissionEngine::permissive().decide(&request), Ask, "{action}");
assert!(!request.always.iter().any(|rule| rule.permission == "ast_grep"));
}
}
/// Every structural scope must be checked, including an outside path after an internal one.
#[test]
fn ast_grep_roots_include_all_supplied_paths() {
let request =
build_request("ast_grep", &json!({"action": "search", "paths": ["src", "/etc"]}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), Ask);
let roots: Vec<_> = request
.checks
.iter()
.filter(|check| check.permission == "read")
.map(|check| check.input.as_str())
.collect();
assert_eq!(roots, ["src", "/etc"]);
}
/// The structural tool's actual aliases and empty-array default must not be dropped by extraction.
#[test]
fn ast_grep_search_roots_honor_aliases_and_defaults() {
for (extra, expected) in [
(json!({"path": "src/a.rs"}), "src/a.rs"),
(json!({"paths": "src/b.rs"}), "src/b.rs"),
(json!({}), "."),
(json!({"paths": []}), "."),
] {
let mut args = json!({"action": "search"});
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
let request = build_request("ast_grep", &args, &root());
assert!(
request
.checks
.iter()
.any(|check| check.permission == "read" && check.input == expected),
"{expected}"
);
}
}
/// A secret file cannot be opened for structural search just because no edits are applied.
#[test]
fn ast_grep_named_env_searches_follow_read_policy() {
for (path, expected) in [(".env", Deny), ("config/.env.local", Deny), (".env.example", Allow)] {
let request =
build_request("ast_grep", &json!({"action": "search", "path": path}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), expected, "{path}");
}
}
/// Internal structural reads remain available in strict/read-only modes without an apply flag.
#[test]
fn ast_grep_internal_searches_stay_nonmutating() {
let request =
build_request("ast_grep", &json!({"action": "search", "paths": ["src"]}), &root());
for mode in [PermissionMode::Strict, PermissionMode::ReadOnly] {
let engine = PermissionEngine::assemble(mode, vec![], vec![], false);
assert_eq!(engine.decide(&request), Allow, "{mode:?}");
}
assert!(!request.checks.iter().any(|check| check.permission == "edit"));
}
/// File outlines and symbol bodies must not bypass external-directory prompts.
#[test]
fn discovery_file_scopes_outside_the_project_ask() {
for tool in ["module_report", "read_symbol"] {
let request =
build_request(tool, &json!({"path": "/etc/hosts", "symbol": "main"}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), Ask, "{tool}");
assert_eq!(request.checks[0].permission, tool);
assert!(request
.checks
.iter()
.any(|check| check.permission == "read" && check.input == "/etc/hosts"));
assert!(request.always.iter().all(|rule| rule.permission == EXTERNAL_DIRECTORY));
}
}
/// Discovery tools read file content even when they return only an outline, so env files stay guarded.
#[test]
fn discovery_named_env_files_follow_read_policy() {
for tool in ["module_report", "read_symbol"] {
for (path, expected) in
[(".env", Deny), ("config/.env.local", Deny), (".env.example", Allow)]
{
let request = build_request(tool, &json!({"path": path, "symbol": "name"}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), expected, "{tool}: {path}");
}
}
}
/// The four LSP file aliases must be honored by file discovery in the same order as execution.
#[test]
fn discovery_scope_uses_the_actual_file_aliases() {
for tool in ["module_report", "read_symbol"] {
for key in ["path", "file", "file_path", "filePath"] {
let request = build_request(tool, &json!({key: "src/a.rs", "symbol": "main"}), &root());
assert!(
request
.checks
.iter()
.any(|check| check.permission == "read" && check.input == "src/a.rs"),
"{tool}: {key}"
);
}
}
}
/// A missing or empty first file alias must not manufacture a whole-project scan scope.
#[test]
fn discovery_without_a_usable_file_keeps_tool_validation() {
for tool in ["module_report", "read_symbol"] {
for args in
[json!({"symbol": "main"}), json!({"path": "", "file": "/etc/hosts", "symbol": "main"})]
{
let request = build_request(tool, &args, &root());
assert!(
!request
.checks
.iter()
.any(|check| check.permission == "read"
|| check.permission == EXTERNAL_DIRECTORY),
"{tool}"
);
}
}
}
/// Internal discovery remains available in nonmutating modes while honoring both tool and read rules.
#[test]
fn discovery_keeps_nonmutating_modes_and_both_policy_keys() {
for tool in ["module_report", "read_symbol"] {
let request = build_request(tool, &json!({"path": "src/a.rs", "symbol": "main"}), &root());
for mode in [PermissionMode::Strict, PermissionMode::ReadOnly] {
let engine = PermissionEngine::assemble(mode, vec![], vec![], false);
assert_eq!(engine.decide(&request), Allow, "{tool}: {mode:?}");
}
for denial in [rule(tool, "*", Deny), rule("read", "src/a.rs", Deny)] {
let engine =
PermissionEngine::assemble(PermissionMode::Default, vec![denial], vec![], false);
assert_eq!(engine.decide(&request), Deny, "{tool}");
}
}
}
/// Navigation and diagnostics open their source file, so an external file must prompt.
#[test]
fn lsp_file_reads_outside_the_project_ask() {
for tool in ["lsp_navigation", "lsp_diagnostics"] {
let request =
build_request(tool, &json!({"path": "/etc/hosts", "action": "hover"}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), Ask, "{tool}");
assert!(request
.checks
.iter()
.any(|check| check.permission == "read" && check.input == "/etc/hosts"));
assert!(request.always.iter().all(|rule| rule.permission == EXTERNAL_DIRECTORY));
}
}
/// Every diagnostics batch entry must be checked, not just a separately supplied single file.
#[test]
fn lsp_diagnostics_uses_all_batch_paths_with_batch_precedence() {
let request = build_request(
"lsp_diagnostics",
&json!({"path": "safe.rs", "paths": ["src/a.rs", "/etc/hosts"]}),
&root(),
);
assert_eq!(PermissionEngine::permissive().decide(&request), Ask);
let paths: Vec<_> = request
.checks
.iter()
.filter(|check| check.permission == "read")
.map(|check| check.input.as_str())
.collect();
assert_eq!(paths, ["src/a.rs", "/etc/hosts"]);
let secret = build_request("lsp_diagnostics", &json!({"paths": ["src/a.rs", ".env"]}), &root());
assert_eq!(PermissionEngine::permissive().decide(&secret), Deny);
}
/// LSP file aliases must not allow a named env file to bypass read policy.
#[test]
fn lsp_read_file_aliases_keep_env_protection() {
for tool in ["lsp_navigation", "lsp_diagnostics"] {
for key in ["path", "file", "file_path", "filePath"] {
let request = build_request(tool, &json!({key: ".env", "action": "hover"}), &root());
assert_eq!(PermissionEngine::permissive().decide(&request), Deny, "{tool}: {key}");
}
}
}
/// Empty diagnostics batches and missing files must not invent a directory scan or fall back to path.
#[test]
fn lsp_missing_file_and_empty_batches_keep_validation_behavior() {
for (tool, args) in [
("lsp_navigation", json!({"action": "hover"})),
("lsp_diagnostics", json!({})),
("lsp_diagnostics", json!({"paths": [], "path": "/etc/hosts"})),
("lsp_navigation", json!({"path": "", "file": "/etc/hosts", "action": "hover"})),
] {
let request = build_request(tool, &args, &root());
assert!(
!request
.checks
.iter()
.any(|check| check.permission == "read" || check.permission == EXTERNAL_DIRECTORY),
"{tool}"
);
}
}
/// Adding read scopes must leave internal navigation and diagnostics available in nonmutating modes.
#[test]
fn lsp_internal_read_actions_stay_nonmutating() {
for tool in ["lsp_navigation", "lsp_diagnostics"] {
let request = build_request(tool, &json!({"path": "src/a.rs", "action": "hover"}), &root());
for mode in [PermissionMode::Strict, PermissionMode::ReadOnly] {
let engine = PermissionEngine::assemble(mode, vec![], vec![], false);
assert_eq!(engine.decide(&request), Allow, "{tool}: {mode:?}");
}
assert!(!request.checks.iter().any(|check| check.permission == "edit"));
}
}
/// LSP-specific rules and explicit read-path refusals must both survive scope extraction.
#[test]
fn lsp_reads_keep_their_tool_policy_and_read_path_policy() {
for tool in ["lsp_navigation", "lsp_diagnostics"] {
let request = build_request(tool, &json!({"path": "src/a.rs", "action": "hover"}), &root());
for denial in [rule(tool, "*", Deny), rule("read", "src/a.rs", Deny)] {
let engine =
PermissionEngine::assemble(PermissionMode::Default, vec![denial], vec![], false);
assert_eq!(engine.decide(&request), Deny, "{tool}");
}
}
}
/// An exact secret filename selector must not hide behind a safe directory read scope.
#[test]
fn grep_exact_env_filters_are_denied_for_directory_scopes() {
for path in [".", "src"] {
for selector in [".env", ".env.local"] {
let request = grep_request(json!({"path": path, "glob": selector, "all": true}));
assert_eq!(PermissionEngine::permissive().decide(&request), Deny, "{path}: {selector}");
}
}
}
/// The template exception must remain allowed when selected from a directory.
#[test]
fn grep_exact_template_filters_keep_the_read_exception() {
let request = grep_request(json!({"path": "src", "glob": ".env.example", "all": true}));
assert!(request
.checks
.iter()
.any(|check| check.permission == "read" && check.input == "src/.env.example"));
assert_eq!(PermissionEngine::permissive().decide(&request), Allow);
}
/// A literal filename filter must participate in scoped read-path rules, not just env defaults.
#[test]
fn grep_exact_file_filters_obey_read_path_rules() {
let request = grep_request(json!({"path": "src", "glob": "README.md"}));
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("read", "src/README.md", Deny)],
vec![],
false,
);
assert_eq!(engine.decide(&request), Deny);
}
/// A filter matching an explicitly named file must not invent a child path inside that file.
#[test]
fn grep_exact_filters_do_not_append_to_a_matching_file_scope() {
let request = grep_request(json!({"path": "src/README.md", "glob": "README.md"}));
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("read", "*", Deny), rule("read", "src/README.md", Allow)],
vec![],
false,
);
assert_eq!(engine.decide(&request), Allow);
}
/// Wildcard and exclusion filters are not a single known file and must not be treated as one.
#[test]
fn grep_nonliteral_filters_do_not_invent_a_literal_target() {
for selector in ["*.rs", "!README.md"] {
let request = grep_request(json!({"path": "src", "glob": selector}));
let paths: Vec<_> = request
.checks
.iter()
.filter(|check| check.permission == "read")
.map(|check| check.input.as_str())
.collect();
assert_eq!(paths, ["src"], "{selector}");
}
}
/// Unrelated tools must not acquire filesystem checks merely because they carry a path field.
#[test]
fn unrelated_tools_do_not_gain_grep_root_checks() {
let request = build_request("web_search", &json!({"query": "rust", "path": "/etc"}), &root());
assert!(!request
.checks
.iter()
.any(|check| check.permission == EXTERNAL_DIRECTORY || check.permission == "read"));
}
/// A pattern-wide approval cannot cover all files in a search scope, so it must not be offered.
#[test]
fn grep_search_scopes_offer_no_pattern_wide_always_rule() {
for request in [grep_request(json!({"path": "/etc"})), grep_request(json!({"path": "src"}))] {
assert!(request.always.iter().all(|rule| rule.permission == EXTERNAL_DIRECTORY));
}
assert!(grep_request(json!({"path": "src"})).always.is_empty());
}
/// One search outside the project can be remembered as that directory, like a read of it.
#[test]
fn a_single_external_search_root_can_be_remembered() {
for tool in ["grep", "glob", "ast_grep", "read_symbol", "lsp_navigation"] {
let args = json!({"pattern": "x", "path": "/srv/other", "action": "hover"});
let request = build_request(tool, &args, &root());
let mut engine = PermissionEngine::permissive();
assert_eq!(engine.decide(&request), Ask, "{tool}");
engine.approve(request.always.clone());
assert_eq!(engine.decide(&request), Allow, "{tool}");
let deeper = json!({"pattern": "x", "path": "/srv/other/sub", "action": "hover"});
assert_eq!(engine.decide(&build_request(tool, &deeper, &root())), Allow, "{tool}");
let sibling = json!({"pattern": "x", "path": "/srv/elsewhere", "action": "hover"});
assert_eq!(engine.decide(&build_request(tool, &sibling, &root())), Ask, "{tool}");
}
let two = json!({"pattern": "x", "paths": ["/srv/a", "/srv/b"]});
assert!(build_request("ast_grep", &two, &root()).always.is_empty());
}

View File

@@ -0,0 +1,123 @@
use super::*;
use crate::permission::{
PermissionAction::{Allow, Ask, Deny},
PermissionEngine, PermissionMode,
};
fn explicit_request(command: &str) -> PermissionRequest {
build_request("test", &json!({"command": command}), &root())
}
/// The test tool must not bypass recursive-delete guards by using a different tool name.
#[test]
fn an_explicit_test_command_cannot_wipe_the_root() {
let request = explicit_request("rm -rf /");
assert_eq!(PermissionEngine::permissive().decide(&request), Deny);
assert!(request.checks.iter().any(|check| check.permission == "bash"));
assert!(request.checks.iter().any(|check| check.permission == "catastrophic_rm"));
assert_eq!(request.tool, "test");
}
/// Fork-bomb detection must apply before a test override reaches its shell.
#[test]
fn an_explicit_test_command_cannot_run_a_fork_bomb() {
let request = explicit_request(":(){ :|:& };:");
assert_eq!(PermissionEngine::permissive().decide(&request), Deny);
}
/// Dangerous Bash operations keep their prompt when routed through the test tool.
#[test]
fn an_explicit_test_force_push_still_asks() {
let request = explicit_request("git push --force origin main");
assert_eq!(PermissionEngine::permissive().decide(&request), Ask);
}
/// A git allowance must not authorize another segment in a test override.
#[test]
fn explicit_test_chains_need_each_segment_allowed() {
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("bash", "*", Ask), rule("bash", "git *", Allow)],
vec![],
false,
);
for command in ["git status && curl example.invalid", "curl example.invalid && git status"] {
assert_eq!(engine.decide(&explicit_request(command)), Ask, "{command}");
}
assert!(explicit_request("git status && cargo test").always.is_empty());
}
/// Explicit shell overrides must remain mutating in strict and read-only modes.
#[test]
fn explicit_test_commands_follow_the_mutating_modes() {
let request = explicit_request("cargo test");
for (mode, expected) in [(PermissionMode::Strict, Ask), (PermissionMode::ReadOnly, Deny)] {
let engine = PermissionEngine::assemble(mode, vec![], vec![], false);
assert_eq!(engine.decide(&request), expected, "{mode:?}");
}
}
/// Adding Bash checks must not discard a user's existing test-tool denial.
#[test]
fn test_specific_denials_still_apply_to_explicit_commands() {
let engine = PermissionEngine::assemble(
PermissionMode::Default,
vec![rule("test", "*", Deny)],
vec![],
false,
);
assert_eq!(engine.decide(&explicit_request("cargo test")), Deny);
}
/// Without a command override, filters are not shell commands and must not add Bash checks.
#[test]
fn autodetected_tests_keep_their_existing_permission_request() {
let request = build_request("test", &json!({"filter": "unit"}), &root());
assert_eq!(request.permission, "test");
assert!(!request.checks.iter().any(|check| check.permission == "bash"));
assert_eq!(PermissionEngine::permissive().decide(&request), Allow);
}
/// A remembered test command relaxes exactly that command, never its whole Bash family.
#[test]
fn a_single_test_command_is_remembered_exactly() {
let mut engine = PermissionEngine::assemble(
PermissionMode::Strict,
vec![rule("test", "*", Ask)],
vec![],
false,
);
let request = explicit_request("cargo test");
assert_eq!(engine.decide(&request), Ask);
assert!(request
.always
.iter()
.any(|rule| rule.permission == "bash" && rule.pattern == "cargo test"));
assert!(!request.always.iter().any(|rule| rule.pattern.contains('*')), "{:?}", request.always);
engine.approve(request.always.clone());
assert_eq!(engine.decide(&request), Allow);
assert_eq!(engine.decide(&explicit_request("cargo publish")), Ask);
let bash = build_request("bash", &json!({"command": "cargo publish"}), &root());
assert_eq!(engine.decide(&bash), Ask);
assert_eq!(engine.decide(&explicit_request("cargo test && curl example.invalid")), Ask);
}
/// A filter is appended to the test command unquoted, so a second command hidden in it is judged.
#[test]
fn a_test_filter_cannot_smuggle_a_second_command() {
for args in [
json!({"command": "pytest", "filter": "unit; rm -rf /"}),
json!({"filter": "unit; rm -rf /"}),
json!({"filter": "unit && rm -rf ~"}),
json!({"filter": "; rm -rf /"}),
json!({"filter": "&& rm -rf ~"}),
json!({"filter": "\nrm -rf /"}),
] {
let request = build_request("test", &args, &root());
assert_eq!(PermissionEngine::permissive().decide(&request), Deny, "{args}");
assert!(request.always.is_empty(), "{args}");
}
let plain = build_request("test", &json!({"command": "pytest", "filter": "unit"}), &root());
assert_eq!(PermissionEngine::permissive().decide(&plain), Allow);
assert!(plain.checks.iter().any(|check| check.input == "pytest unit"));
}