Files
orch/src/policy.rs
T

503 lines
17 KiB
Rust

//! Tool policy for headless runs. hx in `-p` mode never prompts (no permission hook = every tool call is
//! allowed), so the allowlist is enforced here, twice: `orch guard` runs as an hx extension and blocks a call
//! before it executes; orch re-checks every `tool_call` event in the NDJSON stream and kills the run, which
//! also catches a dead guard (hx treats a dead or slow extension as "continue").
//!
//! Allowlist entries: `TOOL` (any call of that tool; `*` = every tool) or `bash:PATTERN` (glob, `*` only).
//! A PATTERN matches only simple commands (no `; & | < > $ ( ) { } \` newline backslash), whose path-like words
//! must stay inside the worktree or `read_roots`. Hard rules apply to every allowed call: no `git push`
//! (publishing is the sink's job), no secret-looking paths, file tools stay in the worktree (reads may also
//! use `read_roots`), writes never touch `.git` or `.hx` (guard config).
//! Not enforceable with hx' `claude_cli` provider: the `claude` binary runs its own tools, invisible to hx' event
//! bus. `run::execute` refuses such a run up front (see `report::provider_mode`) instead of running it unguarded.
//! ponytail: plain `bash` is not confined (a shell cannot be parsed reliably); use `sandbox = true` for that.
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io::{BufRead, Write};
use std::path::{Component, Path, PathBuf};
pub const MARK: &str = "# orch-guard (generated, do not edit)";
pub const PREFIX: &str = "orch-guard:";
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Policy {
pub run: String,
pub allow: Vec<String>,
/// Canonical path of the run's worktree.
pub worktree: PathBuf,
pub read_roots: Vec<PathBuf>,
pub audit: PathBuf,
}
#[derive(Debug, PartialEq)]
pub enum Decision {
Allow(String),
Deny(String),
}
/// `*` matches any run of characters (including none); everything else is literal.
pub fn glob(pat: &str, s: &str) -> bool {
let (p, s): (Vec<char>, Vec<char>) = (pat.chars().collect(), s.chars().collect());
let (mut i, mut j, mut star, mut mark) = (0, 0, None, 0);
while j < s.len() {
if i < p.len() && p[i] == '*' {
star = Some(i);
mark = j;
i += 1;
} else if i < p.len() && p[i] == s[j] {
i += 1;
j += 1;
} else if let Some(st) = star {
i = st + 1;
mark += 1;
j = mark;
} else {
return false;
}
}
p[i..].iter().all(|&c| c == '*')
}
/// Validates one profile entry.
pub fn check_entry(e: &str) -> Result<()> {
let (tool, pat) = match e.split_once(':') {
Some((t, p)) => (t, Some(p)),
None => (e, None),
};
if tool.is_empty() || tool.contains(char::is_whitespace) {
bail!("bad allow entry {e:?}");
}
if pat.is_some_and(|p| p.is_empty()) || (pat.is_some() && !tool.eq_ignore_ascii_case("bash")) {
bail!("allow entry {e:?}: only `bash:PATTERN` takes a pattern");
}
Ok(())
}
/// Credentials by name: reading them is never part of a coding task.
pub fn secret(path: &str) -> bool {
let comps: Vec<&str> = path.trim_matches(['"', '\'']).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" | "mcp-auth.json"
)
|| name.ends_with(".pem")
|| name.ends_with(".key")
}
/// Lexical normalization plus symlink resolution of the deepest existing ancestor.
fn resolve(base: &Path, p: &str) -> PathBuf {
let mut out = if Path::new(p).is_absolute() {
PathBuf::new()
} else {
base.to_path_buf()
};
for c in Path::new(p).components() {
match c {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
c => out.push(c.as_os_str()),
}
}
let (mut cur, mut tail) = (out.clone(), vec![]);
loop {
if let Ok(mut c) = cur.canonicalize() {
c.extend(tail.iter().rev());
return c;
}
match cur.file_name().map(|n| n.to_owned()) {
Some(n) => {
tail.push(n);
cur.pop();
}
None => return out,
}
}
}
fn simple(cmd: &str) -> bool {
!cmd.contains([
'\n', ';', '&', '|', '`', '$', '<', '>', '(', ')', '{', '}', '\\',
])
}
fn mentions_git_push(cmd: &str) -> bool {
let words: Vec<&str> = cmd
.split(|c: char| c.is_whitespace() || ";&|()`".contains(c))
.filter(|w| !w.is_empty())
.collect();
words.iter().any(|w| w.rsplit('/').next() == Some("git")) && words.contains(&"push")
}
impl Policy {
fn inside(&self, p: &Path, roots: &[&Path]) -> bool {
roots.iter().any(|r| p.starts_with(r))
}
fn roots(&self) -> Vec<&Path> {
std::iter::once(self.worktree.as_path())
.chain(self.read_roots.iter().map(|r| r.as_path()))
.collect()
}
pub fn decide(&self, tool: &str, args: &Value) -> Decision {
use Decision::*;
let t = tool.to_lowercase();
let s = |k: &str| args[k].as_str().unwrap_or_default();
let mut why = None;
if t == "bash" {
let cmd = if s("command").is_empty() {
s("cmd")
} else {
s("command")
};
if mentions_git_push(cmd) {
return Deny("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());
}
let free = self
.allow
.iter()
.any(|a| a == "*" || a.eq_ignore_ascii_case("bash"));
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 Some(hit) = hit else {
return Deny(format!("bash `{}` is not in the allowlist", short(cmd)));
};
for w in cmd.split_whitespace() {
let w = w.trim_matches(['"', '\'']);
let w = w.split_once('=').map_or(w, |(_, v)| v);
if w.starts_with('/') || w.starts_with('~') || w.contains("..") {
let ok = !w.starts_with('~')
&& self.inside(&resolve(&self.worktree, w), &self.roots());
if !ok {
return Deny(format!("path `{w}` is outside the worktree"));
}
}
}
why = Some(hit.clone());
}
} else if let Some(path) = ["path", "file_path"]
.iter()
.map(|k| s(k))
.find(|p| !p.is_empty())
{
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"));
}
if write {
let rel = r.strip_prefix(&self.worktree);
if rel.is_err() {
return Deny(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"));
}
} else if !self.inside(&r, &self.roots()) {
return Deny(format!("read outside the worktree: `{path}`"));
}
}
if why.is_none() {
why = self
.allow
.iter()
.find(|a| a.as_str() == "*" || a.eq_ignore_ascii_case(&t))
.cloned();
}
match why {
Some(w) => Allow(w),
None => Deny(format!("tool `{tool}` is not in the allowlist")),
}
}
}
fn short(s: &str) -> String {
s.chars().take(80).collect()
}
/// Append-only JSONL audit trail (O_APPEND; lines stay under PIPE_BUF so concurrent writers do not interleave).
pub fn audit(path: &Path, run: &str, ev: &str, detail: Value) {
let mut line =
json!({"ts": crate::state::now(), "run": run, "ev": ev, "detail": detail}).to_string();
line.truncate(3900);
line.push('\n');
if let Some(d) = path.parent() {
let _ = std::fs::create_dir_all(d);
}
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
let _ = f.write_all(line.as_bytes());
}
}
pub fn audit_path() -> PathBuf {
crate::state_dir().join("audit.log")
}
fn policy_path(run: &str) -> PathBuf {
crate::state_dir()
.join("policies")
.join(format!("{run}.json"))
}
/// 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> {
let pol = Policy {
run: run.into(),
allow: allow.to_vec(),
worktree: wt.canonicalize()?,
read_roots: read_roots
.iter()
.map(|r| resolve(Path::new("/"), &r.to_string_lossy()))
.collect(),
audit: audit_path(),
};
let pp = policy_path(run);
std::fs::create_dir_all(pp.parent().unwrap())?;
std::fs::write(&pp, serde_json::to_vec(&pol)?)?;
let cfg = wt.join(".hx/config.toml");
if let Ok(old) = std::fs::read_to_string(&cfg)
&& !old.starts_with(MARK)
{
bail!(
"{} exists in the repo; orch cannot install its guard next to it",
cfg.display()
);
}
std::fs::create_dir_all(cfg.parent().unwrap())?;
let exe = std::env::current_exe()?.to_string_lossy().into_owned();
// `permissions = "extensions-only"` (hx#182): in claude_cli mode a question is allowed only while a LIVE
// `tool_call` extension guards it, so a dead or slow guard denies instead of "continue". hx ignores the value
// for the direct provider's `-p` path, where orch's stream check is the second line of defence.
let ext = toml::to_string(&json!({"permissions": "extensions-only", "extensions": [{
"command": [exe, "guard", pp.to_string_lossy()], "timeout_secs": 10}]}))?;
std::fs::write(cfg, format!("{MARK}\n{ext}"))?;
Ok(pol)
}
/// Removes the guard config after an attempt (it must never end up in the commit).
pub fn uninstall(wt: &Path) {
let cfg = wt.join(".hx/config.toml");
if std::fs::read_to_string(&cfg).is_ok_and(|s| s.starts_with(MARK)) {
let _ = std::fs::remove_file(&cfg);
let _ = std::fs::remove_dir(wt.join(".hx")); // only if empty
}
}
/// `orch guard POLICY.json`: hx extension, JSON-RPC over stdio (see hx README, "Extensions").
pub fn guard(policy_file: &Path) -> Result<()> {
let pol: Policy = serde_json::from_slice(&std::fs::read(policy_file)?)?;
let mut out = std::io::stdout().lock();
for line in std::io::stdin().lock().lines() {
let m: Value = serde_json::from_str(&line?)?;
let Some(id) = m.get("id") else { continue };
let result = match m["method"].as_str() {
Some("initialize") => Ok(json!({"subscribe": ["tool_call"], "tools": []})),
Some("event") => {
let e = &m["params"]["event"];
let tool = e["name"].as_str().unwrap_or_default();
let d = pol.decide(tool, &e["args"]);
let (act, why, extra) = match &d {
Decision::Allow(w) => ("allow", w.clone(), json!({"action": "continue"})),
Decision::Deny(w) => (
"deny",
w.clone(),
json!({"action": "block", "reason": format!("{PREFIX} {w}")}),
),
};
audit(
&pol.audit,
&pol.run,
"tool",
json!({"tool": tool, "decision": act, "why": why, "args": e["args"]}),
);
Ok(extra)
}
_ => Err("unknown method"),
};
let msg = match result {
Ok(r) => json!({"jsonrpc": "2.0", "id": id, "result": r}),
Err(e) => json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": e}}),
};
writeln!(out, "{msg}")?;
out.flush()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use Decision::*;
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();
Policy {
run: "r".into(),
allow: allow.iter().map(|s| s.to_string()).collect(),
worktree: d.join("wt").canonicalize().unwrap(),
read_roots: vec![],
audit: d.join("audit"),
}
}
#[test]
fn globbing() {
assert!(glob("cargo test*", "cargo test -p x"));
assert!(glob("*", ""));
assert!(glob("a*c*e", "abcde") && !glob("a*c*e", "abcdf"));
assert!(!glob("cargo test", "cargo test -p x"));
}
#[test]
fn entries() {
assert!(check_entry("read").is_ok() && check_entry("bash:cargo *").is_ok());
assert!(
check_entry("").is_err()
&& check_entry("read:x").is_err()
&& check_entry("bash:").is_err()
);
}
#[test]
fn tools_and_allowlist() {
let p = pol(&["read", "Edit"]);
assert!(matches!(
p.decide("Read", &json!({"path": "a.rs"})),
Allow(_)
));
assert!(matches!(
p.decide("edit", &json!({"path": "sub/a.rs"})),
Allow(_)
));
assert!(
matches!(p.decide("write", &json!({"path": "a.rs"})), Deny(_)),
"not in allowlist"
);
assert!(matches!(
p.decide("bash", &json!({"command": "ls"})),
Deny(_)
));
assert!(matches!(
pol(&["*"]).decide("anything", &json!({})),
Allow(_)
));
}
#[test]
fn paths_and_secrets() {
let p = pol(&["*"]);
let w = p.worktree.to_string_lossy().to_string();
for bad in [
"../x",
"/etc/passwd",
"sub/../../x",
".env",
"sub/auth.json",
] {
assert!(
matches!(p.decide("write", &json!({"path": bad})), Deny(_)),
"{bad}"
);
}
for bad in [
"/etc/passwd",
"../x",
"/home/other/.hx/auth.json",
".ssh/id_rsa",
] {
assert!(
matches!(p.decide("read", &json!({"path": bad})), Deny(_)),
"{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!(matches!(
p.decide("read", &json!({"path": format!("{w}/a")})),
Allow(_)
));
// symlink out of the worktree is resolved
std::os::unix::fs::symlink("/etc", p.worktree.join("lnk")).ok();
assert!(matches!(
p.decide("read", &json!({"path": "lnk/passwd"})),
Deny(_)
));
}
#[test]
fn bash_rules() {
let p = pol(&["bash:cargo *", "bash:git status", "read"]);
let b = |c: &str| p.decide("bash", &json!({"command": c}));
assert!(matches!(b("cargo test -p x"), Allow(_)) && matches!(b("git status"), Allow(_)));
for bad in [
"cargo test; rm -rf /",
"cargo test && curl x",
"cargo test | sh",
"cargo test $(id)",
"cargo test > /etc/x",
"ls",
"git status -s",
"cargo build --manifest-path=/etc/x/Cargo.toml",
"cargo run ../../x",
"cargo run ~/x",
] {
assert!(matches!(b(bad), Deny(_)), "{bad}");
}
assert!(matches!(
b("cargo build --manifest-path=sub/Cargo.toml"),
Allow(_)
));
// hard rules hold even for unrestricted bash
let free = pol(&["bash"]);
let f = |c: &str| free.decide("bash", &json!({"command": c}));
assert!(matches!(f("make && ls"), Allow(_)));
for bad in [
"git push origin main",
"cd x; git -C y push",
"/usr/bin/git push",
"cat .env",
"cat ~/.ssh/id_rsa",
] {
assert!(matches!(f(bad), Deny(_)), "{bad}");
}
}
}