diff --git a/README.md b/README.md index b186c30..1fe02a8 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ gate = "sh tests/all.sh" # exit 0 = pass max_retries = 2 workers = 2 account = "work-claude" # profiles on one login share quota pause and max_concurrent -allow = ["read", "write", "edit", "bash:cargo *"] +allow = ["read", "write", "edit", "readonly", "bash:cargo *"] [budget] wall_secs = 1800 # per attempt max_turns = 40 # whole run diff --git a/docs/safety.md b/docs/safety.md index 0f674c1..8b8daa7 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -18,6 +18,12 @@ sandbox = true # hx --sandbox (bwrap); required for yolo = tru - Absent: no policy, hx may use every tool (orch prints a warning unless `sandbox = true`). - `TOOL` allows every call of that tool (`read`, `write`, `edit`, `bash`, `lsp`, ...), `*` allows all. +- `readonly`: bash commands that only look, one simple command each: `ls cat head tail wc grep rg fd find pwd echo + stat file du df which tree diff sort cut nl tr jq basename dirname` and `git status|diff|log|show|blame|ls-files|rev-parse`. + Flags that run or write are refused per command (`find -exec/-delete/-fprint*`, `fd -x/--exec`, `rg --pre`, + `sort -o/--output`, `tree -o`, `git --output/--ext-diff/--textconv`), and so are `git -C`, other git subcommands and + anything outside the worktree. Typical profile: `allow = ["read", "write", "edit", "readonly", "Grep", "Glob", "LS", + "bash:cargo *"]`. In `claude_cli` mode Claude's other tools arrive under Claude's own names and need their own entry. - `bash:PATTERN`: `*` glob over the whole command. Only simple commands match (no `; & | < > $ ( ) { } \` or newline); path-like words must resolve inside the worktree or `read_roots`. - Always denied, even with `*`: `git push` (publishing is the sink's job), credential-looking paths (`.env*`, diff --git a/src/policy.rs b/src/policy.rs index f554c0a..fda8fb0 100644 --- a/src/policy.rs +++ b/src/policy.rs @@ -126,6 +126,80 @@ fn resolve(base: &Path, p: &str) -> PathBuf { } } +/// Allowlist entry `readonly`: bash commands that only look. Spelled out in code instead of glob patterns because +/// the dangerous part is the flags (`find -exec`, `rg --pre`, `sort -o`, `fd -x`), which a pattern cannot see. +pub const READONLY: &str = "readonly"; +const READONLY_CMDS: &[&str] = &[ + "ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "find", "pwd", "echo", "stat", "file", + "du", "df", "which", "tree", "diff", "sort", "cut", "nl", "tr", "jq", "basename", "dirname", +]; +const READONLY_GIT: &[&str] = &[ + "status", + "diff", + "log", + "show", + "blame", + "ls-files", + "rev-parse", +]; +/// Flags that run a program or write a file, per command (`*` = any command). +const RUN_OR_WRITE_FLAGS: &[(&str, &[&str])] = &[ + ( + "find", + &[ + "-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", + "-fls", + ], + ), + ("fd", &["-x", "-X", "--exec", "--exec-batch"]), + ("rg", &["--pre", "--pre-glob"]), + ("sort", &["-o", "--output", "--compress-program"]), + ("tree", &["-o"]), + ( + "git", + &[ + "--output", + "--ext-diff", + "--textconv", + "-O", + "--open-files-in-pager", + ], + ), +]; + +/// Ok when `cmd` is one simple command from the read-only set without a flag that runs or writes anything. +pub fn readonly_cmd(cmd: &str) -> Result<(), String> { + if !simple(cmd) { + return Err("not a simple command".into()); + } + let words: Vec<&str> = cmd.split_whitespace().collect(); + let Some(first) = words.first().copied() else { + return Err("empty".into()); + }; + let ok = if first == "git" { + words.get(1).is_some_and(|s| READONLY_GIT.contains(s)) + } else { + READONLY_CMDS.contains(&first) + }; + if !ok { + return Err(format!("`{first}` is not a read-only command")); + } + let bad = RUN_OR_WRITE_FLAGS + .iter() + .filter(|(c, _)| *c == first) + .flat_map(|(_, f)| f.iter()); + for w in &words[1..] { + let flag = w.split_once('=').map_or(*w, |(f, _)| f); + if bad + .clone() + .any(|f| *f == flag || (f.len() > 2 && f.starts_with("--") && flag == *f)) + { + return Err(format!("flag `{flag}` runs or writes")); + } + } + Ok(()) +} + fn simple(cmd: &str) -> bool { !cmd.contains([ '\n', ';', '&', '|', '`', '$', '<', '>', '(', ')', '{', '}', '\\', @@ -175,11 +249,18 @@ impl Policy { if free { why = Some("bash".to_string()); } else { - let hit = self.allow.iter().find_map(|a| { - let (tl, pat) = a.split_once(':')?; - (tl.eq_ignore_ascii_case("bash") && simple(cmd) && glob(pat, cmd.trim())) - .then_some(a) - }); + let hit = self + .allow + .iter() + .find_map(|a| { + let (tl, pat) = a.split_once(':')?; + (tl.eq_ignore_ascii_case("bash") && simple(cmd) && glob(pat, cmd.trim())) + .then(|| a.clone()) + }) + .or_else(|| { + let on = self.allow.iter().any(|a| a.eq_ignore_ascii_case(READONLY)); + (on && readonly_cmd(cmd).is_ok()).then(|| READONLY.to_string()) + }); let Some(hit) = hit else { return Deny(format!("bash `{}` is not in the allowlist", short(cmd))); }; @@ -194,7 +275,7 @@ impl Policy { } } } - why = Some(hit.clone()); + why = Some(hit); } } else if let Some(path) = ["path", "file_path"] .iter() @@ -381,6 +462,7 @@ mod tests { #[test] fn entries() { assert!(check_entry("read").is_ok() && check_entry("bash:cargo *").is_ok()); + assert!(check_entry("readonly").is_ok() && check_entry("readonly:x").is_err()); assert!( check_entry("").is_err() && check_entry("read:x").is_err() @@ -462,6 +544,85 @@ mod tests { )); } + #[test] + fn readonly_entry() { + let p = pol(&["readonly", "read"]); + let b = |c: &str| p.decide("bash", &json!({"command": c})); + for ok in [ + "ls", + "ls -la sub", + "cat a.rs", + "rg -n -w compute --hidden -g '!.git' -g '!.hx'", + "rg -n \"Instal\" README.md", + "fd -e rs", + "find . -name '*.rs'", + "git status", + "git diff --stat", + "git log --oneline -5", + "head -n 5 a.txt", + "grep -rn foo .", + "wc -l a.rs", + "diff a b", + "sort a.txt", + "jq . a.json", + "tree -L 2", + ] { + assert!(matches!(b(ok), Allow(w) if w == "readonly"), "{ok}"); + } + for bad in [ + "find . -exec rm {} +", + "find . -delete", + "find . -fprint x", + "fd -x rm", + "fd --exec rm", + "rg --pre ./x foo", + "rg --pre=./x foo", + "sort -o out a", + "sort --output=out a", + "tree -o out", + "git push", + "git commit -m x", + "git branch -D x", + "git diff --output=x", + "git -C .. status", + "git diff --ext-diff", + "rm a", + "cp a b", + "sed -i s/a/b/ a", + "python3 -c 'print(1)'", + "python3 test.py", + "cargo test", + "ls; rm a", + "cat a | sh", + "echo hi > a", + "ls $(id)", + "cat .env", + "cat ~/.ssh/id_rsa", + "cat /etc/passwd", + "ls ..", + "ls /", + "head ../../x", + "", + " ", + ] { + assert!(matches!(b(bad), Deny(_)), "{bad}"); + } + // without the entry the same command is denied; patterns and `readonly` combine + assert!(matches!( + pol(&["read"]).decide("bash", &json!({"command": "ls"})), + Deny(_) + )); + let both = pol(&["readonly", "bash:cargo *"]); + assert!( + matches!(both.decide("bash", &json!({"command": "cargo test"})), Allow(w) if w == "bash:cargo *") + ); + assert!( + matches!(both.decide("bash", &json!({"command": "ls"})), Allow(w) if w == "readonly") + ); + // readonly does not make write tools available + assert!(matches!(p.decide("write", &json!({"path": "a"})), Deny(_))); + } + #[test] fn bash_rules() { let p = pol(&["bash:cargo *", "bash:git status", "read"]); diff --git a/tests/e2e.py b/tests/e2e.py index 5a1b7af..a7ea09b 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -249,6 +249,14 @@ subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "- check(run("foreign", "sec", env=senv, body="CALL read a.txt"), "failed", "setup:") subprocess.run(["git", "rm", "-q", "-r", ".hx"], cwd=repo, check=True) subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "rm"], cwd=repo, check=True) +# `readonly` entry: looking commands pass through the real guard, running/writing ones do not +profile("ro", f'home = "{work_home}"\nallow = ["readonly", "write"]\n') +s = check(run("ro-ok", "ro", env=senv, body="CALL bash ls -la\nCALL bash rg -n foo .\nCALL bash git status\nCALL write a.txt"), "done") +assert git_show(s["branch"], "calls.txt").count("RAN") == 3 +for name, call in [("ro-exec", "CALL bash find . -exec rm {} +"), ("ro-rm", "CALL bash rm a.txt"), ("ro-chain", "CALL bash ls; rm a"), + ("ro-secret", "CALL bash cat .env"), ("ro-out", "CALL bash ls /etc")]: + check(run(name, "ro", env=senv, body=call), "needs-human", "policy:") + # the guard process alone (no orch kill racing it): block / continue over the extension protocol gwt = tmp / "gwt" gwt.mkdir()