permit: quote-aware command chains, always-allow for pipelines
This commit is contained in:
1 parent
c29df05e0b
commit
e892fdda67
2 files changed
+196
-41
No files matched your search
+195
-41
@@ -14,10 +14,9 @@ const READONLY: &[&str] = &[
|
||||
"ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "pwd", "echo", "stat", "file", "du",
|
||||
"df", "which", "tree", "diff", "sort", "cut", "nl", "tr", "jq", "find",
|
||||
];
|
||||
/// `find` actions that run or write; `sort -o` writes a file.
|
||||
/// `find` actions that run or write. `sort -o` and `rg --pre` are handled in `readonly_seg`.
|
||||
const WRITING_FLAGS: &[&str] = &[
|
||||
"-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls",
|
||||
"-o", "--output",
|
||||
];
|
||||
const READONLY_GIT: &[&str] = &[
|
||||
"status",
|
||||
@@ -48,19 +47,149 @@ pub fn secret(path: &str) -> bool {
|
||||
|| name.ends_with(".key")
|
||||
}
|
||||
|
||||
fn readonly_cmd(cmd: &str) -> bool {
|
||||
// `||` yields an empty segment, which is rejected
|
||||
!cmd.is_empty() && cmd.split('|').all(|seg| readonly_simple(seg.trim()))
|
||||
/// One simple command of a chain: its words and its source text.
|
||||
struct Seg {
|
||||
words: Vec<String>,
|
||||
raw: String,
|
||||
}
|
||||
|
||||
fn readonly_simple(cmd: &str) -> bool {
|
||||
let w: Vec<&str> = cmd.split_whitespace().collect();
|
||||
/// Split a command line at unquoted `|`, `&&`, `;` into simple commands. `None` for anything else
|
||||
/// the shell would interpret (`||`, `&`, `$`, backticks, parens, `<`, `>`, newlines, open quotes);
|
||||
/// `2>&1` and `>/dev/null` are the only redirects accepted.
|
||||
// ponytail: not a shell parser (no heredocs, `{}` groups, `$'..'`); those ask every time.
|
||||
#[allow(unused_assignments)]
|
||||
fn split_cmd(cmd: &str) -> Option<Vec<Seg>> {
|
||||
let cs: Vec<(usize, char)> = cmd.char_indices().collect();
|
||||
let mut segs: Vec<Seg> = Vec::new();
|
||||
let mut words: Vec<String> = Vec::new();
|
||||
let (mut w, mut in_w, mut start, mut i) = (String::new(), false, 0usize, 0usize);
|
||||
// close the current segment at byte `p`; the next one starts `skip` bytes later
|
||||
macro_rules! end {
|
||||
($p:expr, $skip:expr) => {{
|
||||
if in_w {
|
||||
words.push(std::mem::take(&mut w));
|
||||
in_w = false;
|
||||
}
|
||||
if words.is_empty() {
|
||||
return None;
|
||||
}
|
||||
segs.push(Seg {
|
||||
words: std::mem::take(&mut words),
|
||||
raw: cmd[start..$p].trim().to_string(),
|
||||
});
|
||||
start = $p + $skip;
|
||||
}};
|
||||
}
|
||||
while i < cs.len() {
|
||||
let (p, c) = cs[i];
|
||||
let next = cs.get(i + 1).map(|x| x.1);
|
||||
match c {
|
||||
'\'' => {
|
||||
in_w = true;
|
||||
i += 1;
|
||||
while cs.get(i)?.1 != '\'' {
|
||||
w.push(cs[i].1);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'"' => {
|
||||
in_w = true;
|
||||
i += 1;
|
||||
while cs.get(i)?.1 != '"' {
|
||||
match cs[i].1 {
|
||||
'$' | '`' => return None,
|
||||
'\\' => {
|
||||
i += 1;
|
||||
w.push(cs.get(i)?.1);
|
||||
}
|
||||
ch => w.push(ch),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'\\' => {
|
||||
i += 1;
|
||||
w.push(cs.get(i)?.1);
|
||||
in_w = true;
|
||||
}
|
||||
'|' | ';' => {
|
||||
if c == '|' && next == Some('|') {
|
||||
return None;
|
||||
}
|
||||
end!(p, 1);
|
||||
}
|
||||
'&' if next == Some('&') => {
|
||||
end!(p, 2);
|
||||
i += 1;
|
||||
}
|
||||
'&' | '>' => {
|
||||
// only `[fd]>&1|&2|/dev/null` and `&>/dev/null`
|
||||
let o = if c == '&' { i + 1 } else { i };
|
||||
if c == '&' && next != Some('>') || w.chars().any(|d| !d.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let rest = &cmd[cs[o].0 + 1..];
|
||||
let t = rest.trim_start_matches(' ');
|
||||
let tail_ok = |n: usize| {
|
||||
t[n..]
|
||||
.chars()
|
||||
.next()
|
||||
.is_none_or(|x| x.is_whitespace() || "|;&".contains(x))
|
||||
};
|
||||
let n = ["&1", "&2", "/dev/null"]
|
||||
.iter()
|
||||
.find(|x| t.starts_with(**x) && tail_ok(x.len()))?
|
||||
.len();
|
||||
let stop = cs[o].0 + 1 + rest.len() - t.len() + n;
|
||||
w.clear();
|
||||
in_w = false;
|
||||
i = o;
|
||||
while i + 1 < cs.len() && cs[i + 1].0 < stop {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'<' | '`' | '$' | '(' | ')' | '\n' => return None,
|
||||
c if c.is_whitespace() => {
|
||||
if in_w {
|
||||
words.push(std::mem::take(&mut w));
|
||||
in_w = false;
|
||||
}
|
||||
}
|
||||
c => {
|
||||
w.push(c);
|
||||
in_w = true;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
end!(cmd.len(), 0);
|
||||
Some(segs)
|
||||
}
|
||||
|
||||
fn readonly_cmd(cmd: &str) -> bool {
|
||||
split_cmd(cmd).is_some_and(|s| s.iter().all(readonly_seg))
|
||||
}
|
||||
|
||||
/// `cd` is free: it only matters for what follows, and that is checked on its own.
|
||||
fn readonly_seg(s: &Seg) -> bool {
|
||||
let w: Vec<&str> = s.words.iter().map(String::as_str).collect();
|
||||
let ok = match w.as_slice() {
|
||||
[] => false,
|
||||
["cd", _] => true,
|
||||
["git", sub, ..] => READONLY_GIT.contains(sub),
|
||||
[c, args @ ..] => READONLY.contains(c) && !args.iter().any(|a| WRITING_FLAGS.contains(a)),
|
||||
[c, args @ ..] => {
|
||||
READONLY.contains(c)
|
||||
&& !args.iter().any(|a| {
|
||||
WRITING_FLAGS.contains(a)
|
||||
|| *c == "rg" && a.starts_with("--pre")
|
||||
|| *c == "sort"
|
||||
&& a.starts_with('-')
|
||||
&& (a.starts_with("--output")
|
||||
|| !a.starts_with("--") && a.contains('o'))
|
||||
})
|
||||
}
|
||||
};
|
||||
ok && !compound(&cmd.replace('|', "")) && !w.iter().any(|a| secret(a))
|
||||
ok && !w.iter().any(|a| secret(a))
|
||||
}
|
||||
|
||||
/// Does this call need a yes? Writes and unknown commands do; reads of non-secret files do not.
|
||||
@@ -105,15 +234,10 @@ const RISKY: &[&str] = &[
|
||||
"zsh", "eval", "exec", "xargs", "find", "env", "git",
|
||||
];
|
||||
|
||||
/// Shell syntax that chains or redirects: such commands match no pattern rule and are never
|
||||
/// remembered, so `cargo test && rm -rf ~` cannot ride on a `cargo test *` rule.
|
||||
fn compound(cmd: &str) -> bool {
|
||||
cmd.contains(['\n', ';', '&', '|', '<', '>', '`', '$', '(', ')'])
|
||||
}
|
||||
|
||||
/// Rule for "allow always". Bash: `bash:<command words> *` (first word, plus the subcommand when
|
||||
/// there is one, e.g. `bash:cargo test *`); risky or compound commands store the exact command, or
|
||||
/// nothing at all for compound ones (empty rule = the prompt offers no "always").
|
||||
/// Rule for "allow always". Bash: one `bash:<command words> *` per non-read-only segment of the
|
||||
/// chain (first word, plus the subcommand when there is one, e.g. `bash:cargo test *`), joined by
|
||||
/// newlines; risky segments store their exact text; unparsable commands get no rule (empty rule =
|
||||
/// the prompt offers no "always"). So `cargo test && rm -rf ~` cannot ride on a `cargo test *` rule.
|
||||
/// File tools have no rule (the prompt offers `allow all edits this session` instead).
|
||||
// ponytail: patterns are `*` globs on the full command line; add argument-aware rules if needed.
|
||||
pub fn request(tool: &str, args: &serde_json::Value) -> Request {
|
||||
@@ -127,20 +251,29 @@ pub fn request(tool: &str, args: &serde_json::Value) -> Request {
|
||||
}
|
||||
let cmd = s("command");
|
||||
let cmd = cmd.trim().to_string();
|
||||
let words: Vec<&str> = cmd.split_whitespace().collect();
|
||||
let rule = if compound(&cmd) || words.is_empty() {
|
||||
String::new()
|
||||
} else if RISKY.contains(&words[0]) {
|
||||
format!("bash:{cmd}")
|
||||
} else if let Some(w) = words.get(1).filter(|w| {
|
||||
w.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
&& !w.starts_with('-')
|
||||
}) {
|
||||
format!("bash:{} {w} *", words[0])
|
||||
} else {
|
||||
format!("bash:{} *", words[0])
|
||||
};
|
||||
let mut rules: Vec<String> = Vec::new();
|
||||
for g in split_cmd(&cmd)
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|g| !readonly_seg(g))
|
||||
{
|
||||
let words = &g.words;
|
||||
let r = if RISKY.contains(&words[0].as_str()) {
|
||||
format!("bash:{}", g.raw)
|
||||
} else if let Some(w) = words.get(1).filter(|w| {
|
||||
w.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
&& !w.starts_with('-')
|
||||
}) {
|
||||
format!("bash:{} {w} *", words[0])
|
||||
} else {
|
||||
format!("bash:{} *", words[0])
|
||||
};
|
||||
if !rules.contains(&r) {
|
||||
rules.push(r);
|
||||
}
|
||||
}
|
||||
let rule = rules.join("\n");
|
||||
Request {
|
||||
tool: tool.into(),
|
||||
detail: cmd,
|
||||
@@ -201,13 +334,17 @@ impl Allow {
|
||||
if r.tool != "bash" {
|
||||
return self.rules.contains(&r.rule);
|
||||
}
|
||||
if compound(&r.detail) {
|
||||
let Some(segs) = split_cmd(&r.detail) else {
|
||||
return false;
|
||||
}
|
||||
self.rules
|
||||
.iter()
|
||||
.filter_map(|x| x.strip_prefix("bash:"))
|
||||
.any(|p| glob(p, &r.detail) || p.strip_suffix(" *").is_some_and(|b| b == r.detail))
|
||||
};
|
||||
segs.iter().all(|g| {
|
||||
readonly_seg(g)
|
||||
|| self
|
||||
.rules
|
||||
.iter()
|
||||
.filter_map(|x| x.strip_prefix("bash:"))
|
||||
.any(|p| glob(p, &g.raw) || p.strip_suffix(" *").is_some_and(|b| b == g.raw))
|
||||
})
|
||||
}
|
||||
|
||||
/// Toggle: allow everything (not persisted); returns the new state.
|
||||
@@ -226,7 +363,7 @@ impl Allow {
|
||||
if rule.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.rules.insert(rule.into());
|
||||
self.rules.extend(rule.lines().map(String::from));
|
||||
if let Some(f) = &self.file {
|
||||
let mut v: Vec<_> = self.rules.iter().collect();
|
||||
v.sort();
|
||||
@@ -258,9 +395,15 @@ mod tests {
|
||||
#[test]
|
||||
fn rules_from_requests() {
|
||||
assert_eq!(bash("cargo test -q").rule, "bash:cargo test *");
|
||||
assert_eq!(bash("ls -l").rule, "bash:ls *");
|
||||
assert_eq!(bash("ls -l").rule, ""); // read-only: never asked
|
||||
assert_eq!(bash("rm -rf target").rule, "bash:rm -rf target");
|
||||
assert_eq!(bash("cargo test && rm -rf ~").rule, "");
|
||||
assert_eq!(
|
||||
bash("cargo test && rm -rf ~").rule,
|
||||
"bash:cargo test *\nbash:rm -rf ~"
|
||||
);
|
||||
assert_eq!(bash("go test ./... 2>&1 | tail -30").rule, "bash:go test *");
|
||||
assert_eq!(bash("cd x && go test ./... | tail").rule, "bash:go test *");
|
||||
assert_eq!(bash("go test $(id)").rule, "");
|
||||
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "");
|
||||
assert!(gated("bash") && !gated("read"));
|
||||
}
|
||||
@@ -285,6 +428,13 @@ mod tests {
|
||||
assert!(ask("bash", "command", "node -e 1") && ask("bash", "command", "python3 -c 1"));
|
||||
assert!(ask("bash", "command", "cat a | rm x") && ask("bash", "command", "ls > f"));
|
||||
assert!(ask("bash", "command", "git push") && ask("bash", "command", "find . -delete"));
|
||||
assert!(!ask("bash", "command", r#"rg "foo|bar" src | tail -5"#));
|
||||
assert!(!ask("bash", "command", "rg -o 'fn (a|b)' src 2>&1 | tail"));
|
||||
assert!(!ask("bash", "command", "cd src && rg x 2>/dev/null"));
|
||||
assert!(ask("bash", "command", "rg --pre sh x") && ask("bash", "command", "sort -ro f"));
|
||||
assert!(ask("bash", "command", "ls 2>x") && ask("bash", "command", "ls >> /dev/null"));
|
||||
assert!(ask("bash", "command", "ls 'a") && ask("bash", "command", "ls & rm x"));
|
||||
assert!(ask("bash", "command", "cd x && rm y") && ask("bash", "command", "echo \"$HOME\""));
|
||||
assert!(ask("bash", "command", "cargo test") && ask("bash", "command", ""));
|
||||
assert!(ask("write", "path", "a") && ask("edit", "path", "a"));
|
||||
}
|
||||
@@ -298,6 +448,10 @@ mod tests {
|
||||
assert!(a.allows(&bash("cargo test")) && a.allows(&bash("cargo test -p x")));
|
||||
assert!(!a.allows(&bash("cargo publish")) && !a.allows(&bash("cargo testx")));
|
||||
assert!(!a.allows(&bash("cargo test && rm -rf ~")) && !a.allows(&bash("cargo test; id")));
|
||||
assert!(
|
||||
a.allows(&bash("cargo test 2>&1 | tail -3")) && a.allows(&bash("cd a && cargo test"))
|
||||
);
|
||||
assert!(!a.allows(&bash("cargo test | sh")));
|
||||
assert!(a.allows(&bash("rm -rf target")) && !a.allows(&bash("rm -rf /")));
|
||||
// persisted
|
||||
assert!(Allow::load(d.path()).allows(&bash("cargo test -q")));
|
||||
|
||||
Reference in new issue
Block a user