Files
orch/tests/real_hx.py
T

100 lines
6.3 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"]'
(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`: refused before hx starts, so the claude binary never runs and the secret stays unread
n_calls = len((tmp / "argv.log").read_text().splitlines())
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
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")
finally:
srv.terminate()
shutil.rmtree(tmp, ignore_errors=True)