diff --git a/docs/safety.md b/docs/safety.md index 33035df..0f674c1 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -36,24 +36,31 @@ A repo that already has its own `.hx/config.toml` is refused (`setup:` failure) hx reaches Claude in two ways: -| mode | who runs the tools | what orch sees | +| mode | who runs the tools | how `allow` is enforced | |---|---|---| -| `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 | +| `direct` (API provider) | hx | `orch guard` blocks the `tool_call` before the tool runs; orch re-checks the event stream | +| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary | requires hx with johannes/hx#182: claude asks `mcp__hx__approve` first, hx puts the question on the event bus as `tool_call` (`bash{command}`, `write|edit|read{path}`), `orch guard` blocks it before the tool runs | -`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. +For `claude_cli` orch writes `permissions = "extensions-only"` into the generated worktree config. Then a question +is allowed only while a live `tool_call` extension guards it: if the guard dies or never starts, hx denies (a dead +extension otherwise counts as "continue"). Reads and Bash are asked too (hx passes `--settings permissions.ask`). + +Checks that do not depend on trusting hx or claude: + +- Stream check: orch sees `tool_call` events from claude's tools too and kills the run on a denied one. +- Count check: orch counts the `[claude TOOL: ...]` lines hx prints for every tool claude ran and the `tool_call` + events. Fewer events than lines (hx without #182, or a claude that skips the permission prompt) ends the run + `needs-human`: `policy: claude used N tool(s) but hx reported M tool_call event(s) ...`. This check is after the + fact (the tool already ran); the bridge is what prevents the call. + +`max_turns` counts model turns; in claude_cli mode there is one hx request per run, so it is not a useful limit. 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", exit 1): tokens, turns and tool behaviour differ by an order of magnitude between the modes. -Limit: the mode is derived from config and the `claude` binary, not from hx itself; hx' remembered last provider -(`last.json`) is not read, so set `provider` in profiles you compare. +Limits: the mode is derived from config and the `claude` binary, not from hx itself (hx' remembered last provider +`last.json` is not read, so set `provider` in profiles you compare). hx#182's `--settings` flag is untested against a +real `claude` binary (upstream says so too); tests use a fake claude that asks the bridge like the real one. ## Audit log diff --git a/src/policy.rs b/src/policy.rs index 45e89f7..f554c0a 100644 --- a/src/policy.rs +++ b/src/policy.rs @@ -294,7 +294,10 @@ pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) - } 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": [{ + // `permissions = "extensions-only"` (hx#182): in claude_cli mode a question is allowed only while a LIVE + // `tool_call` extension guards it, so a dead or slow guard denies instead of "continue". hx ignores the value + // for the direct provider's `-p` path, where orch's stream check is the second line of defence. + let ext = toml::to_string(&json!({"permissions": "extensions-only", "extensions": [{ "command": [exe, "guard", pp.to_string_lossy()], "timeout_secs": 10}]}))?; std::fs::write(cfg, format!("{MARK}\n{ext}"))?; Ok(pol) diff --git a/tests/dying_guard.py b/tests/dying_guard.py new file mode 100644 index 0000000..a79c838 --- /dev/null +++ b/tests/dying_guard.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 +"""Extension that starts fine (handshake, subscribes to tool_call) and then dies on the first event: a guard that +crashes mid-run. hx treats this as "continue"; permissions = "extensions-only" must turn it into a deny.""" +import json, sys + +for line in sys.stdin: + m = json.loads(line) + if m["method"] == "initialize": + print(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": {"subscribe": ["tool_call"], "tools": []}}), flush=True) + else: + sys.exit(1) diff --git a/tests/fake_claude.py b/tests/fake_claude.py index 8d6bfef..67e62f5 100644 --- a/tests/fake_claude.py +++ b/tests/fake_claude.py @@ -9,15 +9,38 @@ if "--version" in sys.argv: sys.exit(0) 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) -target = os.environ.get("FAKE_CLAUDE_READ") -if target: - try: - open("claude-read.txt", "w").write(open(target).read()) - 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"): + # like claude with --permission-prompt-tool: ask hx first, run the tool only when allowed + import subprocess + target = os.environ["FAKE_CLAUDE_READ"] + answer = {"behavior": "allow"} + if "--permission-prompt-tool" in sys.argv and not os.environ.get("FAKE_CLAUDE_NOASK"): + 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, + env={**os.environ, **cfg["env"]}) + + 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", {}) + pr.stdout.readline() + rpc(2, "tools/call", {"name": "approve", "arguments": {"tool_name": "Read", "input": {"file_path": target}, "tool_use_id": "t1"}}) + answer = json.loads(json.loads(pr.stdout.readline())["result"]["content"][0]["text"]) + pr.stdin.close() out({"type": "assistant", "session_id": "S1", "message": {"content": [ - {"type": "tool_use", "name": "Read", "input": {"file_path": os.environ["FAKE_CLAUDE_READ"]}}]}}) + {"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": target}}]}}) + if answer["behavior"] == "allow": + try: + seen = open(target).read() + except OSError as e: + seen = "ERR " + str(e) + open("claude-read.txt", "w").write(seen) + res, err = seen, False + else: + res, err = "deny: " + answer.get("message", ""), True + 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": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}}) diff --git a/tests/real_hx.py b/tests/real_hx.py index 371529f..4ea36ba 100644 --- a/tests/real_hx.py +++ b/tests/real_hx.py @@ -55,7 +55,7 @@ try: shutil.copy(root / "tests/fake_claude.py", tmp / "claude") os.chmod(tmp / "claude", 0o755) (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"]' + cenv = '["HX_BASE_URL", "HX_CLAUDE_BIN", "FAKE_CLAUDE_READ", "FAKE_CLAUDE_LOG", "FAKE_CLAUDE_NOASK"]' (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') cenv_vars = {**env, "HX_CLAUDE_BIN": str(tmp / "claude"), "FAKE_CLAUDE_READ": str(secret), "FAKE_CLAUDE_LOG": str(tmp / "argv.log")} @@ -74,13 +74,40 @@ 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` on today's hx (no tool events for claude's tools, hx#182): fail closed, never "guarded" + # with `allow` (hx#182): claude asks hx first, the bridge puts the question on the event bus, `orch guard` blocks + # it BEFORE the tool runs: the fake claude never reads the file st, seen, p = go("guarded", "gd") - assert st["status"] == "needs-human" and "could not be enforced" in st["reason"], (st, p.stdout, p.stderr) + assert st["status"] == "needs-human" and st["reason"].startswith("policy:") and "could not be enforced" not in st["reason"], (st, p.stdout, p.stderr) + assert seen is None, f"secret was read before the guard denied it: {seen!r}" + audit = subprocess.run([orch, "audit", st["id"]], env=env, capture_output=True, text=True).stdout + assert '"decision":"deny"' in audit.replace(" ", ""), audit 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 - # (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)") + # dead guard: an extension that starts and then dies on the first event. hx treats that as "continue", so + # without `permissions = "extensions-only"` the secret is read; with it (what orch writes) hx denies instead. + dead = tmp / "dead" + (dead / "repo/.hx").mkdir(parents=True) + subprocess.run(["git", "init", "-q", "-b", "main"], cwd=dead / "repo", check=True) + denv = {**os.environ, "HOME": str(home), "HX_CLAUDE_BIN": str(tmp / "claude"), "FAKE_CLAUDE_READ": str(secret), "FAKE_CLAUDE_LOG": str(tmp / "argv2.log")} + ext = f'[[extensions]]\ncommand = ["{sys.executable}", "{root / "tests/dying_guard.py"}"]\n' + + def dead_run(prefix): + (dead / "repo/.hx/config.toml").write_text(prefix + ext) + (dead / "repo/claude-read.txt").unlink(missing_ok=True) + subprocess.run([str(hx), "-p", "go", "--mode", "json"], cwd=dead / "repo", env=denv, capture_output=True, text=True, timeout=60) + f = dead / "repo/claude-read.txt" + return f.read_text() if f.exists() else None + + 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" + # 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. + cenv_vars["FAKE_CLAUDE_NOASK"] = "1" + st, seen, p = go("guarded", "gd-noask") + assert st["status"] == "needs-human" and st["reason"].startswith("policy:"), (st, p.stdout, p.stderr) + assert seen is not None and "PRIVATE-TOKEN-123" in seen, "control: without the bridge the read goes through" + del cenv_vars["FAKE_CLAUDE_NOASK"] + print("claude_cli mode ok: guard denies before the tool runs; an unasked tool use is still caught after the fact") finally: srv.terminate() shutil.rmtree(tmp, ignore_errors=True)