claude_cli guard: extensions-only, bridge test against real hx (closes #17)
This commit is contained in:
1 parent
a76c0ac16f
commit
28ad9934e5
5 files changed
+96
-25
No files matched your search
@@ -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)
|
||||
+30
-7
@@ -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}})
|
||||
+32
-5
@@ -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)
|
||||
Reference in new issue
Block a user