From 8361a4411f4cc072de762297e964efe0946daabd Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 13 Nov 2026 00:09:26 +0000 Subject: [PATCH] O5: tool allowlist guard, env isolation, audit log (closes #6) --- docs/safety.md | 38 ++++ src/main.rs | 36 ++++ src/policy.rs | 497 +++++++++++++++++++++++++++++++++++++++++++++++ src/profile.rs | 20 ++ src/run.rs | 109 ++++++++++- tests/all.sh | 2 + tests/e2e.py | 113 ++++++++--- tests/fake_hx.py | 52 +++++ tests/real_hx.py | 52 +++++ 9 files changed, 890 insertions(+), 29 deletions(-) create mode 100644 docs/safety.md create mode 100644 src/policy.rs create mode 100644 tests/fake_hx.py create mode 100644 tests/real_hx.py diff --git a/docs/safety.md b/docs/safety.md new file mode 100644 index 0000000..b876300 --- /dev/null +++ b/docs/safety.md @@ -0,0 +1,38 @@ +# Safety + +hx in `-p` mode never prompts: with no permission hook every tool call is allowed. orch therefore enforces its own +policy and keeps credentials of different profiles apart. + +## Profile keys + +```toml +home = "/work/hxhome" # own HOME => own ~/.hx/auth.json; HX_HOME of orch is NOT passed on +allow = ["read", "write", "edit", "bash:cargo *", "bash:git status"] +read_roots = ["/work/shared-docs"] # extra readable dirs besides the worktree +env = ["GITEA_*"] # orch env vars hx may see (default: PATH HOME USER LOGNAME SHELL TERM LANG LC_* + # TMPDIR CARGO_* RUST* NIX_*, plus HX_HOME only when `home` is unset) +sandbox = true # hx --sandbox (bwrap); required for yolo = true +``` + +## Allowlist (`allow`) + +- Absent: no policy, hx may use every tool (orch prints a warning unless `sandbox = true`). +- `TOOL` allows every call of that tool (`read`, `write`, `edit`, `bash`, `lsp`, ...), `*` allows all. +- `bash:PATTERN`: `*` glob over the whole command. Only simple commands match (no `; & | < > $ ( ) { } \` or + newline); path-like words must resolve inside the worktree or `read_roots`. +- Always denied, even with `*`: `git push` (publishing is the sink's job), credential-looking paths (`.env*`, + `.ssh`, `.aws`, `auth.json`, `*.pem`, `*.key`, ...), file tools outside the worktree (reads may also use + `read_roots`), writes to `.git` and `.hx`. +- A denied call ends the run as `needs-human` with `reason = "policy: ..."`; the branch keeps what was done so far. + +Enforced twice: `orch guard` runs inside hx as an extension (installed as the worktree's `.hx/config.toml`, removed +after each attempt, rewritten before the next) and blocks the call before it executes. orch also checks every +`tool_call` event in the stream and kills the run, because hx treats a dead or slow extension as "continue". + +Limit: plain `bash` (no pattern) is not confined; a shell cannot be parsed reliably. Use `sandbox = true` for that. +A repo that already has its own `.hx/config.toml` is refused (`setup:` failure) so the guard is never silently skipped. + +## Audit log + +`/audit.log`, append-only JSONL: `run_start` (profile, allowlist, sandbox, yolo), one `tool` line per call +(`allow`/`deny`, rule, arguments), `run_end`. `orch audit [RUN_ID]` prints it. diff --git a/src/main.rs b/src/main.rs index f2a8ed4..3ec14e5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ mod adapter; mod lock; +mod policy; mod profile; mod run; mod state; @@ -36,6 +37,11 @@ enum Cmd { #[arg(long)] limit: Option, }, + /// hx extension that enforces a run's tool allowlist (started by hx, not by hand). + #[command(hide = true)] + Guard { policy: PathBuf }, + /// Print the audit log, optionally only one run's lines. + Audit { id: Option }, /// List runs, or show one. Status { id: Option }, /// Print the raw log (hx events, stderr, gate output) of a run. @@ -136,6 +142,21 @@ fn main() -> Result { }); Ok(code(ok.load(Ordering::SeqCst))) } + Cmd::Guard { policy } => { + policy::guard(&policy)?; + Ok(0.into()) + } + Cmd::Audit { id } => { + let log = std::fs::read_to_string(policy::audit_path()).unwrap_or_default(); + let pat = id.map(|i| format!("\"run\":{}", serde_json::json!(i))); + for l in log + .lines() + .filter(|l| pat.as_ref().is_none_or(|p| l.contains(p.as_str()))) + { + println!("{l}"); + } + Ok(0.into()) + } Cmd::Status { id: Some(id) } => { println!("{}", serde_json::to_string_pretty(&state::Run::load(&id)?)?); Ok(0.into()) @@ -176,7 +197,22 @@ fn process( src: Option<&dyn adapter::Source>, ) -> Result { let mut r = run::new_run(t, repo, profile)?; + if p.allow.is_none() && !p.sandbox { + eprintln!( + "warning: profile {profile} has no `allow` list and no sandbox: hx may use every tool" + ); + } + let id = r.id.clone(); + let audit = |ev: &str, d: serde_json::Value| policy::audit(&policy::audit_path(), &id, ev, d); + audit( + "run_start", + serde_json::json!({"profile": profile, "repo": repo, "allow": p.allow, "sandbox": p.sandbox, "yolo": p.yolo, "task": t.id}), + ); run::execute(&mut r, p, t)?; + audit( + "run_end", + serde_json::json!({"status": r.status, "reason": r.reason, "attempts": r.attempts}), + ); if r.status == state::Status::Done { match adapter::sink(p.sink.as_ref()).and_then(|s| s.publish(t, &r)) { Ok(note) => r.published = note, diff --git a/src/policy.rs b/src/policy.rs new file mode 100644 index 0000000..36be6c0 --- /dev/null +++ b/src/policy.rs @@ -0,0 +1,497 @@ +//! 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). +//! 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, + /// Canonical path of the run's worktree. + pub worktree: PathBuf, + pub read_roots: Vec, + 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, Vec) = (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 { + 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(); + let ext = toml::to_string(&json!({"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}"); + } + } +} diff --git a/src/profile.rs b/src/profile.rs index 746199b..5a6c8bc 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -34,6 +34,17 @@ pub struct Profile { /// Extra hx attempts after a red gate (default 2). 0 = fail straight to needs-human. #[serde(default = "default_retries")] pub max_retries: u32, + /// Tool allowlist, see policy.rs. Absent = no policy (hx runs headless with every tool allowed). + /// Present = enforced by `orch guard` inside hx and re-checked on the event stream; a denied call ends + /// the run as needs-human. + pub allow: Option>, + /// Extra directories the agent may read besides the worktree. + #[serde(default)] + pub read_roots: Vec, + /// Names (trailing `*` = prefix) of orch's environment variables passed to hx. hx gets a cleared + /// environment plus PATH, HOME, USER, LOGNAME, SHELL, TERM, LANG, LC_*, TMPDIR, CARGO_*, RUST*. + #[serde(default)] + pub env: Vec, /// Parallel runs for `orch pull` (default 1). #[serde(default = "one")] pub workers: u32, @@ -64,6 +75,9 @@ fn default_hx() -> String { impl Profile { pub fn parse(s: &str) -> Result { let p: Profile = toml::from_str(s)?; + for e in p.allow.iter().flatten() { + crate::policy::check_entry(e)?; + } if p.workers == 0 || p.max_concurrent == Some(0) { bail!("workers and max_concurrent must be >= 1"); } @@ -116,6 +130,12 @@ mod tests { ); } + #[test] + fn allowlist_validated() { + assert!(Profile::parse("allow = [\"read\", \"bash:cargo *\"]").is_ok()); + assert!(Profile::parse("allow = [\"read:x\"]").is_err()); + } + #[test] fn rejects_zero_workers() { assert!(Profile::parse("workers = 0").is_err()); diff --git a/src/run.rs b/src/run.rs index 607f9f2..b58df99 100644 --- a/src/run.rs +++ b/src/run.rs @@ -2,6 +2,7 @@ use crate::adapter::Task; use crate::lock; +use crate::policy::{self, Decision, Policy}; use crate::profile::Profile; use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now}; use anyhow::{Context, Result, bail}; @@ -79,6 +80,21 @@ fn fail(r: &mut Run, reason: impl Into) -> Result<()> { r.save() } +/// Environment hx gets: a fixed base plus the profile's `env` patterns. `HX_HOME` only when the profile has no +/// own `home` (otherwise it would point back at another identity). +pub fn hx_env(vars: impl Iterator, p: &Profile) -> Vec<(String, String)> { + const BASE: &[&str] = &[ + "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "LC_*", "TMPDIR", "CARGO_*", + "RUST*", "NIX_*", + ]; + vars.filter(|(k, _)| { + BASE.iter().any(|b| policy::glob(b, k)) + || p.env.iter().any(|b| policy::glob(b, k)) + || (k == "HX_HOME" && p.home.is_none()) + }) + .collect() +} + /// hx surfaces provider rejections as `api 429: ...`; also match the usual wording. fn is_rate_limit(reason: &str) -> bool { let r = reason.to_lowercase(); @@ -144,7 +160,20 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> { r.status = Status::Running; r.save()?; writeln!(log, "\n--- attempt {}", r.attempts)?; - let reason = run_hx(r, p, &prompt, session.as_deref(), &mut log)?; + // rewritten before every attempt: an agent that tampered with it is healed + let pol = match p + .allow + .as_ref() + .map(|a| policy::install(&r.id, &r.worktree, a, &p.read_roots)) + { + Some(Err(e)) => return fail(r, format!("setup: {e:#}")), + Some(Ok(pol)) => Some(pol), + None => None, + }; + let reason = run_hx(r, p, &prompt, session.as_deref(), pol.as_ref(), &mut log)?; + if pol.is_some() { + policy::uninstall(&r.worktree); + } if !git(&r.worktree, &["status", "--porcelain"])? .trim() .is_empty() @@ -158,6 +187,13 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> { lock::pause(&account, until)?; // every full window pauses the account, even after a clean run } if let Some(reason) = reason { + if reason.starts_with("policy:") { + // the agent wanted something the profile does not allow: a human decides + r.status = Status::NeedsHuman; + r.reason = Some(reason); + r.ended = Some(now()); + return r.save(); + } if r.quota_until.is_some() || is_rate_limit(&reason) { // provider said no: not the task's fault. Pause the account and hand the task back. lock::pause(&account, r.quota_until.unwrap_or(now() + 900))?; @@ -204,6 +240,7 @@ fn run_hx( p: &Profile, body: &str, session: Option<&str>, + pol: Option<&Policy>, log: &mut std::fs::File, ) -> Result> { let mut parts = p.hx.split_whitespace(); @@ -221,6 +258,8 @@ fn run_hx( if let Some(prov) = &p.provider { cmd.args(["--provider", prov]); } + // cleared environment: orch's own secrets and another profile's HX_HOME never reach the agent + cmd.env_clear().envs(hx_env(std::env::vars(), p)); if let Some(h) = &p.home { cmd.env("HOME", h); } @@ -264,6 +303,29 @@ fn run_hx( killed = Some("budget:turns".to_string()); } } + Some("tool_call") if pol.is_some() => { + // second line of defence: hx treats a dead or slow guard as "continue" + let name = ev["name"].as_str().unwrap_or_default(); + if let Decision::Deny(why) = pol.unwrap().decide(name, &ev["args"]) { + // the guard may not have logged yet (we read the event first): log it here too + policy::audit( + &policy::audit_path(), + &r.id, + "tool", + serde_json::json!({"tool": name, "decision": "deny", "why": why, "args": ev["args"], "by": "orch"}), + ); + killed = Some(format!("policy: {why}")); + } + } + Some("tool_result") + if pol.is_some() + && ev["is_error"] == true + && ev["content"].to_string().contains(policy::PREFIX) => + { + let c = ev["content"].as_str().unwrap_or_default(); + let why = c.split_once(policy::PREFIX).map_or(c, |(_, w)| w.trim()); + killed = Some(format!("policy: {why}")); + } Some("stream") if ev["event"]["type"] == "quota" => { let full: Vec<&Value> = ev["event"]["windows"] .as_array() @@ -326,3 +388,48 @@ fn run_hx( _ => None, }) } + +#[cfg(test)] +mod env_tests { + use super::*; + + fn vars(names: &[&str]) -> Vec<(String, String)> { + names.iter().map(|n| (n.to_string(), "v".into())).collect() + } + + fn keys(p: &str, names: &[&str]) -> Vec { + let p = Profile::parse(p).unwrap(); + hx_env(vars(names).into_iter(), &p) + .into_iter() + .map(|(k, _)| k) + .collect() + } + + #[test] + fn env_is_filtered() { + let all = [ + "PATH", + "LC_ALL", + "CARGO_HOME", + "AWS_SECRET_ACCESS_KEY", + "GITEA_TOKEN", + "HX_HOME", + "HX_BASE_URL", + "ORCH_STATE_DIR", + ]; + assert_eq!( + keys("", &all), + ["PATH", "LC_ALL", "CARGO_HOME", "HX_HOME"], + "HX_HOME passes without own home" + ); + assert_eq!( + keys("home = \"/h\"", &all), + ["PATH", "LC_ALL", "CARGO_HOME"], + "own home drops HX_HOME" + ); + assert_eq!( + keys("env = [\"HX_BASE_URL\", \"GITEA_*\"]\nhome = \"/h\"", &all), + ["PATH", "LC_ALL", "CARGO_HOME", "GITEA_TOKEN", "HX_BASE_URL"] + ); + } +} diff --git a/tests/all.sh b/tests/all.sh index 1bee427..895f19a 100644 --- a/tests/all.sh +++ b/tests/all.sh @@ -8,3 +8,5 @@ cargo test -q cargo build -q python3 tests/e2e.py python3 spike/check.py + +python3 tests/real_hx.py diff --git a/tests/e2e.py b/tests/e2e.py index 0aeba1c..e37b05c 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """End-to-end test for the orch binary with a fake hx. Run: python3 tests/e2e.py [path/to/orch]""" -import json, os, pathlib, signal, subprocess, sys, tempfile, time +import json, os, pathlib, shutil, signal, subprocess, sys, tempfile, time root = pathlib.Path(__file__).resolve().parent.parent orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch") @@ -12,35 +12,18 @@ subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True) subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"], cwd=repo, check=True) (tmp / "cfg/profiles").mkdir(parents=True) fake = tmp / "fake_hx.py" -fake.write_text(''' -import json, sys, time, os -body = sys.argv[sys.argv.index("-p") + 1] -e = lambda o: print(json.dumps(o), flush=True) -e({"type": "session_start"}) -if "NOJSON" in body: sys.exit(1) -if "HANG" in body: - open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid())) - time.sleep(300) -conc = os.environ.get("CONC") -if "SLEEP=" in body: - if conc: open(conc, "a").write("+") - time.sleep(float(body.split("SLEEP=")[1].split()[0])) - if conc: open(conc, "a").write("-") -if "QUOTA" in body: - e({"type": "stream", "event": {"type": "quota", "windows": [{"label": "5h", "used_pct": 100.0, "resets_at": int(time.time()) + 3600}], "credits": None}}) -for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1): - e({"type": "turn_start"}) - e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) -if "WRITE" in body: open("out.txt", "w").write("x") -if "--session" in sys.argv: - open("retry-prompt.txt", "w").write(body) - if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x") -e({"type": "done", "error": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) -''') +shutil.copy(root / "tests/fake_hx.py", fake) def profile(name, extra=""): - (tmp / f"cfg/profiles/{name}.toml").write_text(f'hx = "{sys.executable} {fake}"\n{extra}') + # test knobs pass through the (otherwise cleared) hx environment; the secrets used by the O5 tests do not + top, _, rest = extra.partition("\n[") if "\n[" in extra else (extra, "", "") + body = f'hx = "{sys.executable} {fake}"\nenv = ["MODE", "CONC", "PIDFILE"]\n{top}' + if "env = [" in extra: # profile brings its own env list: merge + body = body.replace('env = ["MODE", "CONC", "PIDFILE"]\n', "") + top = top.replace("env = [", 'env = ["MODE", "CONC", "PIDFILE", ') + body = f'hx = "{sys.executable} {fake}"\n{top}' + (tmp / f"cfg/profiles/{name}.toml").write_text(body + (f"\n[{rest}" if rest else "")) def task(name, body): @@ -61,7 +44,7 @@ def status(id): def check(p, st, reason=None): id = p.stdout.split()[0] s = status(id) - assert s["status"] == st and (reason is None or (s["reason"] or "").startswith(reason)), (p.stdout, p.stderr, s) + assert s["status"] == st and (reason is None or (s["reason"] or "").startswith(reason)), (p.stdout, p.stderr, s, (tmp / "state/runs" / (id + ".log")).read_text()[-1500:]) return s @@ -211,6 +194,80 @@ assert p.returncode == 0 and p.stdout.count(" done") == 3, p p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True) assert p.stdout.count(" done") == 1 and (qd / "e.md").exists() and "paused" in p.stderr, p +# --- safety (O5) --- +def git_show(branch, path): + return subprocess.run(["git", "show", f"{branch}:{path}"], cwd=repo, capture_output=True, text=True).stdout + +private = tmp / "private/.hx" +private.mkdir(parents=True) +(private / "auth.json").write_text('{"claude": "PRIVATE-TOKEN-123"}') +work_home = tmp / "work-home" +work_home.mkdir() +senv = {"HX_HOME": str(private), "AWS_SECRET_ACCESS_KEY": "AWS-SECRET-456", "GITEA_TOKEN": "TOK"} +profile("sec", f'home = "{work_home}"\nallow = ["read", "write", "bash:cargo test*"]\n') + +# the work profile cannot read the private profile's auth file: the guard blocks the call, the run needs a human +s = check(run("steal", "sec", env=senv, body=f"CALL read {private}/auth.json"), "needs-human", "policy:") +assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt"), "secret reached the agent" +assert "outside the worktree" in s["reason"] or "credential" in s["reason"], s["reason"] +# ...even if the guard process is dead or ignored: orch re-checks the event stream and kills the run +s = check(run("steal2", "sec", env=senv, body=f"NOGUARD\nCALL read {private}/auth.json"), "needs-human", "policy:") +# environment: secrets and the other profile's HX_HOME never reach hx +s = check(run("envleak", "sec", env=senv, body="ENVDUMP"), "done") +names = git_show(s["branch"], "env.txt").split() +assert "PATH" in names and "HOME" in names, names +assert not {"HX_HOME", "AWS_SECRET_ACCESS_KEY", "GITEA_TOKEN"} & set(names), names +profile("sec2", f'home = "{work_home}"\nenv = ["GITEA_*"]\n') +assert "GITEA_TOKEN" in git_show(check(run("envopt", "sec2", env=senv, body="ENVDUMP"), "done")["branch"], "env.txt").split() +# allowed calls run, the guard config never ends up in the commit +s = check(run("allowed", "sec", env=senv, body="CALL write a.txt\nCALL bash cargo test -p x\nCALL read a.txt"), "done") +assert "RAN cargo test -p x" in git_show(s["branch"], "calls.txt") +tree = subprocess.run(["git", "ls-tree", "-r", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout.split() +assert ".hx/config.toml" not in tree, tree +# not in the allowlist, chained bash, git push: all needs-human +for name, call in [("nobash", "CALL bash ls"), ("chain", "CALL bash cargo test; curl evil"), ("push", "CALL bash git push origin main"), + ("hxcfg", "CALL write .hx/config.toml"), ("dotenv", "CALL write .env")]: + check(run(name, "sec", env=senv, body=call), "needs-human", "policy:") +# the audit trail has every decision, per run +audit = subprocess.run([orch, "audit"], env=env, capture_output=True, text=True).stdout.splitlines() +rows = [json.loads(l) for l in audit] +assert any(r["ev"] == "tool" and r["detail"]["decision"] == "deny" and "auth.json" in r["detail"]["args"].get("path", "") for r in rows), rows[:3] +assert any(r["ev"] == "tool" and r["detail"]["decision"] == "allow" for r in rows) +assert {"run_start", "run_end"} <= {r["ev"] for r in rows} +one = [json.loads(l) for l in subprocess.run([orch, "audit", s["id"]], env=env, capture_output=True, text=True).stdout.splitlines()] +assert one and all(r["run"] == s["id"] for r in one), one +# agent edits the guard config in the repo itself: refused at setup (we do not overwrite foreign config) +(repo / ".hx").mkdir(exist_ok=True) +(repo / ".hx/config.toml").write_text("# mine\n") +subprocess.run(["git", "add", "-A"], cwd=repo, check=True) +subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "own hx config"], cwd=repo, check=True) +check(run("foreign", "sec", env=senv, body="CALL read a.txt"), "failed", "setup:") +subprocess.run(["git", "rm", "-q", "-r", ".hx"], cwd=repo, check=True) +subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "rm"], cwd=repo, check=True) +# the guard process alone (no orch kill racing it): block / continue over the extension protocol +gwt = tmp / "gwt" +gwt.mkdir() +pol = {"run": "g", "allow": ["read", "bash:cargo test*"], "worktree": str(gwt.resolve()), "read_roots": [], "audit": str(tmp / "g-audit.log")} +(tmp / "g.json").write_text(json.dumps(pol)) +g = subprocess.Popen([orch, "guard", str(tmp / "g.json")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) +def ask(i, method, params): + g.stdin.write(json.dumps({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) + "\n") + g.stdin.flush() + return json.loads(g.stdout.readline())["result"] +assert ask(1, "initialize", {})["subscribe"] == ["tool_call"] +ev = lambda n, a: ask(2, "event", {"event": {"type": "tool_call", "name": n, "args": a}}) +assert ev("read", {"path": "x.rs"})["action"] == "continue" +b = ev("read", {"path": str(private / "auth.json")}) +assert b["action"] == "block" and b["reason"].startswith("orch-guard:"), b +assert ev("bash", {"command": "cargo test; id"})["action"] == "block" +assert ev("write", {"path": "x.rs"})["action"] == "block" +g.stdin.close() +assert g.wait(timeout=5) == 0 +assert len((tmp / "g-audit.log").read_text().splitlines()) == 4 + +# warning for unrestricted profiles +assert "no `allow` list" in run("warn", "p", body="WRITE").stderr + # kill orch mid-run: status must say interrupted and hx must be dead after the next orch call pidfile = tmp / "hx.pid" p = subprocess.Popen([orch, "run", str(task("killed", "HANG")), "--repo", str(repo), "--profile", "p"], diff --git a/tests/fake_hx.py b/tests/fake_hx.py new file mode 100644 index 0000000..2e84f60 --- /dev/null +++ b/tests/fake_hx.py @@ -0,0 +1,52 @@ +import json, sys, time, os +body = sys.argv[sys.argv.index("-p") + 1] +e = lambda o: print(json.dumps(o), flush=True) +e({"type": "session_start"}) +import subprocess, tomllib +ext = None +def guard(name, args): + """Speak the hx extension protocol to whatever .hx/config.toml configures (like real hx).""" + global ext + if "NOGUARD" in body or not os.path.exists(".hx/config.toml"): return None + if ext is None: + cmd = tomllib.load(open(".hx/config.toml", "rb"))["extensions"][0]["command"] + ext = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + ext.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n"); ext.stdin.flush() + ext.stdout.readline() + ext.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "event", "params": {"event": {"type": "tool_call", "name": name, "args": args}}}) + "\n"); ext.stdin.flush() + return json.loads(ext.stdout.readline())["result"] +for n, l in enumerate(x for x in body.splitlines() if x.startswith("CALL ")): + _, name, arg = l.split(" ", 2) + args = {"command": arg} if name == "bash" else {"path": arg} + e({"type": "tool_call", "id": f"c{n}", "name": name, "args": args}) + r = guard(name, args) + if r and r["action"] == "block": + e({"type": "tool_result", "id": f"c{n}", "name": name, "args": args, "content": "blocked: " + r["reason"], "is_error": True}) + continue + with open("calls.txt", "a") as f: + if name == "read": + try: f.write("READ " + open(arg).read() + "\n") + except OSError as x: f.write("READ-ERR " + str(x) + "\n") + elif name == "write": open(arg, "w").write("x"); f.write("WROTE " + arg + "\n") + else: f.write("RAN " + arg + "\n") + e({"type": "tool_result", "id": f"c{n}", "name": name, "args": args, "content": "ok", "is_error": False}) +if "ENVDUMP" in body: open("env.txt", "w").write("\n".join(sorted(os.environ))) +if "NOJSON" in body: sys.exit(1) +if "HANG" in body: + open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid())) + time.sleep(300) +conc = os.environ.get("CONC") +if "SLEEP=" in body: + if conc: open(conc, "a").write("+") + time.sleep(float(body.split("SLEEP=")[1].split()[0])) + if conc: open(conc, "a").write("-") +if "QUOTA" in body: + e({"type": "stream", "event": {"type": "quota", "windows": [{"label": "5h", "used_pct": 100.0, "resets_at": int(time.time()) + 3600}], "credits": None}}) +for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1): + e({"type": "turn_start"}) + e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) +if "WRITE" in body: open("out.txt", "w").write("x") +if "--session" in sys.argv: + open("retry-prompt.txt", "w").write(body) + if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x") +e({"type": "done", "error": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) diff --git a/tests/real_hx.py b/tests/real_hx.py new file mode 100644 index 0000000..3b2d950 --- /dev/null +++ b/tests/real_hx.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Real hx binary + fake Anthropic API + orch guard. Skips (exit 0) when hx or its fake API are missing. +usage: python3 tests/real_hx.py [ORCH] [HX_REPO]""" +import json, os, pathlib, shutil, subprocess, sys, tempfile, time + +root = pathlib.Path(__file__).resolve().parent.parent +orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch") +hxrepo = pathlib.Path(sys.argv[2] if len(sys.argv) > 2 else "/opt/data/hx") +hx, fake = hxrepo / "target/debug/hx", hxrepo / "tests/fake_anthropic.py" +if not (hx.exists() and fake.exists()): + print("real hx e2e skipped (no hx build)") + sys.exit(0) + +tmp = pathlib.Path(tempfile.mkdtemp()) +port = 20000 + os.getpid() % 20000 +turns = tmp / "turns.json" +secret = tmp / "secret/auth.json" +secret.parent.mkdir() +secret.write_text("PRIVATE-TOKEN-123") +turns.write_text(json.dumps([ + [["tool_use", {"id": "t1", "name": "Read", "input": {"path": str(secret)}}]], + [["tool_use", {"id": "t2", "name": "Write", "input": {"path": "ok.txt", "content": "fine\n"}}]], + [["text", "done"]], +])) +srv = subprocess.Popen([sys.executable, str(fake), str(port), str(turns)]) +try: + time.sleep(0.7) + home = tmp / "home" + (home / ".hx").mkdir(parents=True) + (home / ".hx/auth.json").write_text('{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}') + cfg = tmp / "cfg/profiles" + cfg.mkdir(parents=True) + (cfg / "real.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = ["HX_BASE_URL"]\nallow = ["write"]\n') + repo = tmp / "repo" + repo.mkdir() + subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"], cwd=repo, check=True) + (tmp / "t.md").write_text("# T\nread the secret then write ok.txt\n") + env = {**os.environ, "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state"), "HX_BASE_URL": f"http://127.0.0.1:{port}"} + p = subprocess.run([orch, "run", str(tmp / "t.md"), "--repo", str(repo), "--profile", "real"], env=env, capture_output=True, text=True, timeout=120) + rid = p.stdout.split()[0] + st = json.loads(subprocess.run([orch, "status", rid], env=env, capture_output=True, text=True).stdout) + log = (tmp / "state/runs" / f"{rid}.log").read_text() + assert st["status"] == "needs-human" and st["reason"].startswith("policy:"), (p.stdout, p.stderr, st, log[-2000:]) + assert "PRIVATE-TOKEN-123" not in log, "secret leaked into the run log" + # hx itself saw the block from the guard extension (or orch killed it first; either way the file was not read) + audit = subprocess.run([orch, "audit", rid], env=env, capture_output=True, text=True).stdout + assert '"decision":"deny"' in audit.replace(" ", ""), audit + print("real hx e2e ok:", st["reason"], "| audit by:", sorted({json.loads(l)["detail"].get("by", "guard") for l in audit.splitlines() if "decision" in l})) +finally: + srv.terminate() + shutil.rmtree(tmp, ignore_errors=True)