Allowlist: readonly entry, on_deny = continue, tokens of stopped runs (#20)
This commit was merged in pull request #20.
This commit is contained in:
1 parent
9ce4756fad
commit
39a2e74742
11 files changed
+487
-89
No files matched your search
@@ -30,7 +30,8 @@ gate = "sh tests/all.sh" # exit 0 = pass
|
|||||||
max_retries = 2
|
max_retries = 2
|
||||||
workers = 2
|
workers = 2
|
||||||
account = "work-claude" # profiles on one login share quota pause and max_concurrent
|
account = "work-claude" # profiles on one login share quota pause and max_concurrent
|
||||||
allow = ["read", "write", "edit", "bash:cargo *"]
|
allow = ["read", "write", "edit", "readonly", "bash:cargo *"]
|
||||||
|
on_deny = "continue" # soft denies go back to the agent instead of ending the run
|
||||||
[budget]
|
[budget]
|
||||||
wall_secs = 1800 # per attempt
|
wall_secs = 1800 # per attempt
|
||||||
max_turns = 40 # whole run
|
max_turns = 40 # whole run
|
||||||
|
|||||||
@@ -18,12 +18,23 @@ sandbox = true # hx --sandbox (bwrap); required for yolo = tru
|
|||||||
|
|
||||||
- Absent: no policy, hx may use every tool (orch prints a warning unless `sandbox = true`).
|
- 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.
|
- `TOOL` allows every call of that tool (`read`, `write`, `edit`, `bash`, `lsp`, ...), `*` allows all.
|
||||||
|
- `readonly`: bash commands that only look, one simple command each: `ls cat head tail wc grep rg fd find pwd echo
|
||||||
|
stat file du df which tree diff sort cut nl tr jq basename dirname` and `git status|diff|log|show|blame|ls-files|rev-parse`.
|
||||||
|
Flags that run or write are refused per command (`find -exec/-delete/-fprint*`, `fd -x/--exec`, `rg --pre`,
|
||||||
|
`sort -o/--output`, `tree -o`, `git --output/--ext-diff/--textconv`), and so are `git -C`, other git subcommands and
|
||||||
|
anything outside the worktree. Typical profile: `allow = ["read", "write", "edit", "readonly", "Grep", "Glob", "LS",
|
||||||
|
"bash:cargo *"]`. In `claude_cli` mode Claude's other tools arrive under Claude's own names and need their own entry.
|
||||||
- `bash:PATTERN`: `*` glob over the whole command. Only simple commands match (no `; & | < > $ ( ) { } \` or
|
- `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`.
|
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*`,
|
- 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
|
`.ssh`, `.aws`, `auth.json`, `*.pem`, `*.key`, ...), file tools outside the worktree (reads may also use
|
||||||
`read_roots`), writes to `.git` and `.hx`.
|
`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.
|
- A denied call ends the run as `needs-human` with `reason = "policy: ..."`; the branch keeps what was done so far.
|
||||||
|
- `on_deny = "continue"` (default `"stop"`): a call that is merely **not in the allowlist** is answered to the agent
|
||||||
|
(`orch-guard-soft: ... Use another way`), the tool does not run and the run goes on; the gate decides in the end.
|
||||||
|
**Hard** denies always stop the run: credential-looking paths, paths outside the worktree, `git push`, writes to
|
||||||
|
`.git`/`.hx`. Every deny is audited (`decision: deny`, `hard: true|false`) and counted (`denies` in the run state,
|
||||||
|
telemetry and the `denies` column of `orch report`).
|
||||||
|
|
||||||
Enforced twice: `orch guard` runs inside hx as an extension (installed as the worktree's `.hx/config.toml`, removed
|
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
|
after each attempt, rewritten before the next) and blocks the call before it executes. orch also checks every
|
||||||
|
|||||||
+259
-35
@@ -20,6 +20,8 @@ use std::path::{Component, Path, PathBuf};
|
|||||||
|
|
||||||
pub const MARK: &str = "# orch-guard (generated, do not edit)";
|
pub const MARK: &str = "# orch-guard (generated, do not edit)";
|
||||||
pub const PREFIX: &str = "orch-guard:";
|
pub const PREFIX: &str = "orch-guard:";
|
||||||
|
/// Block reason of a soft deny under `on_deny = "continue"`: the run goes on, orch only counts it.
|
||||||
|
pub const SOFT_PREFIX: &str = "orch-guard-soft:";
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
pub struct Policy {
|
pub struct Policy {
|
||||||
@@ -29,12 +31,27 @@ pub struct Policy {
|
|||||||
pub worktree: PathBuf,
|
pub worktree: PathBuf,
|
||||||
pub read_roots: Vec<PathBuf>,
|
pub read_roots: Vec<PathBuf>,
|
||||||
pub audit: PathBuf,
|
pub audit: PathBuf,
|
||||||
|
/// `on_deny = "continue"`: soft denies are answered to the agent instead of ending the run.
|
||||||
|
#[serde(default)]
|
||||||
|
pub soft_continue: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum Decision {
|
pub enum Decision {
|
||||||
Allow(String),
|
Allow(String),
|
||||||
|
/// Not in the allowlist: with `on_deny = "continue"` the agent gets the reason and works on.
|
||||||
Deny(String),
|
Deny(String),
|
||||||
|
/// Never negotiable: credentials, outside the worktree, `git push`, `.git`/`.hx`. Ends the run.
|
||||||
|
Hard(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Decision {
|
||||||
|
pub fn deny_reason(&self) -> Option<&str> {
|
||||||
|
match self {
|
||||||
|
Decision::Deny(w) | Decision::Hard(w) => Some(w),
|
||||||
|
Decision::Allow(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `*` matches any run of characters (including none); everything else is literal.
|
/// `*` matches any run of characters (including none); everything else is literal.
|
||||||
@@ -126,6 +143,80 @@ fn resolve(base: &Path, p: &str) -> PathBuf {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Allowlist entry `readonly`: bash commands that only look. Spelled out in code instead of glob patterns because
|
||||||
|
/// the dangerous part is the flags (`find -exec`, `rg --pre`, `sort -o`, `fd -x`), which a pattern cannot see.
|
||||||
|
pub const READONLY: &str = "readonly";
|
||||||
|
const READONLY_CMDS: &[&str] = &[
|
||||||
|
"ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "find", "pwd", "echo", "stat", "file",
|
||||||
|
"du", "df", "which", "tree", "diff", "sort", "cut", "nl", "tr", "jq", "basename", "dirname",
|
||||||
|
];
|
||||||
|
const READONLY_GIT: &[&str] = &[
|
||||||
|
"status",
|
||||||
|
"diff",
|
||||||
|
"log",
|
||||||
|
"show",
|
||||||
|
"blame",
|
||||||
|
"ls-files",
|
||||||
|
"rev-parse",
|
||||||
|
];
|
||||||
|
/// Flags that run a program or write a file, per command (`*` = any command).
|
||||||
|
const RUN_OR_WRITE_FLAGS: &[(&str, &[&str])] = &[
|
||||||
|
(
|
||||||
|
"find",
|
||||||
|
&[
|
||||||
|
"-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf",
|
||||||
|
"-fls",
|
||||||
|
],
|
||||||
|
),
|
||||||
|
("fd", &["-x", "-X", "--exec", "--exec-batch"]),
|
||||||
|
("rg", &["--pre", "--pre-glob"]),
|
||||||
|
("sort", &["-o", "--output", "--compress-program"]),
|
||||||
|
("tree", &["-o"]),
|
||||||
|
(
|
||||||
|
"git",
|
||||||
|
&[
|
||||||
|
"--output",
|
||||||
|
"--ext-diff",
|
||||||
|
"--textconv",
|
||||||
|
"-O",
|
||||||
|
"--open-files-in-pager",
|
||||||
|
],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Ok when `cmd` is one simple command from the read-only set without a flag that runs or writes anything.
|
||||||
|
pub fn readonly_cmd(cmd: &str) -> Result<(), String> {
|
||||||
|
if !simple(cmd) {
|
||||||
|
return Err("not a simple command".into());
|
||||||
|
}
|
||||||
|
let words: Vec<&str> = cmd.split_whitespace().collect();
|
||||||
|
let Some(first) = words.first().copied() else {
|
||||||
|
return Err("empty".into());
|
||||||
|
};
|
||||||
|
let ok = if first == "git" {
|
||||||
|
words.get(1).is_some_and(|s| READONLY_GIT.contains(s))
|
||||||
|
} else {
|
||||||
|
READONLY_CMDS.contains(&first)
|
||||||
|
};
|
||||||
|
if !ok {
|
||||||
|
return Err(format!("`{first}` is not a read-only command"));
|
||||||
|
}
|
||||||
|
let bad = RUN_OR_WRITE_FLAGS
|
||||||
|
.iter()
|
||||||
|
.filter(|(c, _)| *c == first)
|
||||||
|
.flat_map(|(_, f)| f.iter());
|
||||||
|
for w in &words[1..] {
|
||||||
|
let flag = w.split_once('=').map_or(*w, |(f, _)| f);
|
||||||
|
if bad
|
||||||
|
.clone()
|
||||||
|
.any(|f| *f == flag || (f.len() > 2 && f.starts_with("--") && flag == *f))
|
||||||
|
{
|
||||||
|
return Err(format!("flag `{flag}` runs or writes"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn simple(cmd: &str) -> bool {
|
fn simple(cmd: &str) -> bool {
|
||||||
!cmd.contains([
|
!cmd.contains([
|
||||||
'\n', ';', '&', '|', '`', '$', '<', '>', '(', ')', '{', '}', '\\',
|
'\n', ';', '&', '|', '`', '$', '<', '>', '(', ')', '{', '}', '\\',
|
||||||
@@ -163,10 +254,10 @@ impl Policy {
|
|||||||
s("command")
|
s("command")
|
||||||
};
|
};
|
||||||
if mentions_git_push(cmd) {
|
if mentions_git_push(cmd) {
|
||||||
return Deny("git push is done by the sink, not the agent".into());
|
return Hard("git push is done by the sink, not the agent".into());
|
||||||
}
|
}
|
||||||
if cmd.split_whitespace().any(secret) {
|
if cmd.split_whitespace().any(secret) {
|
||||||
return Deny("command touches a secret-looking path".into());
|
return Hard("command touches a secret-looking path".into());
|
||||||
}
|
}
|
||||||
let free = self
|
let free = self
|
||||||
.allow
|
.allow
|
||||||
@@ -175,11 +266,18 @@ impl Policy {
|
|||||||
if free {
|
if free {
|
||||||
why = Some("bash".to_string());
|
why = Some("bash".to_string());
|
||||||
} else {
|
} else {
|
||||||
let hit = self.allow.iter().find_map(|a| {
|
let hit = self
|
||||||
let (tl, pat) = a.split_once(':')?;
|
.allow
|
||||||
(tl.eq_ignore_ascii_case("bash") && simple(cmd) && glob(pat, cmd.trim()))
|
.iter()
|
||||||
.then_some(a)
|
.find_map(|a| {
|
||||||
});
|
let (tl, pat) = a.split_once(':')?;
|
||||||
|
(tl.eq_ignore_ascii_case("bash") && simple(cmd) && glob(pat, cmd.trim()))
|
||||||
|
.then(|| a.clone())
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
let on = self.allow.iter().any(|a| a.eq_ignore_ascii_case(READONLY));
|
||||||
|
(on && readonly_cmd(cmd).is_ok()).then(|| READONLY.to_string())
|
||||||
|
});
|
||||||
let Some(hit) = hit else {
|
let Some(hit) = hit else {
|
||||||
return Deny(format!("bash `{}` is not in the allowlist", short(cmd)));
|
return Deny(format!("bash `{}` is not in the allowlist", short(cmd)));
|
||||||
};
|
};
|
||||||
@@ -190,11 +288,11 @@ impl Policy {
|
|||||||
let ok = !w.starts_with('~')
|
let ok = !w.starts_with('~')
|
||||||
&& self.inside(&resolve(&self.worktree, w), &self.roots());
|
&& self.inside(&resolve(&self.worktree, w), &self.roots());
|
||||||
if !ok {
|
if !ok {
|
||||||
return Deny(format!("path `{w}` is outside the worktree"));
|
return Hard(format!("path `{w}` is outside the worktree"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
why = Some(hit.clone());
|
why = Some(hit);
|
||||||
}
|
}
|
||||||
} else if let Some(path) = ["path", "file_path"]
|
} else if let Some(path) = ["path", "file_path"]
|
||||||
.iter()
|
.iter()
|
||||||
@@ -204,21 +302,21 @@ impl Policy {
|
|||||||
let write = matches!(t.as_str(), "write" | "edit");
|
let write = matches!(t.as_str(), "write" | "edit");
|
||||||
let r = resolve(&self.worktree, path);
|
let r = resolve(&self.worktree, path);
|
||||||
if secret(&r.to_string_lossy()) {
|
if secret(&r.to_string_lossy()) {
|
||||||
return Deny(format!("`{path}` looks like a credential file"));
|
return Hard(format!("`{path}` looks like a credential file"));
|
||||||
}
|
}
|
||||||
if write {
|
if write {
|
||||||
let rel = r.strip_prefix(&self.worktree);
|
let rel = r.strip_prefix(&self.worktree);
|
||||||
if rel.is_err() {
|
if rel.is_err() {
|
||||||
return Deny(format!("write outside the worktree: `{path}`"));
|
return Hard(format!("write outside the worktree: `{path}`"));
|
||||||
}
|
}
|
||||||
if rel.is_ok_and(|x| {
|
if rel.is_ok_and(|x| {
|
||||||
x.components()
|
x.components()
|
||||||
.any(|c| matches!(c.as_os_str().to_str(), Some(".git" | ".hx")))
|
.any(|c| matches!(c.as_os_str().to_str(), Some(".git" | ".hx")))
|
||||||
}) {
|
}) {
|
||||||
return Deny(format!("`{path}` is guard/git metadata"));
|
return Hard(format!("`{path}` is guard/git metadata"));
|
||||||
}
|
}
|
||||||
} else if !self.inside(&r, &self.roots()) {
|
} else if !self.inside(&r, &self.roots()) {
|
||||||
return Deny(format!("read outside the worktree: `{path}`"));
|
return Hard(format!("read outside the worktree: `{path}`"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if why.is_none() {
|
if why.is_none() {
|
||||||
@@ -269,7 +367,13 @@ fn policy_path(run: &str) -> PathBuf {
|
|||||||
|
|
||||||
/// Writes the policy and the worktree's `.hx/config.toml` that starts the guard. Rewritten before every
|
/// 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.
|
/// 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> {
|
pub fn install(
|
||||||
|
run: &str,
|
||||||
|
wt: &Path,
|
||||||
|
allow: &[String],
|
||||||
|
read_roots: &[PathBuf],
|
||||||
|
soft_continue: bool,
|
||||||
|
) -> Result<Policy> {
|
||||||
let pol = Policy {
|
let pol = Policy {
|
||||||
run: run.into(),
|
run: run.into(),
|
||||||
allow: allow.to_vec(),
|
allow: allow.to_vec(),
|
||||||
@@ -279,6 +383,7 @@ pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) -
|
|||||||
.map(|r| resolve(Path::new("/"), &r.to_string_lossy()))
|
.map(|r| resolve(Path::new("/"), &r.to_string_lossy()))
|
||||||
.collect(),
|
.collect(),
|
||||||
audit: audit_path(),
|
audit: audit_path(),
|
||||||
|
soft_continue,
|
||||||
};
|
};
|
||||||
let pp = policy_path(run);
|
let pp = policy_path(run);
|
||||||
std::fs::create_dir_all(pp.parent().unwrap())?;
|
std::fs::create_dir_all(pp.parent().unwrap())?;
|
||||||
@@ -328,6 +433,16 @@ pub fn guard(policy_file: &Path) -> Result<()> {
|
|||||||
let (act, why, extra) = match &d {
|
let (act, why, extra) = match &d {
|
||||||
Decision::Allow(w) => ("allow", w.clone(), json!({"action": "continue"})),
|
Decision::Allow(w) => ("allow", w.clone(), json!({"action": "continue"})),
|
||||||
Decision::Deny(w) => (
|
Decision::Deny(w) => (
|
||||||
|
"deny",
|
||||||
|
w.clone(),
|
||||||
|
// soft: the agent reads the reason and picks another way (orch does not kill the run)
|
||||||
|
json!({"action": "block", "reason": if pol.soft_continue {
|
||||||
|
format!("{SOFT_PREFIX} {w}. Use another way (allowed: read-only commands, project tests).")
|
||||||
|
} else {
|
||||||
|
format!("{PREFIX} {w}")
|
||||||
|
}}),
|
||||||
|
),
|
||||||
|
Decision::Hard(w) => (
|
||||||
"deny",
|
"deny",
|
||||||
w.clone(),
|
w.clone(),
|
||||||
json!({"action": "block", "reason": format!("{PREFIX} {w}")}),
|
json!({"action": "block", "reason": format!("{PREFIX} {w}")}),
|
||||||
@@ -337,7 +452,8 @@ pub fn guard(policy_file: &Path) -> Result<()> {
|
|||||||
&pol.audit,
|
&pol.audit,
|
||||||
&pol.run,
|
&pol.run,
|
||||||
"tool",
|
"tool",
|
||||||
json!({"tool": tool, "decision": act, "why": why, "args": e["args"]}),
|
json!({"tool": tool, "decision": act, "why": why, "args": e["args"],
|
||||||
|
"hard": matches!(d, Decision::Hard(_))}),
|
||||||
);
|
);
|
||||||
Ok(extra)
|
Ok(extra)
|
||||||
}
|
}
|
||||||
@@ -358,6 +474,11 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use Decision::*;
|
use Decision::*;
|
||||||
|
|
||||||
|
/// Denied, soft or hard.
|
||||||
|
fn denied(d: Decision) -> bool {
|
||||||
|
d.deny_reason().is_some()
|
||||||
|
}
|
||||||
|
|
||||||
fn pol(allow: &[&str]) -> Policy {
|
fn pol(allow: &[&str]) -> Policy {
|
||||||
let d = std::env::temp_dir().join(format!("orch-pol-{}", std::process::id()));
|
let d = std::env::temp_dir().join(format!("orch-pol-{}", std::process::id()));
|
||||||
std::fs::create_dir_all(d.join("wt/sub")).unwrap();
|
std::fs::create_dir_all(d.join("wt/sub")).unwrap();
|
||||||
@@ -367,6 +488,7 @@ mod tests {
|
|||||||
worktree: d.join("wt").canonicalize().unwrap(),
|
worktree: d.join("wt").canonicalize().unwrap(),
|
||||||
read_roots: vec![],
|
read_roots: vec![],
|
||||||
audit: d.join("audit"),
|
audit: d.join("audit"),
|
||||||
|
soft_continue: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,6 +503,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn entries() {
|
fn entries() {
|
||||||
assert!(check_entry("read").is_ok() && check_entry("bash:cargo *").is_ok());
|
assert!(check_entry("read").is_ok() && check_entry("bash:cargo *").is_ok());
|
||||||
|
assert!(check_entry("readonly").is_ok() && check_entry("readonly:x").is_err());
|
||||||
assert!(
|
assert!(
|
||||||
check_entry("").is_err()
|
check_entry("").is_err()
|
||||||
&& check_entry("read:x").is_err()
|
&& check_entry("read:x").is_err()
|
||||||
@@ -400,13 +523,10 @@ mod tests {
|
|||||||
Allow(_)
|
Allow(_)
|
||||||
));
|
));
|
||||||
assert!(
|
assert!(
|
||||||
matches!(p.decide("write", &json!({"path": "a.rs"})), Deny(_)),
|
denied(p.decide("write", &json!({"path": "a.rs"}))),
|
||||||
"not in allowlist"
|
"not in allowlist"
|
||||||
);
|
);
|
||||||
assert!(matches!(
|
assert!(denied(p.decide("bash", &json!({"command": "ls"}))));
|
||||||
p.decide("bash", &json!({"command": "ls"})),
|
|
||||||
Deny(_)
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
pol(&["*"]).decide("anything", &json!({})),
|
pol(&["*"]).decide("anything", &json!({})),
|
||||||
Allow(_)
|
Allow(_)
|
||||||
@@ -424,10 +544,7 @@ mod tests {
|
|||||||
".env",
|
".env",
|
||||||
"sub/auth.json",
|
"sub/auth.json",
|
||||||
] {
|
] {
|
||||||
assert!(
|
assert!(denied(p.decide("write", &json!({"path": bad}))), "{bad}");
|
||||||
matches!(p.decide("write", &json!({"path": bad})), Deny(_)),
|
|
||||||
"{bad}"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
for bad in [
|
for bad in [
|
||||||
"/etc/passwd",
|
"/etc/passwd",
|
||||||
@@ -435,20 +552,14 @@ mod tests {
|
|||||||
"/home/other/.hx/auth.json",
|
"/home/other/.hx/auth.json",
|
||||||
".ssh/id_rsa",
|
".ssh/id_rsa",
|
||||||
] {
|
] {
|
||||||
assert!(
|
assert!(denied(p.decide("read", &json!({"path": bad}))), "{bad}");
|
||||||
matches!(p.decide("read", &json!({"path": bad})), Deny(_)),
|
|
||||||
"{bad}"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
for bad in [
|
for bad in [
|
||||||
".git/hooks/pre-commit",
|
".git/hooks/pre-commit",
|
||||||
".hx/config.toml",
|
".hx/config.toml",
|
||||||
"sub/../.hx/config.toml",
|
"sub/../.hx/config.toml",
|
||||||
] {
|
] {
|
||||||
assert!(
|
assert!(denied(p.decide("edit", &json!({"path": bad}))), "{bad}");
|
||||||
matches!(p.decide("edit", &json!({"path": bad})), Deny(_)),
|
|
||||||
"{bad}"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
p.decide("read", &json!({"path": format!("{w}/a")})),
|
p.decide("read", &json!({"path": format!("{w}/a")})),
|
||||||
@@ -456,10 +567,123 @@ mod tests {
|
|||||||
));
|
));
|
||||||
// symlink out of the worktree is resolved
|
// symlink out of the worktree is resolved
|
||||||
std::os::unix::fs::symlink("/etc", p.worktree.join("lnk")).ok();
|
std::os::unix::fs::symlink("/etc", p.worktree.join("lnk")).ok();
|
||||||
|
assert!(denied(p.decide("read", &json!({"path": "lnk/passwd"}))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hard_and_soft_denies() {
|
||||||
|
let p = pol(&["read", "bash:cargo *"]);
|
||||||
|
let d = |t: &str, a: Value| p.decide(t, &a);
|
||||||
|
// soft: simply not allowed, the agent may try something else
|
||||||
|
assert!(matches!(d("bash", json!({"command": "ls"})), Deny(_)));
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
p.decide("read", &json!({"path": "lnk/passwd"})),
|
d("bash", json!({"command": "python3 -c 'print(1)'"})),
|
||||||
Deny(_)
|
Deny(_)
|
||||||
));
|
));
|
||||||
|
assert!(matches!(d("write", json!({"path": "a.rs"})), Deny(_)));
|
||||||
|
assert!(matches!(d("Foo", json!({})), Deny(_)));
|
||||||
|
// hard: never negotiable
|
||||||
|
assert!(matches!(d("read", json!({"path": ".env"})), Hard(_)));
|
||||||
|
assert!(matches!(d("read", json!({"path": "/etc/passwd"})), Hard(_)));
|
||||||
|
assert!(matches!(
|
||||||
|
d("bash", json!({"command": "git push origin main"})),
|
||||||
|
Hard(_)
|
||||||
|
));
|
||||||
|
assert!(matches!(d("bash", json!({"command": "cat .env"})), Hard(_)));
|
||||||
|
assert!(matches!(
|
||||||
|
d("bash", json!({"command": "cargo run ../../x"})),
|
||||||
|
Hard(_)
|
||||||
|
));
|
||||||
|
let w = pol(&["*"]);
|
||||||
|
assert!(matches!(
|
||||||
|
w.decide("edit", &json!({"path": ".hx/config.toml"})),
|
||||||
|
Hard(_)
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
w.decide("write", &json!({"path": "../x"})),
|
||||||
|
Hard(_)
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
Deny("x".into()).deny_reason().is_some() && Allow("x".into()).deny_reason().is_none()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn readonly_entry() {
|
||||||
|
let p = pol(&["readonly", "read"]);
|
||||||
|
let b = |c: &str| p.decide("bash", &json!({"command": c}));
|
||||||
|
for ok in [
|
||||||
|
"ls",
|
||||||
|
"ls -la sub",
|
||||||
|
"cat a.rs",
|
||||||
|
"rg -n -w compute --hidden -g '!.git' -g '!.hx'",
|
||||||
|
"rg -n \"Instal\" README.md",
|
||||||
|
"fd -e rs",
|
||||||
|
"find . -name '*.rs'",
|
||||||
|
"git status",
|
||||||
|
"git diff --stat",
|
||||||
|
"git log --oneline -5",
|
||||||
|
"head -n 5 a.txt",
|
||||||
|
"grep -rn foo .",
|
||||||
|
"wc -l a.rs",
|
||||||
|
"diff a b",
|
||||||
|
"sort a.txt",
|
||||||
|
"jq . a.json",
|
||||||
|
"tree -L 2",
|
||||||
|
] {
|
||||||
|
assert!(matches!(b(ok), Allow(w) if w == "readonly"), "{ok}");
|
||||||
|
}
|
||||||
|
for bad in [
|
||||||
|
"find . -exec rm {} +",
|
||||||
|
"find . -delete",
|
||||||
|
"find . -fprint x",
|
||||||
|
"fd -x rm",
|
||||||
|
"fd --exec rm",
|
||||||
|
"rg --pre ./x foo",
|
||||||
|
"rg --pre=./x foo",
|
||||||
|
"sort -o out a",
|
||||||
|
"sort --output=out a",
|
||||||
|
"tree -o out",
|
||||||
|
"git push",
|
||||||
|
"git commit -m x",
|
||||||
|
"git branch -D x",
|
||||||
|
"git diff --output=x",
|
||||||
|
"git -C .. status",
|
||||||
|
"git diff --ext-diff",
|
||||||
|
"rm a",
|
||||||
|
"cp a b",
|
||||||
|
"sed -i s/a/b/ a",
|
||||||
|
"python3 -c 'print(1)'",
|
||||||
|
"python3 test.py",
|
||||||
|
"cargo test",
|
||||||
|
"ls; rm a",
|
||||||
|
"cat a | sh",
|
||||||
|
"echo hi > a",
|
||||||
|
"ls $(id)",
|
||||||
|
"cat .env",
|
||||||
|
"cat ~/.ssh/id_rsa",
|
||||||
|
"cat /etc/passwd",
|
||||||
|
"ls ..",
|
||||||
|
"ls /",
|
||||||
|
"head ../../x",
|
||||||
|
"",
|
||||||
|
" ",
|
||||||
|
] {
|
||||||
|
assert!(denied(b(bad)), "{bad}");
|
||||||
|
}
|
||||||
|
// without the entry the same command is denied; patterns and `readonly` combine
|
||||||
|
assert!(denied(
|
||||||
|
pol(&["read"]).decide("bash", &json!({"command": "ls"}))
|
||||||
|
));
|
||||||
|
let both = pol(&["readonly", "bash:cargo *"]);
|
||||||
|
assert!(
|
||||||
|
matches!(both.decide("bash", &json!({"command": "cargo test"})), Allow(w) if w == "bash:cargo *")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(both.decide("bash", &json!({"command": "ls"})), Allow(w) if w == "readonly")
|
||||||
|
);
|
||||||
|
// readonly does not make write tools available
|
||||||
|
assert!(denied(p.decide("write", &json!({"path": "a"}))));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -479,7 +703,7 @@ mod tests {
|
|||||||
"cargo run ../../x",
|
"cargo run ../../x",
|
||||||
"cargo run ~/x",
|
"cargo run ~/x",
|
||||||
] {
|
] {
|
||||||
assert!(matches!(b(bad), Deny(_)), "{bad}");
|
assert!(denied(b(bad)), "{bad}");
|
||||||
}
|
}
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
b("cargo build --manifest-path=sub/Cargo.toml"),
|
b("cargo build --manifest-path=sub/Cargo.toml"),
|
||||||
@@ -496,7 +720,7 @@ mod tests {
|
|||||||
"cat .env",
|
"cat .env",
|
||||||
"cat ~/.ssh/id_rsa",
|
"cat ~/.ssh/id_rsa",
|
||||||
] {
|
] {
|
||||||
assert!(matches!(f(bad), Deny(_)), "{bad}");
|
assert!(denied(f(bad)), "{bad}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,14 @@ pub struct Budget {
|
|||||||
pub max_tokens: Option<u64>,
|
pub max_tokens: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum OnDeny {
|
||||||
|
#[default]
|
||||||
|
Stop,
|
||||||
|
Continue,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Profile {
|
pub struct Profile {
|
||||||
@@ -38,6 +46,11 @@ pub struct Profile {
|
|||||||
/// Present = enforced by `orch guard` inside hx and re-checked on the event stream; a denied call ends
|
/// Present = enforced by `orch guard` inside hx and re-checked on the event stream; a denied call ends
|
||||||
/// the run as needs-human.
|
/// the run as needs-human.
|
||||||
pub allow: Option<Vec<String>>,
|
pub allow: Option<Vec<String>>,
|
||||||
|
/// What a denied tool call does: `stop` (default) ends the run as needs-human; `continue` answers the agent with
|
||||||
|
/// the reason so it can pick another way. Credentials, paths outside the worktree, `git push` and `.git`/`.hx`
|
||||||
|
/// always stop. Every deny is audited and counted (`denies` in the run and in telemetry).
|
||||||
|
#[serde(default)]
|
||||||
|
pub on_deny: OnDeny,
|
||||||
/// Extra directories the agent may read besides the worktree.
|
/// Extra directories the agent may read besides the worktree.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub read_roots: Vec<PathBuf>,
|
pub read_roots: Vec<PathBuf>,
|
||||||
@@ -135,6 +148,16 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn on_deny_parses() {
|
||||||
|
assert_eq!(Profile::parse("").unwrap().on_deny, OnDeny::Stop);
|
||||||
|
assert_eq!(
|
||||||
|
Profile::parse("on_deny = \"continue\"").unwrap().on_deny,
|
||||||
|
OnDeny::Continue
|
||||||
|
);
|
||||||
|
assert!(Profile::parse("on_deny = \"ignore\"").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn allowlist_validated() {
|
fn allowlist_validated() {
|
||||||
assert!(Profile::parse("allow = [\"read\", \"bash:cargo *\"]").is_ok());
|
assert!(Profile::parse("allow = [\"read\", \"bash:cargo *\"]").is_ok());
|
||||||
|
|||||||
+11
-2
@@ -31,6 +31,9 @@ pub struct Rec {
|
|||||||
pub cache_read_tokens: u64,
|
pub cache_read_tokens: u64,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub cache_write_tokens: u64,
|
pub cache_write_tokens: u64,
|
||||||
|
/// Tool calls the allowlist denied in this run.
|
||||||
|
#[serde(default)]
|
||||||
|
pub denies: u32,
|
||||||
pub seconds: u64,
|
pub seconds: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,6 +118,7 @@ pub fn rec(r: &crate::state::Run, hx_version: &str, mode: &str) -> Rec {
|
|||||||
output_tokens: r.output_tokens,
|
output_tokens: r.output_tokens,
|
||||||
cache_read_tokens: r.cache_read_tokens,
|
cache_read_tokens: r.cache_read_tokens,
|
||||||
cache_write_tokens: r.cache_write_tokens,
|
cache_write_tokens: r.cache_write_tokens,
|
||||||
|
denies: r.denies,
|
||||||
seconds: r
|
seconds: r
|
||||||
.ended
|
.ended
|
||||||
.unwrap_or_else(crate::state::now)
|
.unwrap_or_else(crate::state::now)
|
||||||
@@ -192,6 +196,7 @@ pub struct Agg {
|
|||||||
pub retries: u64,
|
pub retries: u64,
|
||||||
pub tokens: u64,
|
pub tokens: u64,
|
||||||
pub tokens_done: u64,
|
pub tokens_done: u64,
|
||||||
|
pub denies: u64,
|
||||||
pub cache_read: u64,
|
pub cache_read: u64,
|
||||||
pub input_all: u64,
|
pub input_all: u64,
|
||||||
pub secs: Vec<u64>,
|
pub secs: Vec<u64>,
|
||||||
@@ -212,6 +217,7 @@ impl Agg {
|
|||||||
}
|
}
|
||||||
_ => self.failed += 1,
|
_ => self.failed += 1,
|
||||||
}
|
}
|
||||||
|
self.denies += u64::from(r.denies);
|
||||||
self.cache_read += r.cache_read_tokens;
|
self.cache_read += r.cache_read_tokens;
|
||||||
self.input_all += r.input_all();
|
self.input_all += r.input_all();
|
||||||
self.retries += u64::from(r.attempts.saturating_sub(1));
|
self.retries += u64::from(r.attempts.saturating_sub(1));
|
||||||
@@ -259,7 +265,7 @@ fn pct(v: Option<f64>) -> String {
|
|||||||
|
|
||||||
pub fn report(recs: &[Rec]) -> String {
|
pub fn report(recs: &[Rec]) -> String {
|
||||||
let mut out = format!(
|
let mut out = format!(
|
||||||
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n",
|
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6} {:>6}\n",
|
||||||
"profile",
|
"profile",
|
||||||
"hx-version",
|
"hx-version",
|
||||||
"mode",
|
"mode",
|
||||||
@@ -272,11 +278,12 @@ pub fn report(recs: &[Rec]) -> String {
|
|||||||
"tok/run",
|
"tok/run",
|
||||||
"tok/done",
|
"tok/done",
|
||||||
"cache",
|
"cache",
|
||||||
|
"denies",
|
||||||
"med-s"
|
"med-s"
|
||||||
);
|
);
|
||||||
let mut line = |a: &str, b: &str, m: &str, g: &Agg| {
|
let mut line = |a: &str, b: &str, m: &str, g: &Agg| {
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n",
|
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6} {:>6}\n",
|
||||||
a,
|
a,
|
||||||
b,
|
b,
|
||||||
m,
|
m,
|
||||||
@@ -289,6 +296,7 @@ pub fn report(recs: &[Rec]) -> String {
|
|||||||
n(g.tok_per_run()),
|
n(g.tok_per_run()),
|
||||||
n(g.tok_per_done()),
|
n(g.tok_per_done()),
|
||||||
pct(g.cache_pct()),
|
pct(g.cache_pct()),
|
||||||
|
g.denies,
|
||||||
n(g.median_secs())
|
n(g.median_secs())
|
||||||
));
|
));
|
||||||
};
|
};
|
||||||
@@ -483,6 +491,7 @@ mod tests {
|
|||||||
output_tokens: 0,
|
output_tokens: 0,
|
||||||
cache_read_tokens: 0,
|
cache_read_tokens: 0,
|
||||||
cache_write_tokens: 0,
|
cache_write_tokens: 0,
|
||||||
|
denies: 0,
|
||||||
seconds: secs,
|
seconds: secs,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+71
-27
@@ -3,7 +3,7 @@
|
|||||||
use crate::adapter::Task;
|
use crate::adapter::Task;
|
||||||
use crate::lock;
|
use crate::lock;
|
||||||
use crate::policy::{self, Decision, Policy};
|
use crate::policy::{self, Decision, Policy};
|
||||||
use crate::profile::Profile;
|
use crate::profile::{OnDeny, Profile};
|
||||||
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
|
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
|
||||||
use anyhow::{Context, Result, bail};
|
use anyhow::{Context, Result, bail};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
@@ -71,6 +71,7 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
|
|||||||
attempts: 0,
|
attempts: 0,
|
||||||
turns: 0,
|
turns: 0,
|
||||||
spent_tokens: 0,
|
spent_tokens: 0,
|
||||||
|
denies: 0,
|
||||||
published: None,
|
published: None,
|
||||||
quota_until: None,
|
quota_until: None,
|
||||||
})
|
})
|
||||||
@@ -100,16 +101,15 @@ pub fn hx_env(vars: impl Iterator<Item = (String, String)>, p: &Profile) -> Vec<
|
|||||||
|
|
||||||
/// All tokens of one hx usage object. hx reports `input_tokens` as the uncached part only, so cached input
|
/// All tokens of one hx usage object. hx reports `input_tokens` as the uncached part only, so cached input
|
||||||
/// (`cache_read_tokens`, `cache_write_tokens`) has to be added or the count is off by orders of magnitude.
|
/// (`cache_read_tokens`, `cache_write_tokens`) has to be added or the count is off by orders of magnitude.
|
||||||
|
const USAGE_KEYS: [&str; 4] = [
|
||||||
|
"input_tokens",
|
||||||
|
"output_tokens",
|
||||||
|
"cache_read_tokens",
|
||||||
|
"cache_write_tokens",
|
||||||
|
];
|
||||||
|
|
||||||
fn usage_total(u: &Value) -> u64 {
|
fn usage_total(u: &Value) -> u64 {
|
||||||
[
|
USAGE_KEYS.iter().map(|k| u[*k].as_u64().unwrap_or(0)).sum()
|
||||||
"input_tokens",
|
|
||||||
"output_tokens",
|
|
||||||
"cache_read_tokens",
|
|
||||||
"cache_write_tokens",
|
|
||||||
]
|
|
||||||
.iter()
|
|
||||||
.map(|k| u[*k].as_u64().unwrap_or(0))
|
|
||||||
.sum()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The line hx' claude_cli provider writes into the text stream for every tool claude runs: `\n[claude Bash: ls]\n`.
|
/// The line hx' claude_cli provider writes into the text stream for every tool claude runs: `\n[claude Bash: ls]\n`.
|
||||||
@@ -183,11 +183,15 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
|
|||||||
r.save()?;
|
r.save()?;
|
||||||
writeln!(log, "\n--- attempt {}", r.attempts)?;
|
writeln!(log, "\n--- attempt {}", r.attempts)?;
|
||||||
// rewritten before every attempt: an agent that tampered with it is healed
|
// rewritten before every attempt: an agent that tampered with it is healed
|
||||||
let pol = match p
|
let pol = match p.allow.as_ref().map(|a| {
|
||||||
.allow
|
policy::install(
|
||||||
.as_ref()
|
&r.id,
|
||||||
.map(|a| policy::install(&r.id, &r.worktree, a, &p.read_roots))
|
&r.worktree,
|
||||||
{
|
a,
|
||||||
|
&p.read_roots,
|
||||||
|
p.on_deny == OnDeny::Continue,
|
||||||
|
)
|
||||||
|
}) {
|
||||||
Some(Err(e)) => return fail(r, format!("setup: {e:#}")),
|
Some(Err(e)) => return fail(r, format!("setup: {e:#}")),
|
||||||
Some(Ok(pol)) => Some(pol),
|
Some(Ok(pol)) => Some(pol),
|
||||||
None => None,
|
None => None,
|
||||||
@@ -309,9 +313,13 @@ fn run_hx(
|
|||||||
|
|
||||||
let deadline = Instant::now() + Duration::from_secs(p.wall_secs());
|
let deadline = Instant::now() + Duration::from_secs(p.wall_secs());
|
||||||
let mut done = None::<Value>;
|
let mut done = None::<Value>;
|
||||||
|
// usage per component from the stream `done` events of THIS attempt: the final `done` line never comes when
|
||||||
|
// the run is stopped (guard, budget, timeout), and those runs would otherwise report 0 tokens
|
||||||
|
let mut seen = [0u64; 4];
|
||||||
// claude_cli: claude runs the tools; hx prints a `[claude TOOL: ...]` line per tool use and (hx#182) reports
|
// claude_cli: claude runs the tools; hx prints a `[claude TOOL: ...]` line per tool use and (hx#182) reports
|
||||||
// each one as a tool_call event so the guard can decide. Fewer events than lines = something ran unseen.
|
// each one as a tool_call event so the guard can decide. Fewer events than lines = something ran unseen.
|
||||||
let (mut claude_lines, mut calls) = (0u32, 0u32);
|
let (mut claude_lines, mut calls) = (0u32, 0u32);
|
||||||
|
let mut seen_ids = std::collections::HashSet::<String>::new();
|
||||||
let mut killed = None;
|
let mut killed = None;
|
||||||
loop {
|
loop {
|
||||||
let left = deadline.saturating_duration_since(Instant::now());
|
let left = deadline.saturating_duration_since(Instant::now());
|
||||||
@@ -339,27 +347,54 @@ fn run_hx(
|
|||||||
}
|
}
|
||||||
Some("tool_call") if pol.is_some() => {
|
Some("tool_call") if pol.is_some() => {
|
||||||
calls += 1;
|
calls += 1;
|
||||||
|
seen_ids.insert(ev["id"].as_str().unwrap_or_default().to_string());
|
||||||
// second line of defence: hx treats a dead or slow guard as "continue"
|
// second line of defence: hx treats a dead or slow guard as "continue"
|
||||||
let name = ev["name"].as_str().unwrap_or_default();
|
let name = ev["name"].as_str().unwrap_or_default();
|
||||||
if let Decision::Deny(why) = pol.unwrap().decide(name, &ev["args"]) {
|
let d = pol.unwrap().decide(name, &ev["args"]);
|
||||||
// the guard may not have logged yet (we read the event first): log it here too
|
// soft denies under on_deny=continue are answered by the guard (the tool never runs);
|
||||||
policy::audit(
|
// everything else is a reason to stop the run
|
||||||
&policy::audit_path(),
|
let stop = match &d {
|
||||||
&r.id,
|
Decision::Hard(_) => true,
|
||||||
"tool",
|
Decision::Deny(_) => p.on_deny == OnDeny::Stop,
|
||||||
serde_json::json!({"tool": name, "decision": "deny", "why": why, "args": ev["args"], "by": "orch"}),
|
Decision::Allow(_) => false,
|
||||||
);
|
};
|
||||||
killed = Some(format!("policy: {why}"));
|
if let Some(why) = d.deny_reason() {
|
||||||
|
r.denies += 1;
|
||||||
|
if stop {
|
||||||
|
// 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")
|
Some("tool_result")
|
||||||
if pol.is_some()
|
if pol.is_some()
|
||||||
&& ev["is_error"] == true
|
&& ev["is_error"] == true
|
||||||
&& ev["content"].to_string().contains(policy::PREFIX) =>
|
&& (ev["content"].to_string().contains(policy::PREFIX)
|
||||||
|
|| ev["content"].to_string().contains(policy::SOFT_PREFIX)) =>
|
||||||
{
|
{
|
||||||
let c = ev["content"].as_str().unwrap_or_default();
|
let c = ev["content"].as_str().unwrap_or_default();
|
||||||
let why = c.split_once(policy::PREFIX).map_or(c, |(_, w)| w.trim());
|
if c.contains(policy::SOFT_PREFIX) {
|
||||||
killed = Some(format!("policy: {why}"));
|
// soft deny answered to the agent (on_deny = continue): the guard saw the call even
|
||||||
|
// though no tool_call line reached this stream; count it, keep the run going
|
||||||
|
if !seen_ids.contains(ev["id"].as_str().unwrap_or_default()) {
|
||||||
|
calls += 1;
|
||||||
|
r.denies += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// hard (or `stop`-mode) deny: counted unless the tool_call event of the same id was
|
||||||
|
// already evaluated by the stream check above
|
||||||
|
if !seen_ids.contains(ev["id"].as_str().unwrap_or_default()) {
|
||||||
|
r.denies += 1;
|
||||||
|
}
|
||||||
|
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" => {
|
Some("stream") if ev["event"]["type"] == "quota" => {
|
||||||
let full: Vec<&Value> = ev["event"]["windows"]
|
let full: Vec<&Value> = ev["event"]["windows"]
|
||||||
@@ -377,6 +412,9 @@ fn run_hx(
|
|||||||
}
|
}
|
||||||
Some("stream") if ev["event"]["type"] == "done" => {
|
Some("stream") if ev["event"]["type"] == "done" => {
|
||||||
let u = &ev["event"]["usage"];
|
let u = &ev["event"]["usage"];
|
||||||
|
for (s, k) in seen.iter_mut().zip(USAGE_KEYS) {
|
||||||
|
*s += u[k].as_u64().unwrap_or(0);
|
||||||
|
}
|
||||||
r.spent_tokens += usage_total(u);
|
r.spent_tokens += usage_total(u);
|
||||||
if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) {
|
if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) {
|
||||||
killed = Some("budget:tokens".to_string());
|
killed = Some("budget:tokens".to_string());
|
||||||
@@ -411,6 +449,12 @@ fn run_hx(
|
|||||||
r.cache_read_tokens = f("cache_read_tokens");
|
r.cache_read_tokens = f("cache_read_tokens");
|
||||||
r.cache_write_tokens = f("cache_write_tokens");
|
r.cache_write_tokens = f("cache_write_tokens");
|
||||||
r.session = d["session"].as_str().map(String::from);
|
r.session = d["session"].as_str().map(String::from);
|
||||||
|
} else {
|
||||||
|
// killed before the final `done`: keep what the stream reported (a lower bound, never less than before)
|
||||||
|
r.input_tokens = r.input_tokens.max(seen[0]);
|
||||||
|
r.output_tokens = r.output_tokens.max(seen[1]);
|
||||||
|
r.cache_read_tokens = r.cache_read_tokens.max(seen[2]);
|
||||||
|
r.cache_write_tokens = r.cache_write_tokens.max(seen[3]);
|
||||||
}
|
}
|
||||||
if let Some(k) = killed {
|
if let Some(k) = killed {
|
||||||
return Ok(Some(k));
|
return Ok(Some(k));
|
||||||
|
|||||||
@@ -68,6 +68,9 @@ pub struct Run {
|
|||||||
pub turns: u64,
|
pub turns: u64,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub spent_tokens: u64,
|
pub spent_tokens: u64,
|
||||||
|
/// Tool calls the policy denied (soft denies that the agent got to answer, plus the one that stopped the run).
|
||||||
|
#[serde(default)]
|
||||||
|
pub denies: u32,
|
||||||
/// Sink result (PR URL, branch note) once published.
|
/// Sink result (PR URL, branch note) once published.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub published: Option<String>,
|
pub published: Option<String>,
|
||||||
@@ -187,6 +190,7 @@ mod tests {
|
|||||||
attempts: 0,
|
attempts: 0,
|
||||||
turns: 0,
|
turns: 0,
|
||||||
spent_tokens: 0,
|
spent_tokens: 0,
|
||||||
|
denies: 0,
|
||||||
published: None,
|
published: None,
|
||||||
quota_until: None,
|
quota_until: None,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -249,6 +249,44 @@ subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-
|
|||||||
check(run("foreign", "sec", env=senv, body="CALL read a.txt"), "failed", "setup:")
|
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", "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)
|
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "rm"], cwd=repo, check=True)
|
||||||
|
# `readonly` entry: looking commands pass through the real guard, running/writing ones do not
|
||||||
|
profile("ro", f'home = "{work_home}"\nallow = ["readonly", "write"]\n')
|
||||||
|
s = check(run("ro-ok", "ro", env=senv, body="CALL bash ls -la\nCALL bash rg -n foo .\nCALL bash git status\nCALL write a.txt"), "done")
|
||||||
|
assert git_show(s["branch"], "calls.txt").count("RAN") == 3
|
||||||
|
for name, call in [("ro-exec", "CALL bash find . -exec rm {} +"), ("ro-rm", "CALL bash rm a.txt"), ("ro-chain", "CALL bash ls; rm a"),
|
||||||
|
("ro-secret", "CALL bash cat .env"), ("ro-out", "CALL bash ls /etc")]:
|
||||||
|
check(run(name, "ro", env=senv, body=call), "needs-human", "policy:")
|
||||||
|
|
||||||
|
# --- on_deny = "continue": soft denies are answered, the run goes on; hard denies still stop it ---
|
||||||
|
profile("soft", f'home = "{work_home}"\nallow = ["readonly", "write"]\non_deny = "continue"\n')
|
||||||
|
# the agent tries a forbidden command, gets the reason, then does the allowed thing
|
||||||
|
s = check(run("soft-ok", "soft", env=senv, body="CALL bash python3 -c 'print(1)'\nCALL bash ls\nCALL write a.txt"), "done")
|
||||||
|
calls = git_show(s["branch"], "calls.txt")
|
||||||
|
assert "RAN ls" in calls and "WROTE a.txt" in calls and "python3" not in calls, calls # the denied call never ran
|
||||||
|
assert s["denies"] == 1, s
|
||||||
|
assert not (tmp / "state/worktrees" / s["id"] / ".hx").exists()
|
||||||
|
# the soft reason reaches the agent and says to use another way
|
||||||
|
rows = [json.loads(l) for l in subprocess.run([orch, "audit", s["id"]], env=env, capture_output=True, text=True).stdout.splitlines()]
|
||||||
|
assert [r["detail"]["decision"] for r in rows if r["ev"] == "tool"] == ["deny", "allow", "allow"], rows
|
||||||
|
assert "orch-guard-soft:" in (tmp / "state/runs" / (s["id"] + ".log")).read_text()
|
||||||
|
# hard denies stop the run even with on_deny = continue
|
||||||
|
s = check(run("soft-hard", "soft", env=senv, body=f"CALL bash python3 -c 'x'\nCALL read {private}/auth.json\nCALL write b.txt"), "needs-human", "policy:")
|
||||||
|
assert s["denies"] == 2 and "WROTE b.txt" not in git_show(s["branch"], "calls.txt"), s # stopped at the credential read
|
||||||
|
assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt")
|
||||||
|
for name, call in [("soft-push", "CALL bash git push origin main"), ("soft-meta", "CALL write .hx/config.toml"), ("soft-out", "CALL bash ls /etc")]:
|
||||||
|
check(run(name, "soft", env=senv, body=call), "needs-human", "policy:")
|
||||||
|
# default stop: the first soft deny ends the run (unchanged)
|
||||||
|
s = check(run("stop-default", "ro", env=senv, body="CALL bash python3 -c 'print(1)'\nCALL write a.txt"), "needs-human", "policy:")
|
||||||
|
assert s["denies"] == 1 and "a.txt" not in git_show(s["branch"], "calls.txt"), s
|
||||||
|
# direct provider only emits the tool_call: soft deny with the stream check alone (NOGUARD) must not kill the run
|
||||||
|
check(run("soft-noguard", "soft", env=senv, body="NOGUARD\nCALL bash python3 -c 'print(1)'\nCALL write a.txt"), "done")
|
||||||
|
|
||||||
|
# --- tokens of a run that is stopped before hx prints its final `done` line are kept ---
|
||||||
|
tel_now = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()]
|
||||||
|
stopped = next(r for r in reversed(tel_now) if r["task"] == "stop-default")
|
||||||
|
assert stopped["status"] == "needs-human" and stopped["input_tokens"] == 100 and stopped["cache_read_tokens"] == 1000, stopped
|
||||||
|
assert stopped["denies"] == 1, stopped
|
||||||
|
|
||||||
# the guard process alone (no orch kill racing it): block / continue over the extension protocol
|
# the guard process alone (no orch kill racing it): block / continue over the extension protocol
|
||||||
gwt = tmp / "gwt"
|
gwt = tmp / "gwt"
|
||||||
gwt.mkdir()
|
gwt.mkdir()
|
||||||
|
|||||||
+45
-23
@@ -10,37 +10,59 @@ if "--version" in sys.argv:
|
|||||||
open(os.environ.get("FAKE_CLAUDE_LOG", "/dev/null"), "a").write(json.dumps(sys.argv[1:]) + "\n")
|
open(os.environ.get("FAKE_CLAUDE_LOG", "/dev/null"), "a").write(json.dumps(sys.argv[1:]) + "\n")
|
||||||
out = lambda o: print(json.dumps(o), flush=True)
|
out = lambda o: print(json.dumps(o), flush=True)
|
||||||
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
||||||
if os.environ.get("FAKE_CLAUDE_READ"):
|
import subprocess
|
||||||
# like claude with --permission-prompt-tool: ask hx first, run the tool only when allowed
|
|
||||||
import subprocess
|
_bridge = {}
|
||||||
target = os.environ["FAKE_CLAUDE_READ"]
|
|
||||||
answer = {"behavior": "allow"}
|
|
||||||
if "--permission-prompt-tool" in sys.argv and not os.environ.get("FAKE_CLAUDE_NOASK"):
|
def ask(tool, inp, tid):
|
||||||
|
"""Ask hx whether `tool` may run (like claude with --permission-prompt-tool); returns the answer dict."""
|
||||||
|
if "--permission-prompt-tool" not in sys.argv or os.environ.get("FAKE_CLAUDE_NOASK"):
|
||||||
|
return {"behavior": "allow"}
|
||||||
|
if not _bridge:
|
||||||
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
||||||
pr = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,
|
_bridge["p"] = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||||
env={**os.environ, **cfg["env"]})
|
text=True, env={**os.environ, **cfg["env"]})
|
||||||
|
_bridge["n"] = 0
|
||||||
|
send("initialize", {})
|
||||||
|
_bridge["p"].stdout.readline()
|
||||||
|
send("tools/call", {"name": "approve", "arguments": {"tool_name": tool, "input": inp, "tool_use_id": tid}})
|
||||||
|
return json.loads(json.loads(_bridge["p"].stdout.readline())["result"]["content"][0]["text"])
|
||||||
|
|
||||||
def rpc(i, m, p):
|
|
||||||
pr.stdin.write(json.dumps({"jsonrpc": "2.0", "id": i, "method": m, "params": p}) + "\n")
|
|
||||||
pr.stdin.flush() # (a lambda `write(..) or flush()` never reaches flush: write returns a truthy count)
|
|
||||||
|
|
||||||
rpc(1, "initialize", {})
|
def send(method, params):
|
||||||
pr.stdout.readline()
|
_bridge["n"] = _bridge.get("n", 0) + 1
|
||||||
rpc(2, "tools/call", {"name": "approve", "arguments": {"tool_name": "Read", "input": {"file_path": target}, "tool_use_id": "t1"}})
|
_bridge["p"].stdin.write(json.dumps({"jsonrpc": "2.0", "id": _bridge["n"], "method": method, "params": params}) + "\n")
|
||||||
answer = json.loads(json.loads(pr.stdout.readline())["result"]["content"][0]["text"])
|
_bridge["p"].stdin.flush() # (a lambda `write(..) or flush()` never reaches flush: write returns a truthy count)
|
||||||
pr.stdin.close()
|
|
||||||
out({"type": "assistant", "session_id": "S1", "message": {"content": [
|
|
||||||
{"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": target}}]}})
|
def tool(tid, name, inp, run):
|
||||||
|
"""One tool use: ask, announce, run only when allowed, report the result."""
|
||||||
|
answer = ask(name, inp, tid)
|
||||||
|
out({"type": "assistant", "session_id": "S1", "message": {"content": [{"type": "tool_use", "id": tid, "name": name, "input": inp}]}})
|
||||||
if answer["behavior"] == "allow":
|
if answer["behavior"] == "allow":
|
||||||
|
res, err = run(), False
|
||||||
|
else:
|
||||||
|
res, err = "deny: " + answer.get("message", ""), True
|
||||||
|
out({"type": "user", "session_id": "S1", "message": {"content": [
|
||||||
|
{"type": "tool_result", "tool_use_id": tid, "content": res, "is_error": err}]}})
|
||||||
|
return not err
|
||||||
|
|
||||||
|
|
||||||
|
if os.environ.get("FAKE_CLAUDE_BASH"): # first a Bash call (may be denied softly), then a Read of $FAKE_CLAUDE_READ
|
||||||
|
cmd = os.environ["FAKE_CLAUDE_BASH"]
|
||||||
|
tool("b1", "Bash", {"command": cmd}, lambda: subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout)
|
||||||
|
elif os.environ.get("FAKE_CLAUDE_READ"):
|
||||||
|
target = os.environ["FAKE_CLAUDE_READ"]
|
||||||
|
|
||||||
|
def read():
|
||||||
try:
|
try:
|
||||||
seen = open(target).read()
|
seen = open(target).read()
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
seen = "ERR " + str(e)
|
seen = "ERR " + str(e)
|
||||||
open("claude-read.txt", "w").write(seen)
|
open("claude-read.txt", "w").write(seen)
|
||||||
res, err = seen, False
|
return seen
|
||||||
else:
|
|
||||||
res, err = "deny: " + answer.get("message", ""), True
|
tool("t1", "Read", {"file_path": target}, read)
|
||||||
out({"type": "user", "session_id": "S1", "message": {"content": [
|
|
||||||
{"type": "tool_result", "tool_use_id": "t1", "content": res, "is_error": err}]}})
|
|
||||||
out({"type": "stream_event", "session_id": "S1", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "done"}}})
|
out({"type": "stream_event", "session_id": "S1", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "done"}}})
|
||||||
out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}})
|
out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}})
|
||||||
@@ -18,6 +18,9 @@ def guard(name, args):
|
|||||||
ext.stdout.readline()
|
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()
|
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"]
|
return json.loads(ext.stdout.readline())["result"]
|
||||||
|
if "CALL " in body: # a model turn that ends in tool calls is one request: its usage is streamed right away
|
||||||
|
e({"type": "turn_start"})
|
||||||
|
e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50, "cache_read_tokens": 1000, "cache_write_tokens": 10}}})
|
||||||
for n, l in enumerate(x for x in body.splitlines() if x.startswith("CALL ")):
|
for n, l in enumerate(x for x in body.splitlines() if x.startswith("CALL ")):
|
||||||
_, name, arg = l.split(" ", 2)
|
_, name, arg = l.split(" ", 2)
|
||||||
args = {"command": arg} if name == "bash" else {"path": arg}
|
args = {"command": arg} if name == "bash" else {"path": arg}
|
||||||
|
|||||||
+20
-1
@@ -55,7 +55,7 @@ try:
|
|||||||
shutil.copy(root / "tests/fake_claude.py", tmp / "claude")
|
shutil.copy(root / "tests/fake_claude.py", tmp / "claude")
|
||||||
os.chmod(tmp / "claude", 0o755)
|
os.chmod(tmp / "claude", 0o755)
|
||||||
(home / ".hx/config.toml").write_text("claude_cli = []\n") # the profile's own home turns the provider on
|
(home / ".hx/config.toml").write_text("claude_cli = []\n") # the profile's own home turns the provider on
|
||||||
cenv = '["HX_BASE_URL", "HX_CLAUDE_BIN", "FAKE_CLAUDE_READ", "FAKE_CLAUDE_LOG", "FAKE_CLAUDE_NOASK"]'
|
cenv = '["HX_BASE_URL", "HX_CLAUDE_BIN", "FAKE_CLAUDE_READ", "FAKE_CLAUDE_LOG", "FAKE_CLAUDE_NOASK", "FAKE_CLAUDE_BASH"]'
|
||||||
(cfg / "guarded.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["write"]\n')
|
(cfg / "guarded.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["write"]\n')
|
||||||
(cfg / "open.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\n')
|
(cfg / "open.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\n')
|
||||||
cenv_vars = {**env, "HX_CLAUDE_BIN": str(tmp / "claude"), "FAKE_CLAUDE_READ": str(secret), "FAKE_CLAUDE_LOG": str(tmp / "argv.log")}
|
cenv_vars = {**env, "HX_CLAUDE_BIN": str(tmp / "claude"), "FAKE_CLAUDE_READ": str(secret), "FAKE_CLAUDE_LOG": str(tmp / "argv.log")}
|
||||||
@@ -100,6 +100,25 @@ try:
|
|||||||
|
|
||||||
assert dead_run("") == "PRIVATE-TOKEN-123", "control: a dead guard without extensions-only lets the read through"
|
assert dead_run("") == "PRIVATE-TOKEN-123", "control: a dead guard without extensions-only lets the read through"
|
||||||
assert dead_run('permissions = "extensions-only"\n') is None, "extensions-only must deny when the guard is dead"
|
assert dead_run('permissions = "extensions-only"\n') is None, "extensions-only must deny when the guard is dead"
|
||||||
|
# on_deny = "continue" against the real hx bridge: a soft deny is answered to claude (tool does not run) and the run
|
||||||
|
# goes on; the fake claude then asks for a second tool, which is allowed
|
||||||
|
(cfg / "soft.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["read"]\non_deny = "continue"\n')
|
||||||
|
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
|
||||||
|
st, seen, p = go("soft", "soft1")
|
||||||
|
del cenv_vars["FAKE_CLAUDE_BASH"]
|
||||||
|
assert st["status"] == "done" and st["denies"] == 1, (st, p.stdout, p.stderr)
|
||||||
|
# the denied `ls` never ran; the same command is allowed once the profile has `readonly`
|
||||||
|
(cfg / "soft2.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["readonly"]\non_deny = "continue"\n')
|
||||||
|
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
|
||||||
|
st, seen, p = go("soft2", "soft2")
|
||||||
|
del cenv_vars["FAKE_CLAUDE_BASH"]
|
||||||
|
assert st["status"] == "done" and st["denies"] == 0, (st, p.stdout, p.stderr)
|
||||||
|
# default on_deny (stop): the same soft deny ends the run
|
||||||
|
(cfg / "stop.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["read"]\n')
|
||||||
|
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
|
||||||
|
st, seen, p = go("stop", "stop1")
|
||||||
|
del cenv_vars["FAKE_CLAUDE_BASH"]
|
||||||
|
assert st["status"] == "needs-human" and st["reason"].startswith("policy:") and st["denies"] >= 1, (st, p.stdout, p.stderr)
|
||||||
# claude that never asks hx (flags ignored): hx still reports the tool via claude's tool result, so orch's own
|
# claude that never asks hx (flags ignored): hx still reports the tool via claude's tool result, so orch's own
|
||||||
# stream check sees it. The tool ran already (after the fact), but the run is not called clean.
|
# stream check sees it. The tool ran already (after the fact), but the run is not called clean.
|
||||||
cenv_vars["FAKE_CLAUDE_NOASK"] = "1"
|
cenv_vars["FAKE_CLAUDE_NOASK"] = "1"
|
||||||
|
|||||||
Reference in new issue
Block a user