Files

133 lines
9.1 KiB
Python

#!/usr/bin/env python3
"""Real hx binary + fake Anthropic API + orch guard. Skips (exit 0) when hx or its fake API are missing.
usage: python3 tests/real_hx.py [ORCH] [HX_REPO]"""
import json, os, pathlib, shutil, 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")
hxrepo = pathlib.Path(sys.argv[2] if len(sys.argv) > 2 else "/opt/data/hx")
hx, fake = hxrepo / "target/debug/hx", hxrepo / "tests/fake_anthropic.py"
if not (hx.exists() and fake.exists()):
print("real hx e2e skipped (no hx build)")
sys.exit(0)
tmp = pathlib.Path(tempfile.mkdtemp())
port = 20000 + os.getpid() % 20000
turns = tmp / "turns.json"
secret = tmp / "secret/auth.json"
secret.parent.mkdir()
secret.write_text("PRIVATE-TOKEN-123")
turns.write_text(json.dumps([
[["tool_use", {"id": "t1", "name": "Read", "input": {"path": str(secret)}}]],
[["tool_use", {"id": "t2", "name": "Write", "input": {"path": "ok.txt", "content": "fine\n"}}]],
[["text", "done"]],
]))
srv = subprocess.Popen([sys.executable, str(fake), str(port), str(turns)])
try:
time.sleep(0.7)
home = tmp / "home"
(home / ".hx").mkdir(parents=True)
(home / ".hx/auth.json").write_text('{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}')
cfg = tmp / "cfg/profiles"
cfg.mkdir(parents=True)
(cfg / "real.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = ["HX_BASE_URL"]\nallow = ["write"]\n')
repo = tmp / "repo"
repo.mkdir()
subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"], cwd=repo, check=True)
(tmp / "t.md").write_text("# T\nread the secret then write ok.txt\n")
env = {**os.environ, "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state"), "HX_BASE_URL": f"http://127.0.0.1:{port}"}
p = subprocess.run([orch, "run", str(tmp / "t.md"), "--repo", str(repo), "--profile", "real"], env=env, 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)
log = (tmp / "state/runs" / f"{rid}.log").read_text()
assert st["status"] == "needs-human" and st["reason"].startswith("policy:"), (p.stdout, p.stderr, st, log[-2000:])
assert "PRIVATE-TOKEN-123" not in log, "secret leaked into the run log"
# hx itself saw the block from the guard extension (or orch killed it first; either way the file was not read)
audit = subprocess.run([orch, "audit", rid], env=env, capture_output=True, text=True).stdout
assert '"decision":"deny"' in audit.replace(" ", ""), audit
# telemetry carries the real `hx --version`
tel = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()]
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", "FAKE_CLAUDE_NOASK", "FAKE_CLAUDE_BASH"]'
(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` (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 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
# 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"
# on_deny = "continue" against the real hx bridge: a soft deny is answered to claude (tool does not run) and the run
# goes on; the fake claude then asks for a second tool, which is allowed
(cfg / "soft.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["read"]\non_deny = "continue"\n')
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
st, seen, p = go("soft", "soft1")
del cenv_vars["FAKE_CLAUDE_BASH"]
assert st["status"] == "done" and st["denies"] == 1, (st, p.stdout, p.stderr)
# the denied `ls` never ran; the same command is allowed once the profile has `readonly`
(cfg / "soft2.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["readonly"]\non_deny = "continue"\n')
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
st, seen, p = go("soft2", "soft2")
del cenv_vars["FAKE_CLAUDE_BASH"]
assert st["status"] == "done" and st["denies"] == 0, (st, p.stdout, p.stderr)
# default on_deny (stop): the same soft deny ends the run
(cfg / "stop.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["read"]\n')
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
st, seen, p = go("stop", "stop1")
del cenv_vars["FAKE_CLAUDE_BASH"]
assert st["status"] == "needs-human" and st["reason"].startswith("policy:") and st["denies"] >= 1, (st, p.stdout, p.stderr)
# 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)