Allowlist: readonly entry, on_deny = continue, tokens of stopped runs (#20)
This commit was merged in pull request #20.
This commit is contained in:
1 parent
9ce4756fad
commit
39a2e74742
11 files changed
+487
-89
No files matched your search
+259
-35
@@ -20,6 +20,8 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MARK: &str = "# orch-guard (generated, do not edit)";
|
||||
pub const PREFIX: &str = "orch-guard:";
|
||||
/// Block reason of a soft deny under `on_deny = "continue"`: the run goes on, orch only counts it.
|
||||
pub const SOFT_PREFIX: &str = "orch-guard-soft:";
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct Policy {
|
||||
@@ -29,12 +31,27 @@ pub struct Policy {
|
||||
pub worktree: PathBuf,
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
pub audit: PathBuf,
|
||||
/// `on_deny = "continue"`: soft denies are answered to the agent instead of ending the run.
|
||||
#[serde(default)]
|
||||
pub soft_continue: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Decision {
|
||||
Allow(String),
|
||||
/// Not in the allowlist: with `on_deny = "continue"` the agent gets the reason and works on.
|
||||
Deny(String),
|
||||
/// Never negotiable: credentials, outside the worktree, `git push`, `.git`/`.hx`. Ends the run.
|
||||
Hard(String),
|
||||
}
|
||||
|
||||
impl Decision {
|
||||
pub fn deny_reason(&self) -> Option<&str> {
|
||||
match self {
|
||||
Decision::Deny(w) | Decision::Hard(w) => Some(w),
|
||||
Decision::Allow(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `*` matches any run of characters (including none); everything else is literal.
|
||||
@@ -126,6 +143,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', ';', '&', '|', '`', '$', '<', '>', '(', ')', '{', '}', '\\',
|
||||
@@ -163,10 +254,10 @@ impl Policy {
|
||||
s("command")
|
||||
};
|
||||
if mentions_git_push(cmd) {
|
||||
return Deny("git push is done by the sink, not the agent".into());
|
||||
return Hard("git push is done by the sink, not the agent".into());
|
||||
}
|
||||
if cmd.split_whitespace().any(secret) {
|
||||
return Deny("command touches a secret-looking path".into());
|
||||
return Hard("command touches a secret-looking path".into());
|
||||
}
|
||||
let free = self
|
||||
.allow
|
||||
@@ -175,11 +266,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)));
|
||||
};
|
||||
@@ -190,11 +288,11 @@ impl Policy {
|
||||
let ok = !w.starts_with('~')
|
||||
&& self.inside(&resolve(&self.worktree, w), &self.roots());
|
||||
if !ok {
|
||||
return Deny(format!("path `{w}` is outside the worktree"));
|
||||
return Hard(format!("path `{w}` is outside the worktree"));
|
||||
}
|
||||
}
|
||||
}
|
||||
why = Some(hit.clone());
|
||||
why = Some(hit);
|
||||
}
|
||||
} else if let Some(path) = ["path", "file_path"]
|
||||
.iter()
|
||||
@@ -204,21 +302,21 @@ impl Policy {
|
||||
let write = matches!(t.as_str(), "write" | "edit");
|
||||
let r = resolve(&self.worktree, path);
|
||||
if secret(&r.to_string_lossy()) {
|
||||
return Deny(format!("`{path}` looks like a credential file"));
|
||||
return Hard(format!("`{path}` looks like a credential file"));
|
||||
}
|
||||
if write {
|
||||
let rel = r.strip_prefix(&self.worktree);
|
||||
if rel.is_err() {
|
||||
return Deny(format!("write outside the worktree: `{path}`"));
|
||||
return Hard(format!("write outside the worktree: `{path}`"));
|
||||
}
|
||||
if rel.is_ok_and(|x| {
|
||||
x.components()
|
||||
.any(|c| matches!(c.as_os_str().to_str(), Some(".git" | ".hx")))
|
||||
}) {
|
||||
return Deny(format!("`{path}` is guard/git metadata"));
|
||||
return Hard(format!("`{path}` is guard/git metadata"));
|
||||
}
|
||||
} else if !self.inside(&r, &self.roots()) {
|
||||
return Deny(format!("read outside the worktree: `{path}`"));
|
||||
return Hard(format!("read outside the worktree: `{path}`"));
|
||||
}
|
||||
}
|
||||
if why.is_none() {
|
||||
@@ -269,7 +367,13 @@ fn policy_path(run: &str) -> PathBuf {
|
||||
|
||||
/// Writes the policy and the worktree's `.hx/config.toml` that starts the guard. Rewritten before every
|
||||
/// attempt, so an agent that edited it is healed. Refuses to touch a config that is not ours.
|
||||
pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) -> Result<Policy> {
|
||||
pub fn install(
|
||||
run: &str,
|
||||
wt: &Path,
|
||||
allow: &[String],
|
||||
read_roots: &[PathBuf],
|
||||
soft_continue: bool,
|
||||
) -> Result<Policy> {
|
||||
let pol = Policy {
|
||||
run: run.into(),
|
||||
allow: allow.to_vec(),
|
||||
@@ -279,6 +383,7 @@ pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) -
|
||||
.map(|r| resolve(Path::new("/"), &r.to_string_lossy()))
|
||||
.collect(),
|
||||
audit: audit_path(),
|
||||
soft_continue,
|
||||
};
|
||||
let pp = policy_path(run);
|
||||
std::fs::create_dir_all(pp.parent().unwrap())?;
|
||||
@@ -328,6 +433,16 @@ pub fn guard(policy_file: &Path) -> Result<()> {
|
||||
let (act, why, extra) = match &d {
|
||||
Decision::Allow(w) => ("allow", w.clone(), json!({"action": "continue"})),
|
||||
Decision::Deny(w) => (
|
||||
"deny",
|
||||
w.clone(),
|
||||
// soft: the agent reads the reason and picks another way (orch does not kill the run)
|
||||
json!({"action": "block", "reason": if pol.soft_continue {
|
||||
format!("{SOFT_PREFIX} {w}. Use another way (allowed: read-only commands, project tests).")
|
||||
} else {
|
||||
format!("{PREFIX} {w}")
|
||||
}}),
|
||||
),
|
||||
Decision::Hard(w) => (
|
||||
"deny",
|
||||
w.clone(),
|
||||
json!({"action": "block", "reason": format!("{PREFIX} {w}")}),
|
||||
@@ -337,7 +452,8 @@ pub fn guard(policy_file: &Path) -> Result<()> {
|
||||
&pol.audit,
|
||||
&pol.run,
|
||||
"tool",
|
||||
json!({"tool": tool, "decision": act, "why": why, "args": e["args"]}),
|
||||
json!({"tool": tool, "decision": act, "why": why, "args": e["args"],
|
||||
"hard": matches!(d, Decision::Hard(_))}),
|
||||
);
|
||||
Ok(extra)
|
||||
}
|
||||
@@ -358,6 +474,11 @@ mod tests {
|
||||
use super::*;
|
||||
use Decision::*;
|
||||
|
||||
/// Denied, soft or hard.
|
||||
fn denied(d: Decision) -> bool {
|
||||
d.deny_reason().is_some()
|
||||
}
|
||||
|
||||
fn pol(allow: &[&str]) -> Policy {
|
||||
let d = std::env::temp_dir().join(format!("orch-pol-{}", std::process::id()));
|
||||
std::fs::create_dir_all(d.join("wt/sub")).unwrap();
|
||||
@@ -367,6 +488,7 @@ mod tests {
|
||||
worktree: d.join("wt").canonicalize().unwrap(),
|
||||
read_roots: vec![],
|
||||
audit: d.join("audit"),
|
||||
soft_continue: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,6 +503,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()
|
||||
@@ -400,13 +523,10 @@ mod tests {
|
||||
Allow(_)
|
||||
));
|
||||
assert!(
|
||||
matches!(p.decide("write", &json!({"path": "a.rs"})), Deny(_)),
|
||||
denied(p.decide("write", &json!({"path": "a.rs"}))),
|
||||
"not in allowlist"
|
||||
);
|
||||
assert!(matches!(
|
||||
p.decide("bash", &json!({"command": "ls"})),
|
||||
Deny(_)
|
||||
));
|
||||
assert!(denied(p.decide("bash", &json!({"command": "ls"}))));
|
||||
assert!(matches!(
|
||||
pol(&["*"]).decide("anything", &json!({})),
|
||||
Allow(_)
|
||||
@@ -424,10 +544,7 @@ mod tests {
|
||||
".env",
|
||||
"sub/auth.json",
|
||||
] {
|
||||
assert!(
|
||||
matches!(p.decide("write", &json!({"path": bad})), Deny(_)),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(denied(p.decide("write", &json!({"path": bad}))), "{bad}");
|
||||
}
|
||||
for bad in [
|
||||
"/etc/passwd",
|
||||
@@ -435,20 +552,14 @@ mod tests {
|
||||
"/home/other/.hx/auth.json",
|
||||
".ssh/id_rsa",
|
||||
] {
|
||||
assert!(
|
||||
matches!(p.decide("read", &json!({"path": bad})), Deny(_)),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(denied(p.decide("read", &json!({"path": bad}))), "{bad}");
|
||||
}
|
||||
for bad in [
|
||||
".git/hooks/pre-commit",
|
||||
".hx/config.toml",
|
||||
"sub/../.hx/config.toml",
|
||||
] {
|
||||
assert!(
|
||||
matches!(p.decide("edit", &json!({"path": bad})), Deny(_)),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(denied(p.decide("edit", &json!({"path": bad}))), "{bad}");
|
||||
}
|
||||
assert!(matches!(
|
||||
p.decide("read", &json!({"path": format!("{w}/a")})),
|
||||
@@ -456,10 +567,123 @@ mod tests {
|
||||
));
|
||||
// symlink out of the worktree is resolved
|
||||
std::os::unix::fs::symlink("/etc", p.worktree.join("lnk")).ok();
|
||||
assert!(denied(p.decide("read", &json!({"path": "lnk/passwd"}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_and_soft_denies() {
|
||||
let p = pol(&["read", "bash:cargo *"]);
|
||||
let d = |t: &str, a: Value| p.decide(t, &a);
|
||||
// soft: simply not allowed, the agent may try something else
|
||||
assert!(matches!(d("bash", json!({"command": "ls"})), Deny(_)));
|
||||
assert!(matches!(
|
||||
p.decide("read", &json!({"path": "lnk/passwd"})),
|
||||
d("bash", json!({"command": "python3 -c 'print(1)'"})),
|
||||
Deny(_)
|
||||
));
|
||||
assert!(matches!(d("write", json!({"path": "a.rs"})), Deny(_)));
|
||||
assert!(matches!(d("Foo", json!({})), Deny(_)));
|
||||
// hard: never negotiable
|
||||
assert!(matches!(d("read", json!({"path": ".env"})), Hard(_)));
|
||||
assert!(matches!(d("read", json!({"path": "/etc/passwd"})), Hard(_)));
|
||||
assert!(matches!(
|
||||
d("bash", json!({"command": "git push origin main"})),
|
||||
Hard(_)
|
||||
));
|
||||
assert!(matches!(d("bash", json!({"command": "cat .env"})), Hard(_)));
|
||||
assert!(matches!(
|
||||
d("bash", json!({"command": "cargo run ../../x"})),
|
||||
Hard(_)
|
||||
));
|
||||
let w = pol(&["*"]);
|
||||
assert!(matches!(
|
||||
w.decide("edit", &json!({"path": ".hx/config.toml"})),
|
||||
Hard(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
w.decide("write", &json!({"path": "../x"})),
|
||||
Hard(_)
|
||||
));
|
||||
assert!(
|
||||
Deny("x".into()).deny_reason().is_some() && Allow("x".into()).deny_reason().is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[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!(denied(b(bad)), "{bad}");
|
||||
}
|
||||
// without the entry the same command is denied; patterns and `readonly` combine
|
||||
assert!(denied(
|
||||
pol(&["read"]).decide("bash", &json!({"command": "ls"}))
|
||||
));
|
||||
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!(denied(p.decide("write", &json!({"path": "a"}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -479,7 +703,7 @@ mod tests {
|
||||
"cargo run ../../x",
|
||||
"cargo run ~/x",
|
||||
] {
|
||||
assert!(matches!(b(bad), Deny(_)), "{bad}");
|
||||
assert!(denied(b(bad)), "{bad}");
|
||||
}
|
||||
assert!(matches!(
|
||||
b("cargo build --manifest-path=sub/Cargo.toml"),
|
||||
@@ -496,7 +720,7 @@ mod tests {
|
||||
"cat .env",
|
||||
"cat ~/.ssh/id_rsa",
|
||||
] {
|
||||
assert!(matches!(f(bad), Deny(_)), "{bad}");
|
||||
assert!(denied(f(bad)), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user