permissions: --yolo, command-aware allow rules, load allow.json
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

This commit is contained in:
hermes committed 2026-10-02 21:37:49 +00:00
1 parent b36559bd95
commit 23dc8cd36e
6 files changed
+148 -36

No files matched your search

+97 -23
View File
@@ -32,25 +32,74 @@ pub type Permit = std::sync::Arc<
+ Sync,
>;
/// `bash` rules cover a command's first word (`bash:cargo`); file tools are covered as a whole.
// ponytail: first-word granularity; add glob/argument patterns when people want `rm target/*` only.
/// Never remembered as a pattern: "always" stores the exact command only.
const RISKY: &[&str] = &[
"rm", "sudo", "su", "dd", "mkfs", "chmod", "chown", "curl", "wget", "ssh", "scp", "sh", "bash",
"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").
/// File tools are covered as a whole by the tool name.
// 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 {
let s = |k: &str| args[k].as_str().unwrap_or_default().to_string();
if tool == "bash" {
let cmd = s("command");
let word = cmd.split_whitespace().next().unwrap_or_default();
Request {
tool: tool.into(),
detail: cmd.clone(),
rule: format!("bash:{word}"),
}
} else {
Request {
if tool != "bash" {
return Request {
tool: tool.into(),
detail: s("path"),
rule: tool.into(),
};
}
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])
};
Request {
tool: tool.into(),
detail: cmd,
rule,
}
}
/// `*` matches any run of characters; everything else literally.
fn glob(pat: &str, s: &str) -> bool {
let parts: Vec<&str> = pat.split('*').collect();
if parts.len() == 1 {
return pat == s;
}
let (first, last) = (parts[0], parts[parts.len() - 1]);
if s.len() < first.len() + last.len() || !s.starts_with(first) || !s.ends_with(last) {
return false;
}
let mut at = first.len();
let end = s.len() - last.len();
for m in &parts[1..parts.len() - 1] {
match s[at..end].find(m) {
Some(i) => at += i + m.len(),
None => return false,
}
}
true
}
/// Always-allowed rules, persisted in `<project>/.hx/allow.json`.
@@ -72,11 +121,26 @@ impl Allow {
file: Some(file),
}
}
pub fn has(&self, rule: &str) -> bool {
self.rules.contains(rule)
/// Is this request covered by a stored rule? `bash:cargo test *` also covers a bare `cargo test`.
pub fn allows(&self, r: &Request) -> bool {
if r.tool != "bash" {
return self.rules.contains(&r.rule);
}
if compound(&r.detail) {
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))
}
/// Remember a rule; the file is best effort (the rule holds for this session either way).
pub fn add(&mut self, rule: &str) {
if rule.is_empty() {
return;
}
self.rules.insert(rule.into());
if let Some(f) = &self.file {
let mut v: Vec<_> = self.rules.iter().collect();
@@ -102,23 +166,33 @@ mod tests {
use super::*;
use serde_json::json;
fn bash(c: &str) -> Request {
request("bash", &json!({ "command": c }))
}
#[test]
fn rules_from_requests() {
let r = request("bash", &json!({"command": "cargo test -q"}));
assert_eq!(
(r.rule.as_str(), r.detail.as_str()),
("bash:cargo", "cargo test -q")
);
assert_eq!(bash("cargo test -q").rule, "bash:cargo test *");
assert_eq!(bash("ls -l").rule, "bash:ls *");
assert_eq!(bash("rm -rf target").rule, "bash:rm -rf target");
assert_eq!(bash("cargo test && rm -rf ~").rule, "");
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "edit");
assert!(gated("bash") && !gated("read"));
}
#[test]
fn allow_persists() {
fn rules_match_narrowly() {
let d = tempfile::tempdir().unwrap();
let mut a = Allow::load(d.path());
assert!(!a.has("bash:ls"));
a.add("bash:ls");
assert!(Allow::load(d.path()).has("bash:ls"));
a.add(&bash("cargo test -q").rule);
a.add(&bash("rm -rf target").rule);
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("rm -rf target")) && !a.allows(&bash("rm -rf /")));
// persisted
assert!(Allow::load(d.path()).allows(&bash("cargo test -q")));
a.add("");
assert!(!a.allows(&bash("")));
}
}