Files
hx/crates/hx-core/src/permit.rs
T

542 lines
19 KiB
Rust

//! Permission gate for mutating tools (bash, write, edit) and secret reads and the edits log behind `/review`.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// Tools that need a yes before they run.
pub fn gated(tool: &str) -> bool {
matches!(tool, "bash" | "write" | "edit")
}
/// Read-only commands that run without a prompt (when not compound and no argument is a secret).
/// Pipes are fine when every segment is read-only. Not listed on purpose: env, xargs, sed, cargo, curl.
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` and `rg --pre` are handled in `readonly_seg`.
const WRITING_FLAGS: &[&str] = &[
"-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls",
];
const READONLY_GIT: &[&str] = &[
"status",
"log",
"diff",
"show",
"branch",
"blame",
"ls-files",
"rev-parse",
];
/// Paths that hold credentials: reading them asks first.
// ponytail: name/dir patterns only; add content sniffing if needed.
pub fn secret(path: &str) -> bool {
let p = path.trim_matches(['"', '\'']);
let comps: Vec<&str> = p.split('/').collect();
let name = comps.last().copied().unwrap_or_default();
comps
.iter()
.any(|c| matches!(*c, ".ssh" | ".aws" | ".gnupg"))
|| name.starts_with(".env")
|| name.starts_with("id_rsa")
|| name.starts_with("id_ed25519")
|| name.starts_with("credentials")
|| matches!(name, ".netrc" | ".git-credentials" | "auth.json")
|| name.ends_with(".pem")
|| name.ends_with(".key")
}
/// One simple command of a chain: its words and its source text.
pub(crate) struct Seg {
pub(crate) words: Vec<String>,
pub(crate) raw: String,
}
/// 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)]
pub(crate) 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.
pub(crate) 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 == "rg" && a.starts_with("--pre")
|| *c == "sort"
&& a.starts_with('-')
&& (a.starts_with("--output")
|| !a.starts_with("--") && a.contains('o'))
})
}
};
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.
pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool {
let a = |k: &str| args[k].as_str().unwrap_or_default();
match tool {
"bash" => !readonly_cmd(a("command").trim()),
"read" => secret(a("path")),
"web_fetch" => true,
_ => gated(tool),
}
}
/// What the user is asked.
#[derive(Debug, Clone, PartialEq)]
pub struct Request {
pub tool: String,
/// One line: the command or the path.
pub detail: String,
/// What "allow always" stores and shows.
pub rule: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
Once,
Always,
/// All write/edit calls for the rest of this session (not persisted).
Edits,
Deny,
}
/// Asks the user; set by interactive frontends only (None = everything runs, as in print mode).
pub type Permit = std::sync::Arc<
dyn Fn(Request) -> std::pin::Pin<Box<dyn std::future::Future<Output = Decision> + Send>>
+ Send
+ Sync,
>;
/// 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",
];
/// 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 {
let s = |k: &str| args[k].as_str().unwrap_or_default().to_string();
if tool == "web_fetch" {
let url = s("url");
let host = url
.split_once("://")
.map_or(url.as_str(), |x| x.1)
.split(['/', '?', '#'])
.next()
.unwrap_or_default()
.rsplit('@')
.next()
.unwrap_or_default()
.to_string();
return Request {
tool: tool.into(),
detail: url,
rule: format!("web:{host}"),
};
}
if tool != "bash" {
return Request {
tool: tool.into(),
detail: s("path"),
rule: String::new(),
};
}
let cmd = s("command");
let cmd = cmd.trim().to_string();
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,
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`.
#[derive(Default)]
pub struct Allow {
rules: HashSet<String>,
all_edits: bool,
yolo: bool,
auto: bool,
/// Plan mode: read-only until the user approves a plan.
plan: bool,
/// Last calls auto mode refused (newest last), for `/auto`.
blocks: Vec<String>,
file: Option<PathBuf>,
}
impl Allow {
pub fn load(cwd: &Path) -> Self {
let file = cwd.join(".hx/allow.json");
let rules = std::fs::read_to_string(&file)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
Self {
rules,
all_edits: false,
yolo: false,
auto: false,
plan: false,
blocks: Vec::new(),
file: Some(file),
}
}
/// 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 self.yolo || self.all_edits && matches!(r.tool.as_str(), "write" | "edit") {
return true;
}
if r.tool != "bash" {
return self.rules.contains(&r.rule);
}
let Some(segs) = split_cmd(&r.detail) else {
return false;
};
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))
})
}
pub fn yolo_on(&self) -> bool {
self.yolo
}
/// Toggle: allow everything (not persisted); returns the new state.
pub fn toggle_yolo(&mut self) -> bool {
self.yolo = !self.yolo;
self.yolo
}
pub fn plan_on(&self) -> bool {
self.plan
}
pub fn set_plan(&mut self, on: bool) {
self.plan = on;
hx_ai::claude_cli::set_plan(on);
}
pub fn auto_on(&self) -> bool {
self.auto
}
/// Auto mode: dangerous calls are refused, safe ones run, the rest is judged or asked.
pub fn set_auto(&mut self, on: bool) {
self.auto = on;
}
/// Remember a refused call (last 20).
pub fn note_block(&mut self, s: String) {
if self.blocks.len() >= 20 {
self.blocks.remove(0);
}
self.blocks.push(s);
}
pub fn blocks(&self) -> &[String] {
&self.blocks
}
/// Allow every write/edit until the session ends.
pub fn allow_edits(&mut self) {
self.all_edits = true;
}
/// 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.extend(rule.lines().map(String::from));
if let Some(f) = &self.file {
let mut v: Vec<_> = self.rules.iter().collect();
v.sort();
if let Some(d) = f.parent() {
let _ = std::fs::create_dir_all(d);
}
let _ = std::fs::write(f, serde_json::to_string_pretty(&v).unwrap_or_default());
}
}
}
/// One file change by write/edit; `old` None = the file did not exist.
#[derive(Debug, Clone, PartialEq)]
pub struct FileEdit {
pub path: PathBuf,
pub old: Option<String>,
pub new: String,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn bash(c: &str) -> Request {
request("bash", &json!({ "command": c }))
}
#[test]
fn rules_from_requests() {
assert_eq!(bash("cargo test -q").rule, "bash:cargo test *");
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,
"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"));
}
#[test]
fn reads_are_free_unless_secret() {
let ask = |t: &str, k: &str, v: &str| needs_permit(t, &json!({ k: v }));
assert!(!ask("read", "path", "src/main.rs"));
assert!(ask("read", "path", ".env") && ask("read", "path", "/h/.ssh/config"));
assert!(ask("read", "path", "certs/a.pem"));
assert!(!ask("bash", "command", "ls -l"));
assert!(!ask("bash", "command", "git status"));
assert!(!ask("bash", "command", "grep -rn foo src"));
assert!(ask("bash", "command", "cat .env") && ask("bash", "command", "cat ~/.ssh/id_rsa"));
assert!(!ask("bash", "command", "rg foo src | head -5"));
assert!(!ask("bash", "command", "find . -name '*.rs' | sort | head"));
assert!(!ask("bash", "command", "cat a.json | jq .x"));
assert!(
ask("bash", "command", "find . -exec rm {} +") && ask("bash", "command", "sort -o f f")
);
assert!(ask("bash", "command", "ls || rm x") && ask("bash", "command", "ls | sh"));
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"));
}
#[test]
fn web_fetch_asks_once_per_domain() {
let a = |u: &str| serde_json::json!({ "url": u });
assert!(needs_permit("web_fetch", &a("https://docs.rs/x")));
let d = tempfile::tempdir().unwrap();
let mut al = Allow::load(d.path());
let r = request("web_fetch", &a("https://user@docs.rs/serde?x=1"));
assert_eq!(r.rule, "web:docs.rs");
assert!(!al.allows(&r));
al.add(&r.rule);
assert!(al.allows(&request("web_fetch", &a("https://docs.rs/other"))));
assert!(!al.allows(&request("web_fetch", &a("https://evil.test/"))));
}
#[test]
fn rules_match_narrowly() {
let d = tempfile::tempdir().unwrap();
let mut a = Allow::load(d.path());
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("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")));
a.add("");
assert!(!a.allows(&bash("")));
let e = request("edit", &json!({"path": "a.rs"}));
assert!(!a.allows(&e));
a.allow_edits();
assert!(a.allows(&e) && !a.allows(&bash("make")));
assert!(a.toggle_yolo() && a.allows(&bash("rm -rf /")) && !a.toggle_yolo());
}
}