Allowlist with claude_cli: fail closed until hx#182; record provider mode (#18)
This commit was merged in pull request #18.
This commit is contained in:
1 parent
374cf28aed
commit
a76c0ac16f
9 files changed
+259
-14
No files matched your search
+38
-5
@@ -5,7 +5,8 @@ import json, os, pathlib, shutil, signal, subprocess, sys, tempfile, time
|
||||
root = pathlib.Path(__file__).resolve().parent.parent
|
||||
orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch")
|
||||
tmp = pathlib.Path(tempfile.mkdtemp())
|
||||
env = {**os.environ, "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state")}
|
||||
# hermetic provider mode: no `claude` binary, whatever the host has (a host with claude in PATH would be claude_cli)
|
||||
env = {**os.environ, "HX_CLAUDE_BIN": "/nonexistent/claude", "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state")}
|
||||
repo = tmp / "repo"
|
||||
repo.mkdir()
|
||||
subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True)
|
||||
@@ -18,10 +19,10 @@ shutil.copy(root / "tests/fake_hx.py", fake)
|
||||
def profile(name, extra=""):
|
||||
# test knobs pass through the (otherwise cleared) hx environment; the secrets used by the O5 tests do not
|
||||
top, _, rest = extra.partition("\n[") if "\n[" in extra else (extra, "", "")
|
||||
body = f'hx = "{sys.executable} {fake}"\nenv = ["MODE", "CONC", "PIDFILE"]\n{top}'
|
||||
body = f'hx = "{sys.executable} {fake}"\nenv = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN"]\n{top}'
|
||||
if "env = [" in extra: # profile brings its own env list: merge
|
||||
body = body.replace('env = ["MODE", "CONC", "PIDFILE"]\n', "")
|
||||
top = top.replace("env = [", 'env = ["MODE", "CONC", "PIDFILE", ')
|
||||
body = body.replace('env = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN"]\n', "")
|
||||
top = top.replace("env = [", 'env = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN", ')
|
||||
body = f'hx = "{sys.executable} {fake}"\n{top}'
|
||||
(tmp / f"cfg/profiles/{name}.toml").write_text(body + (f"\n[{rest}" if rest else ""))
|
||||
|
||||
@@ -50,6 +51,7 @@ def check(p, st, reason=None):
|
||||
|
||||
profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n')
|
||||
s = check(run("ok", body="WRITE"), "done")
|
||||
ok_id = s["id"]
|
||||
assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s
|
||||
assert (s["cache_read_tokens"], s["cache_write_tokens"]) == (1000, 10), s
|
||||
assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout
|
||||
@@ -268,6 +270,37 @@ g.stdin.close()
|
||||
assert g.wait(timeout=5) == 0
|
||||
assert len((tmp / "g-audit.log").read_text().splitlines()) == 4
|
||||
|
||||
# provider mode is recorded; with `allow` + claude_cli the run is refused instead of running unguarded (#17)
|
||||
s = check(run("direct-mode", "sec", env=senv, body="CALL write a.txt"), "done")
|
||||
tel = tmp / "state/telemetry.jsonl"
|
||||
recs2 = [json.loads(l) for l in tel.read_text().splitlines() if l.strip()]
|
||||
assert [r["provider_mode"] for r in recs2 if r["task"] == "direct-mode"] == ["direct"], recs2[-3:]
|
||||
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
|
||||
# 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")
|
||||
assert [json.loads(l)["provider_mode"] for l in tel.read_text().splitlines() if l.strip()][-1] == "claude_cli"
|
||||
# mode comparison: files from different modes are refused
|
||||
fa, fb = tmp / "ma.jsonl", tmp / "mb.jsonl"
|
||||
base = next(r for r in recs2 if r["task"] == "ok")
|
||||
fa.write_text(json.dumps({**base, "provider_mode": "direct"}) + "\n")
|
||||
fb.write_text(json.dumps({**base, "provider_mode": "claude_cli"}) + "\n")
|
||||
cmp_ = subprocess.run([orch, "eval", str(fa), str(fb)], env=env, capture_output=True, text=True)
|
||||
assert cmp_.returncode == 1 and "NOT COMPARABLE" in cmp_.stdout, cmp_
|
||||
assert subprocess.run([orch, "eval", str(fa), str(fa)], env=env, capture_output=True, text=True).returncode == 0
|
||||
assert "mode" in subprocess.run([orch, "report", str(fb)], env=env, capture_output=True, text=True).stdout.splitlines()[0]
|
||||
|
||||
# warning for unrestricted profiles
|
||||
assert "no `allow` list" in run("warn", "p", body="WRITE").stderr
|
||||
|
||||
@@ -354,6 +387,6 @@ try:
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
logs = subprocess.run([orch, "logs", s["id"]], env=env, capture_output=True, text=True).stdout
|
||||
logs = subprocess.run([orch, "logs", ok_id], env=env, capture_output=True, text=True).stdout
|
||||
assert '"type": "done"' in logs or '"type":"done"' in logs, logs
|
||||
print("e2e ok")
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fake `claude -p` for the claude_cli provider (orch tests). It is the process that "executes tools": it reads the
|
||||
file named in $FAKE_CLAUDE_READ the way the real claude would (directly, no hx involved) and writes what it saw to
|
||||
./claude-read.txt, then answers. Logs argv to $FAKE_CLAUDE_LOG."""
|
||||
import json, os, sys
|
||||
|
||||
if "--version" in sys.argv:
|
||||
print("fake")
|
||||
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"):
|
||||
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}})
|
||||
@@ -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":
|
||||
|
||||
@@ -51,6 +51,36 @@ try:
|
||||
ver = subprocess.run([str(hx), "--version"], capture_output=True, text=True).stdout.strip()
|
||||
assert ver and tel[-1]["hx_version"] == ver and tel[-1]["status"] == "needs-human", (tel, ver)
|
||||
print("real hx e2e ok:", st["reason"], "| audit by:", sorted({json.loads(l)["detail"].get("by", "guard") for l in audit.splitlines() if "decision" in l}))
|
||||
# --- claude_cli mode (issue #17): the claude binary executes tools itself and hx emits no tool_call events ---
|
||||
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"]'
|
||||
(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")}
|
||||
|
||||
def go(profile_name, name):
|
||||
(tmp / f"{name}.md").write_text(f"# {name}\nread the secret\n")
|
||||
p = subprocess.run([orch, "run", str(tmp / f"{name}.md"), "--repo", str(repo), "--profile", profile_name],
|
||||
env=cenv_vars, capture_output=True, text=True, timeout=120)
|
||||
rid = p.stdout.split()[0]
|
||||
st = json.loads(subprocess.run([orch, "status", rid], env=env, capture_output=True, text=True).stdout)
|
||||
seen = subprocess.run(["git", "show", f"{st['branch']}:claude-read.txt"], cwd=repo, capture_output=True, text=True)
|
||||
return st, seen.stdout if seen.returncode == 0 else None, p
|
||||
|
||||
# control: without `allow` the claude binary really runs and reads the secret (proves the test is sensitive)
|
||||
st, seen, p = go("open", "ctl")
|
||||
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"
|
||||
st, seen, p = go("guarded", "gd")
|
||||
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"] == "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)
|
||||
Reference in new issue
Block a user