From 80ea84f8f6e60c0096a9239e077bfb93f2721591 Mon Sep 17 00:00:00 2001 From: hermes Date: Sat, 14 Nov 2026 10:22:29 +0000 Subject: [PATCH] accept allow with claude_cli, fail closed when tool calls are unseen --- docs/safety.md | 23 ++++++++++++----------- src/run.rs | 33 ++++++++++++++++++++++++--------- tests/e2e.py | 16 ++++++++-------- tests/fake_claude.py | 3 +++ tests/fake_hx.py | 4 ++++ tests/real_hx.py | 23 +++++------------------ 6 files changed, 56 insertions(+), 46 deletions(-) diff --git a/docs/safety.md b/docs/safety.md index 9ca88ef..33035df 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -34,19 +34,20 @@ A repo that already has its own `.hx/config.toml` is refused (`setup:` failure) ## 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` | -|---|---|---|---| -| `direct` (API provider) | hx | enforced (guard + stream check) | counts model turns | -| `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 | +| mode | who runs the tools | what orch sees | +|---|---|---| +| `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 | 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 -`policy: allow cannot be enforced ...`. orch never runs "guarded" without a guard and never switches providers -silently (the direct Claude provider is not usable on every subscription). Options for such a profile: -no `allow` plus `sandbox = true`, `home`, the cleared environment; or `claude_cli = false` in the profile's hx config -if the direct provider works for you. Planned: make the claude_cli provider guardable in hx (permission bridge on -the event bus, tool events), see the linked hx issue. +`allow` works in both modes **provided hx reports claude's tools as `tool_call` events** (hx#182). orch checks this +on every run: it counts the `[claude ...]` tool lines in the text stream and the `tool_call` events. If claude used +more tools than hx reported, the run ends `needs-human` with `policy: claude used N tool(s) but hx reported M +tool_call event(s) ...`: a profile is never silently unguarded. On an hx without #182 every claude_cli run that +uses a tool therefore fails closed; the tool has already run by then (the check is after the fact), so on such an hx +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` shows it as a column and `orch eval` refuses to compare files with different (or mixed) modes ("NOT COMPARABLE", diff --git a/src/run.rs b/src/run.rs index d2e6a1d..af444e9 100644 --- a/src/run.rs +++ b/src/run.rs @@ -112,7 +112,10 @@ fn usage_total(u: &Value) -> u64 { .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. fn is_rate_limit(reason: &str) -> bool { @@ -171,14 +174,6 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> { return Ok(()); } 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 session: Option = None; loop { @@ -314,6 +309,9 @@ fn run_hx( let deadline = Instant::now() + Duration::from_secs(p.wall_secs()); let mut done = None::; + // 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; loop { let left = deadline.saturating_duration_since(Instant::now()); @@ -330,7 +328,17 @@ fn run_hx( 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() => { + calls += 1; // 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"]) { @@ -407,6 +415,13 @@ fn run_hx( if let Some(k) = killed { 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 { None => Some("hx-failed: no done event".into()), Some(d) if !d["error"].is_null() => Some(format!( diff --git a/tests/e2e.py b/tests/e2e.py index b10783b..5a1b7af 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -279,14 +279,14 @@ fakecl = tmp / "claude" fakecl.write_text("#!/bin/sh\n[ \"$1\" = --version ] && echo fake\nexit 0\n") fakecl.chmod(0o755) 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") -assert s["attempts"] == 0 and s["hx_exit"] is None, s # hx was never started -assert "claude_cli = false" in (tmp / "state/runs" / (s["id"] + ".log")).read_text() -# explicit opt-out in the profile's hx config => direct, allowed again -(work_home / ".hx").mkdir(exist_ok=True) -(work_home / ".hx/config.toml").write_text("claude_cli = false\n") -check(run("optout", "sec", env=cenv, body="CALL write a.txt"), "done") -(work_home / ".hx/config.toml").unlink() +# claude_cli + allow: every tool claude runs must reach the guard as a tool_call (hx#182); fewer = fail closed +s = check(run("cli-seen", "sec", env=cenv, body="CLAUDE\nCALL write a.txt\nCALL bash cargo test -p x"), "done") +s = check(run("cli-deny", "sec", env=cenv, body=f"CLAUDE\nCALL read {private}/auth.json"), "needs-human", "policy:") +assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt") +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") +assert "johannes/hx#182" in s["reason"] or "hx#182" in s["reason"], s +# no claude lines => nothing to cross-check (direct provider): unaffected +check(run("direct-ok", "sec", env=senv, body="CALL write a.txt"), "done") # without `allow` claude_cli runs as before (recorded as claude_cli) profile("noallow", f'home = "{work_home}"\n') check(run("cli-ok", "noallow", env=cenv, body="WRITE"), "done") diff --git a/tests/fake_claude.py b/tests/fake_claude.py index b2a589c..8d6bfef 100644 --- a/tests/fake_claude.py +++ b/tests/fake_claude.py @@ -16,5 +16,8 @@ if target: except OSError as e: open("claude-read.txt", "w").write("ERR " + str(e)) 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": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}}) diff --git a/tests/fake_hx.py b/tests/fake_hx.py index 98ec9dd..5ba686f 100644 --- a/tests/fake_hx.py +++ b/tests/fake_hx.py @@ -21,6 +21,10 @@ def guard(name, args): for n, l in enumerate(x for x in body.splitlines() if x.startswith("CALL ")): _, name, arg = l.split(" ", 2) args = {"command": arg} if name == "bash" else {"path": arg} + 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}) r = guard(name, args) if r and r["action"] == "block": diff --git a/tests/real_hx.py b/tests/real_hx.py index 7686c69..371529f 100644 --- a/tests/real_hx.py +++ b/tests/real_hx.py @@ -74,26 +74,13 @@ try: 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] assert last["provider_mode"] == "claude_cli", last - # with `allow`: refused before hx starts, so the claude binary never runs and the secret stays unread - n_calls = len((tmp / "argv.log").read_text().splitlines()) + # with `allow` on today's hx (no tool events for claude's tools, hx#182): fail closed, never "guarded" st, seen, p = go("guarded", "gd") - assert len((tmp / "argv.log").read_text().splitlines()) == n_calls, "claude binary was started despite allow" - 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 + assert st["status"] == "needs-human" and "could not be enforced" in st["reason"], (st, p.stdout, p.stderr) last = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()][-1] - assert last["provider_mode"] == "direct", last - print("claude_cli mode ok: allow refused with claude_cli, enforced with direct") + assert last["provider_mode"] == "claude_cli", last + # (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: srv.terminate() shutil.rmtree(tmp, ignore_errors=True)