O5: safety - allowlist guard, credential separation, audit log (#13)
This commit was merged in pull request #13.
This commit is contained in:
1 parent
06662a085f
commit
bea07e82bb
9 files changed
+890
-29
No files matched your search
+36
@@ -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<usize>,
|
||||
},
|
||||
/// 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<String> },
|
||||
/// List runs, or show one.
|
||||
Status { id: Option<String> },
|
||||
/// Print the raw log (hx events, stderr, gate output) of a run.
|
||||
@@ -136,6 +142,21 @@ fn main() -> Result<std::process::ExitCode> {
|
||||
});
|
||||
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<state::Run> {
|
||||
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,
|
||||
|
||||
+497
@@ -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<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();
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<String>>,
|
||||
/// Extra directories the agent may read besides the worktree.
|
||||
#[serde(default)]
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
/// 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<String>,
|
||||
/// 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<Self> {
|
||||
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());
|
||||
|
||||
+108
-1
@@ -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<String>) -> 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<Item = (String, String)>, 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<Option<String>> {
|
||||
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<String> {
|
||||
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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user