allowlist entry readonly

This commit is contained in:
hermes committed 2026-11-14 11:29:03 +00:00
1 parent 9ce4756fad
commit e668eb1b0d
4 files changed
+182 -7

No files matched your search

+167 -6
View File
@@ -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"]);