O5: safety - allowlist guard, credential separation, audit log (#13)
This commit was merged in pull request #13.
This commit is contained in:
1 parent
06662a085f
commit
bea07e82bb
9 files changed
+890
-29
No files matched your search
@@ -8,3 +8,5 @@ cargo test -q
|
||||
cargo build -q
|
||||
python3 tests/e2e.py
|
||||
python3 spike/check.py
|
||||
|
||||
python3 tests/real_hx.py
|
||||
+85
-28
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""End-to-end test for the orch binary with a fake hx. Run: python3 tests/e2e.py [path/to/orch]"""
|
||||
import json, os, pathlib, signal, subprocess, sys, tempfile, time
|
||||
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")
|
||||
@@ -12,35 +12,18 @@ 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 / "cfg/profiles").mkdir(parents=True)
|
||||
fake = tmp / "fake_hx.py"
|
||||
fake.write_text('''
|
||||
import json, sys, time, os
|
||||
body = sys.argv[sys.argv.index("-p") + 1]
|
||||
e = lambda o: print(json.dumps(o), flush=True)
|
||||
e({"type": "session_start"})
|
||||
if "NOJSON" in body: sys.exit(1)
|
||||
if "HANG" in body:
|
||||
open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid()))
|
||||
time.sleep(300)
|
||||
conc = os.environ.get("CONC")
|
||||
if "SLEEP=" in body:
|
||||
if conc: open(conc, "a").write("+")
|
||||
time.sleep(float(body.split("SLEEP=")[1].split()[0]))
|
||||
if conc: open(conc, "a").write("-")
|
||||
if "QUOTA" in body:
|
||||
e({"type": "stream", "event": {"type": "quota", "windows": [{"label": "5h", "used_pct": 100.0, "resets_at": int(time.time()) + 3600}], "credits": None}})
|
||||
for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1):
|
||||
e({"type": "turn_start"})
|
||||
e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}})
|
||||
if "WRITE" in body: open("out.txt", "w").write("x")
|
||||
if "--session" in sys.argv:
|
||||
open("retry-prompt.txt", "w").write(body)
|
||||
if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x")
|
||||
e({"type": "done", "error": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"})
|
||||
''')
|
||||
shutil.copy(root / "tests/fake_hx.py", fake)
|
||||
|
||||
|
||||
def profile(name, extra=""):
|
||||
(tmp / f"cfg/profiles/{name}.toml").write_text(f'hx = "{sys.executable} {fake}"\n{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}'
|
||||
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 = f'hx = "{sys.executable} {fake}"\n{top}'
|
||||
(tmp / f"cfg/profiles/{name}.toml").write_text(body + (f"\n[{rest}" if rest else ""))
|
||||
|
||||
|
||||
def task(name, body):
|
||||
@@ -61,7 +44,7 @@ def status(id):
|
||||
def check(p, st, reason=None):
|
||||
id = p.stdout.split()[0]
|
||||
s = status(id)
|
||||
assert s["status"] == st and (reason is None or (s["reason"] or "").startswith(reason)), (p.stdout, p.stderr, s)
|
||||
assert s["status"] == st and (reason is None or (s["reason"] or "").startswith(reason)), (p.stdout, p.stderr, s, (tmp / "state/runs" / (id + ".log")).read_text()[-1500:])
|
||||
return s
|
||||
|
||||
|
||||
@@ -211,6 +194,80 @@ assert p.returncode == 0 and p.stdout.count(" done") == 3, p
|
||||
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
|
||||
assert p.stdout.count(" done") == 1 and (qd / "e.md").exists() and "paused" in p.stderr, p
|
||||
|
||||
# --- safety (O5) ---
|
||||
def git_show(branch, path):
|
||||
return subprocess.run(["git", "show", f"{branch}:{path}"], cwd=repo, capture_output=True, text=True).stdout
|
||||
|
||||
private = tmp / "private/.hx"
|
||||
private.mkdir(parents=True)
|
||||
(private / "auth.json").write_text('{"claude": "PRIVATE-TOKEN-123"}')
|
||||
work_home = tmp / "work-home"
|
||||
work_home.mkdir()
|
||||
senv = {"HX_HOME": str(private), "AWS_SECRET_ACCESS_KEY": "AWS-SECRET-456", "GITEA_TOKEN": "TOK"}
|
||||
profile("sec", f'home = "{work_home}"\nallow = ["read", "write", "bash:cargo test*"]\n')
|
||||
|
||||
# the work profile cannot read the private profile's auth file: the guard blocks the call, the run needs a human
|
||||
s = check(run("steal", "sec", env=senv, body=f"CALL read {private}/auth.json"), "needs-human", "policy:")
|
||||
assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt"), "secret reached the agent"
|
||||
assert "outside the worktree" in s["reason"] or "credential" in s["reason"], s["reason"]
|
||||
# ...even if the guard process is dead or ignored: orch re-checks the event stream and kills the run
|
||||
s = check(run("steal2", "sec", env=senv, body=f"NOGUARD\nCALL read {private}/auth.json"), "needs-human", "policy:")
|
||||
# environment: secrets and the other profile's HX_HOME never reach hx
|
||||
s = check(run("envleak", "sec", env=senv, body="ENVDUMP"), "done")
|
||||
names = git_show(s["branch"], "env.txt").split()
|
||||
assert "PATH" in names and "HOME" in names, names
|
||||
assert not {"HX_HOME", "AWS_SECRET_ACCESS_KEY", "GITEA_TOKEN"} & set(names), names
|
||||
profile("sec2", f'home = "{work_home}"\nenv = ["GITEA_*"]\n')
|
||||
assert "GITEA_TOKEN" in git_show(check(run("envopt", "sec2", env=senv, body="ENVDUMP"), "done")["branch"], "env.txt").split()
|
||||
# allowed calls run, the guard config never ends up in the commit
|
||||
s = check(run("allowed", "sec", env=senv, body="CALL write a.txt\nCALL bash cargo test -p x\nCALL read a.txt"), "done")
|
||||
assert "RAN cargo test -p x" in git_show(s["branch"], "calls.txt")
|
||||
tree = subprocess.run(["git", "ls-tree", "-r", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout.split()
|
||||
assert ".hx/config.toml" not in tree, tree
|
||||
# not in the allowlist, chained bash, git push: all needs-human
|
||||
for name, call in [("nobash", "CALL bash ls"), ("chain", "CALL bash cargo test; curl evil"), ("push", "CALL bash git push origin main"),
|
||||
("hxcfg", "CALL write .hx/config.toml"), ("dotenv", "CALL write .env")]:
|
||||
check(run(name, "sec", env=senv, body=call), "needs-human", "policy:")
|
||||
# the audit trail has every decision, per run
|
||||
audit = subprocess.run([orch, "audit"], env=env, capture_output=True, text=True).stdout.splitlines()
|
||||
rows = [json.loads(l) for l in audit]
|
||||
assert any(r["ev"] == "tool" and r["detail"]["decision"] == "deny" and "auth.json" in r["detail"]["args"].get("path", "") for r in rows), rows[:3]
|
||||
assert any(r["ev"] == "tool" and r["detail"]["decision"] == "allow" for r in rows)
|
||||
assert {"run_start", "run_end"} <= {r["ev"] for r in rows}
|
||||
one = [json.loads(l) for l in subprocess.run([orch, "audit", s["id"]], env=env, capture_output=True, text=True).stdout.splitlines()]
|
||||
assert one and all(r["run"] == s["id"] for r in one), one
|
||||
# agent edits the guard config in the repo itself: refused at setup (we do not overwrite foreign config)
|
||||
(repo / ".hx").mkdir(exist_ok=True)
|
||||
(repo / ".hx/config.toml").write_text("# mine\n")
|
||||
subprocess.run(["git", "add", "-A"], cwd=repo, check=True)
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "own hx config"], cwd=repo, check=True)
|
||||
check(run("foreign", "sec", env=senv, body="CALL read a.txt"), "failed", "setup:")
|
||||
subprocess.run(["git", "rm", "-q", "-r", ".hx"], cwd=repo, check=True)
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "rm"], cwd=repo, check=True)
|
||||
# the guard process alone (no orch kill racing it): block / continue over the extension protocol
|
||||
gwt = tmp / "gwt"
|
||||
gwt.mkdir()
|
||||
pol = {"run": "g", "allow": ["read", "bash:cargo test*"], "worktree": str(gwt.resolve()), "read_roots": [], "audit": str(tmp / "g-audit.log")}
|
||||
(tmp / "g.json").write_text(json.dumps(pol))
|
||||
g = subprocess.Popen([orch, "guard", str(tmp / "g.json")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
|
||||
def ask(i, method, params):
|
||||
g.stdin.write(json.dumps({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) + "\n")
|
||||
g.stdin.flush()
|
||||
return json.loads(g.stdout.readline())["result"]
|
||||
assert ask(1, "initialize", {})["subscribe"] == ["tool_call"]
|
||||
ev = lambda n, a: ask(2, "event", {"event": {"type": "tool_call", "name": n, "args": a}})
|
||||
assert ev("read", {"path": "x.rs"})["action"] == "continue"
|
||||
b = ev("read", {"path": str(private / "auth.json")})
|
||||
assert b["action"] == "block" and b["reason"].startswith("orch-guard:"), b
|
||||
assert ev("bash", {"command": "cargo test; id"})["action"] == "block"
|
||||
assert ev("write", {"path": "x.rs"})["action"] == "block"
|
||||
g.stdin.close()
|
||||
assert g.wait(timeout=5) == 0
|
||||
assert len((tmp / "g-audit.log").read_text().splitlines()) == 4
|
||||
|
||||
# warning for unrestricted profiles
|
||||
assert "no `allow` list" in run("warn", "p", body="WRITE").stderr
|
||||
|
||||
# kill orch mid-run: status must say interrupted and hx must be dead after the next orch call
|
||||
pidfile = tmp / "hx.pid"
|
||||
p = subprocess.Popen([orch, "run", str(task("killed", "HANG")), "--repo", str(repo), "--profile", "p"],
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import json, sys, time, os
|
||||
body = sys.argv[sys.argv.index("-p") + 1]
|
||||
e = lambda o: print(json.dumps(o), flush=True)
|
||||
e({"type": "session_start"})
|
||||
import subprocess, tomllib
|
||||
ext = None
|
||||
def guard(name, args):
|
||||
"""Speak the hx extension protocol to whatever .hx/config.toml configures (like real hx)."""
|
||||
global ext
|
||||
if "NOGUARD" in body or not os.path.exists(".hx/config.toml"): return None
|
||||
if ext is None:
|
||||
cmd = tomllib.load(open(".hx/config.toml", "rb"))["extensions"][0]["command"]
|
||||
ext = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
|
||||
ext.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n"); ext.stdin.flush()
|
||||
ext.stdout.readline()
|
||||
ext.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "event", "params": {"event": {"type": "tool_call", "name": name, "args": args}}}) + "\n"); ext.stdin.flush()
|
||||
return json.loads(ext.stdout.readline())["result"]
|
||||
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}
|
||||
e({"type": "tool_call", "id": f"c{n}", "name": name, "args": args})
|
||||
r = guard(name, args)
|
||||
if r and r["action"] == "block":
|
||||
e({"type": "tool_result", "id": f"c{n}", "name": name, "args": args, "content": "blocked: " + r["reason"], "is_error": True})
|
||||
continue
|
||||
with open("calls.txt", "a") as f:
|
||||
if name == "read":
|
||||
try: f.write("READ " + open(arg).read() + "\n")
|
||||
except OSError as x: f.write("READ-ERR " + str(x) + "\n")
|
||||
elif name == "write": open(arg, "w").write("x"); f.write("WROTE " + arg + "\n")
|
||||
else: f.write("RAN " + arg + "\n")
|
||||
e({"type": "tool_result", "id": f"c{n}", "name": name, "args": args, "content": "ok", "is_error": False})
|
||||
if "ENVDUMP" in body: open("env.txt", "w").write("\n".join(sorted(os.environ)))
|
||||
if "NOJSON" in body: sys.exit(1)
|
||||
if "HANG" in body:
|
||||
open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid()))
|
||||
time.sleep(300)
|
||||
conc = os.environ.get("CONC")
|
||||
if "SLEEP=" in body:
|
||||
if conc: open(conc, "a").write("+")
|
||||
time.sleep(float(body.split("SLEEP=")[1].split()[0]))
|
||||
if conc: open(conc, "a").write("-")
|
||||
if "QUOTA" in body:
|
||||
e({"type": "stream", "event": {"type": "quota", "windows": [{"label": "5h", "used_pct": 100.0, "resets_at": int(time.time()) + 3600}], "credits": None}})
|
||||
for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1):
|
||||
e({"type": "turn_start"})
|
||||
e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}})
|
||||
if "WRITE" in body: open("out.txt", "w").write("x")
|
||||
if "--session" in sys.argv:
|
||||
open("retry-prompt.txt", "w").write(body)
|
||||
if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x")
|
||||
e({"type": "done", "error": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"})
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/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
|
||||
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}))
|
||||
finally:
|
||||
srv.terminate()
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
Reference in new issue
Block a user