accept allow with claude_cli, fail closed when tool calls are unseen
This commit is contained in:
1 parent
2751bcf27b
commit
80ea84f8f6
6 files changed
+56
-46
No files matched your search
+12
-11
@@ -34,19 +34,20 @@ A repo that already has its own `.hx/config.toml` is refused (`setup:` failure)
|
|||||||
|
|
||||||
## Provider modes
|
## Provider modes
|
||||||
|
|
||||||
hx has two ways to reach Claude. They differ in what orch can enforce:
|
hx reaches Claude in two ways:
|
||||||
|
|
||||||
| mode | who runs the tools | `allow` | `max_turns` |
|
| mode | who runs the tools | what orch sees |
|
||||||
|---|---|---|---|
|
|---|---|---|
|
||||||
| `direct` (API provider) | hx | enforced (guard + stream check) | counts model turns |
|
| `direct` (API provider) | hx | every tool as a `tool_call` event |
|
||||||
| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary; hx emits no `tool_call` events and its permission bridge skips reads | cannot be enforced | meaningless: 1 hx request per run |
|
| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary | with johannes/hx#182: every tool as a `tool_call` event, decided by the guard through hx' permission bridge; without it: only a `[claude TOOL: ...]` text line |
|
||||||
|
|
||||||
A profile with `allow` in `claude_cli` mode is **refused** before hx starts: the run ends `needs-human` with
|
`allow` works in both modes **provided hx reports claude's tools as `tool_call` events** (hx#182). orch checks this
|
||||||
`policy: allow cannot be enforced ...`. orch never runs "guarded" without a guard and never switches providers
|
on every run: it counts the `[claude ...]` tool lines in the text stream and the `tool_call` events. If claude used
|
||||||
silently (the direct Claude provider is not usable on every subscription). Options for such a profile:
|
more tools than hx reported, the run ends `needs-human` with `policy: claude used N tool(s) but hx reported M
|
||||||
no `allow` plus `sandbox = true`, `home`, the cleared environment; or `claude_cli = false` in the profile's hx config
|
tool_call event(s) ...`: a profile is never silently unguarded. On an hx without #182 every claude_cli run that
|
||||||
if the direct provider works for you. Planned: make the claude_cli provider guardable in hx (permission bridge on
|
uses a tool therefore fails closed; the tool has already run by then (the check is after the fact), so on such an hx
|
||||||
the event bus, tool events), see the linked hx issue.
|
use no `allow` plus `sandbox = true` for claude_cli profiles.
|
||||||
|
`max_turns` counts model turns; in claude_cli mode there is one hx request per run, so it is not a useful limit there.
|
||||||
|
|
||||||
Telemetry records the mode (`provider_mode`: `claude_cli`, `direct`, `codex`; old lines `unknown`). `orch report`
|
Telemetry records the mode (`provider_mode`: `claude_cli`, `direct`, `codex`; old lines `unknown`). `orch report`
|
||||||
shows it as a column and `orch eval` refuses to compare files with different (or mixed) modes ("NOT COMPARABLE",
|
shows it as a column and `orch eval` refuses to compare files with different (or mixed) modes ("NOT COMPARABLE",
|
||||||
|
|||||||
+24
-9
@@ -112,7 +112,10 @@ fn usage_total(u: &Value) -> u64 {
|
|||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
const REFUSE_CLAUDE_CLI: &str = "`allow` cannot be enforced with hx' claude_cli provider (the claude binary runs its own tools, hx sees no tool calls). Remove `allow` and use `sandbox = true`, or set `claude_cli = false` in the profile's hx config to use the direct provider.";
|
/// The line hx' claude_cli provider writes into the text stream for every tool claude runs: `\n[claude Bash: ls]\n`.
|
||||||
|
fn is_claude_tool_line(t: &str) -> bool {
|
||||||
|
t.starts_with("\n[claude ") && t.ends_with("]\n") && t.len() > 12
|
||||||
|
}
|
||||||
|
|
||||||
/// hx surfaces provider rejections as `api 429: ...`; also match the usual wording.
|
/// hx surfaces provider rejections as `api 429: ...`; also match the usual wording.
|
||||||
fn is_rate_limit(reason: &str) -> bool {
|
fn is_rate_limit(reason: &str) -> bool {
|
||||||
@@ -171,14 +174,6 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let mut log = std::fs::File::create(log_path(&r.id))?;
|
let mut log = std::fs::File::create(log_path(&r.id))?;
|
||||||
if p.allow.is_some() && crate::report::provider_mode(p, &r.worktree) == "claude_cli" {
|
|
||||||
// never run "guarded" without a guard: the claude binary's tools are invisible to hx and orch
|
|
||||||
writeln!(log, "{REFUSE_CLAUDE_CLI}")?;
|
|
||||||
r.status = Status::NeedsHuman;
|
|
||||||
r.reason = Some(format!("policy: {REFUSE_CLAUDE_CLI}"));
|
|
||||||
r.ended = Some(now());
|
|
||||||
return r.save();
|
|
||||||
}
|
|
||||||
let mut prompt = body.clone();
|
let mut prompt = body.clone();
|
||||||
let mut session: Option<String> = None;
|
let mut session: Option<String> = None;
|
||||||
loop {
|
loop {
|
||||||
@@ -314,6 +309,9 @@ 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>;
|
||||||
|
// 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.
|
||||||
|
let (mut claude_lines, mut calls) = (0u32, 0u32);
|
||||||
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());
|
||||||
@@ -330,7 +328,17 @@ fn run_hx(
|
|||||||
killed = Some("budget:turns".to_string());
|
killed = Some("budget:turns".to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Some("stream")
|
||||||
|
if pol.is_some()
|
||||||
|
&& ev["event"]["type"] == "text_delta"
|
||||||
|
&& is_claude_tool_line(
|
||||||
|
ev["event"]["text"].as_str().unwrap_or_default(),
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
claude_lines += 1;
|
||||||
|
}
|
||||||
Some("tool_call") if pol.is_some() => {
|
Some("tool_call") if pol.is_some() => {
|
||||||
|
calls += 1;
|
||||||
// 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"]) {
|
if let Decision::Deny(why) = pol.unwrap().decide(name, &ev["args"]) {
|
||||||
@@ -407,6 +415,13 @@ fn run_hx(
|
|||||||
if let Some(k) = killed {
|
if let Some(k) = killed {
|
||||||
return Ok(Some(k));
|
return Ok(Some(k));
|
||||||
}
|
}
|
||||||
|
if pol.is_some() && calls < claude_lines {
|
||||||
|
// fail closed: never call a run guarded when claude used tools hx did not report to the guard
|
||||||
|
return Ok(Some(format!(
|
||||||
|
"policy: claude used {claude_lines} tool(s) but hx reported {calls} tool_call event(s); the allowlist \
|
||||||
|
could not be enforced for this run (hx without claude_cli tool events, see johannes/hx#182)"
|
||||||
|
)));
|
||||||
|
}
|
||||||
Ok(match &done {
|
Ok(match &done {
|
||||||
None => Some("hx-failed: no done event".into()),
|
None => Some("hx-failed: no done event".into()),
|
||||||
Some(d) if !d["error"].is_null() => Some(format!(
|
Some(d) if !d["error"].is_null() => Some(format!(
|
||||||
|
|||||||
+8
-8
@@ -279,14 +279,14 @@ fakecl = tmp / "claude"
|
|||||||
fakecl.write_text("#!/bin/sh\n[ \"$1\" = --version ] && echo fake\nexit 0\n")
|
fakecl.write_text("#!/bin/sh\n[ \"$1\" = --version ] && echo fake\nexit 0\n")
|
||||||
fakecl.chmod(0o755)
|
fakecl.chmod(0o755)
|
||||||
cenv = {"HX_CLAUDE_BIN": str(fakecl)} # a claude binary exists => hx would pick claude_cli
|
cenv = {"HX_CLAUDE_BIN": str(fakecl)} # a claude binary exists => hx would pick claude_cli
|
||||||
s = check(run("refuse", "sec", env=cenv, body="CALL write a.txt"), "needs-human", "policy: `allow` cannot be enforced")
|
# claude_cli + allow: every tool claude runs must reach the guard as a tool_call (hx#182); fewer = fail closed
|
||||||
assert s["attempts"] == 0 and s["hx_exit"] is None, s # hx was never started
|
s = check(run("cli-seen", "sec", env=cenv, body="CLAUDE\nCALL write a.txt\nCALL bash cargo test -p x"), "done")
|
||||||
assert "claude_cli = false" in (tmp / "state/runs" / (s["id"] + ".log")).read_text()
|
s = check(run("cli-deny", "sec", env=cenv, body=f"CLAUDE\nCALL read {private}/auth.json"), "needs-human", "policy:")
|
||||||
# explicit opt-out in the profile's hx config => direct, allowed again
|
assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt")
|
||||||
(work_home / ".hx").mkdir(exist_ok=True)
|
s = check(run("cli-unseen", "sec", env=cenv, body="CLAUDE UNSEEN\nCALL write a.txt"), "needs-human", "policy: claude used 1 tool(s) but hx reported 0")
|
||||||
(work_home / ".hx/config.toml").write_text("claude_cli = false\n")
|
assert "johannes/hx#182" in s["reason"] or "hx#182" in s["reason"], s
|
||||||
check(run("optout", "sec", env=cenv, body="CALL write a.txt"), "done")
|
# no claude lines => nothing to cross-check (direct provider): unaffected
|
||||||
(work_home / ".hx/config.toml").unlink()
|
check(run("direct-ok", "sec", env=senv, body="CALL write a.txt"), "done")
|
||||||
# without `allow` claude_cli runs as before (recorded as claude_cli)
|
# without `allow` claude_cli runs as before (recorded as claude_cli)
|
||||||
profile("noallow", f'home = "{work_home}"\n')
|
profile("noallow", f'home = "{work_home}"\n')
|
||||||
check(run("cli-ok", "noallow", env=cenv, body="WRITE"), "done")
|
check(run("cli-ok", "noallow", env=cenv, body="WRITE"), "done")
|
||||||
|
|||||||
@@ -16,5 +16,8 @@ if target:
|
|||||||
except OSError as e:
|
except OSError as e:
|
||||||
open("claude-read.txt", "w").write("ERR " + str(e))
|
open("claude-read.txt", "w").write("ERR " + str(e))
|
||||||
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
||||||
|
if os.environ.get("FAKE_CLAUDE_READ"):
|
||||||
|
out({"type": "assistant", "session_id": "S1", "message": {"content": [
|
||||||
|
{"type": "tool_use", "name": "Read", "input": {"file_path": os.environ["FAKE_CLAUDE_READ"]}}]}})
|
||||||
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}})
|
||||||
@@ -21,6 +21,10 @@ def guard(name, args):
|
|||||||
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}
|
||||||
|
if "CLAUDE" in body: # claude_cli: hx prints a text line per tool claude runs
|
||||||
|
e({"type": "stream", "event": {"type": "text_delta", "text": f"\n[claude {name}: {arg}]\n"}})
|
||||||
|
if "UNSEEN" in body: # hx without #182: the line is there, the tool_call event is not
|
||||||
|
continue
|
||||||
e({"type": "tool_call", "id": f"c{n}", "name": name, "args": args})
|
e({"type": "tool_call", "id": f"c{n}", "name": name, "args": args})
|
||||||
r = guard(name, args)
|
r = guard(name, args)
|
||||||
if r and r["action"] == "block":
|
if r and r["action"] == "block":
|
||||||
|
|||||||
+5
-18
@@ -74,26 +74,13 @@ try:
|
|||||||
assert seen == "PRIVATE-TOKEN-123", (seen, p.stdout, p.stderr, st)
|
assert seen == "PRIVATE-TOKEN-123", (seen, p.stdout, p.stderr, st)
|
||||||
last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1]
|
last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1]
|
||||||
assert last["provider_mode"] == "claude_cli", last
|
assert last["provider_mode"] == "claude_cli", last
|
||||||
# with `allow`: refused before hx starts, so the claude binary never runs and the secret stays unread
|
# with `allow` on today's hx (no tool events for claude's tools, hx#182): fail closed, never "guarded"
|
||||||
n_calls = len((tmp / "argv.log").read_text().splitlines())
|
|
||||||
st, seen, p = go("guarded", "gd")
|
st, seen, p = go("guarded", "gd")
|
||||||
assert len((tmp / "argv.log").read_text().splitlines()) == n_calls, "claude binary was started despite allow"
|
assert st["status"] == "needs-human" and "could not be enforced" in st["reason"], (st, p.stdout, p.stderr)
|
||||||
assert seen is None, seen
|
|
||||||
assert st["status"] == "needs-human" and "cannot be enforced" in st["reason"], (st, p.stdout, p.stderr)
|
|
||||||
# the escape hatch: the direct provider in the profile's hx config makes `allow` enforceable again
|
|
||||||
(home / ".hx/config.toml").write_text("claude_cli = false\n")
|
|
||||||
srv2 = subprocess.Popen([sys.executable, str(fake), str(port + 1), str(turns)])
|
|
||||||
time.sleep(0.7)
|
|
||||||
cenv_vars["HX_BASE_URL"] = f"http://127.0.0.1:{port + 1}"
|
|
||||||
try:
|
|
||||||
st, seen, p = go("guarded", "gd2")
|
|
||||||
finally:
|
|
||||||
srv2.terminate()
|
|
||||||
assert st["status"] == "needs-human" and st["reason"].startswith("policy: ") and "cannot be enforced" not in st["reason"], (st, p.stdout)
|
|
||||||
assert seen is None or "PRIVATE-TOKEN-123" not in seen
|
|
||||||
last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1]
|
last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1]
|
||||||
assert last["provider_mode"] == "direct", last
|
assert last["provider_mode"] == "claude_cli", last
|
||||||
print("claude_cli mode ok: allow refused with claude_cli, enforced with direct")
|
# (the fake claude has already read the secret by then: this hx cannot stop it, which is what hx#182 is for)
|
||||||
|
print("claude_cli mode ok: unseen tool use fails closed (hx#182 missing)")
|
||||||
finally:
|
finally:
|
||||||
srv.terminate()
|
srv.terminate()
|
||||||
shutil.rmtree(tmp, ignore_errors=True)
|
shutil.rmtree(tmp, ignore_errors=True)
|
||||||
Reference in new issue
Block a user