on_deny=continue (soft vs hard denies), denies counter, tokens of stopped runs
This commit is contained in:
1 parent
e668eb1b0d
commit
8c76da90e8
11 files changed
+310
-87
No files matched your search
@@ -257,6 +257,36 @@ for name, call in [("ro-exec", "CALL bash find . -exec rm {} +"), ("ro-rm", "CAL
|
||||
("ro-secret", "CALL bash cat .env"), ("ro-out", "CALL bash ls /etc")]:
|
||||
check(run(name, "ro", env=senv, body=call), "needs-human", "policy:")
|
||||
|
||||
# --- on_deny = "continue": soft denies are answered, the run goes on; hard denies still stop it ---
|
||||
profile("soft", f'home = "{work_home}"\nallow = ["readonly", "write"]\non_deny = "continue"\n')
|
||||
# the agent tries a forbidden command, gets the reason, then does the allowed thing
|
||||
s = check(run("soft-ok", "soft", env=senv, body="CALL bash python3 -c 'print(1)'\nCALL bash ls\nCALL write a.txt"), "done")
|
||||
calls = git_show(s["branch"], "calls.txt")
|
||||
assert "RAN ls" in calls and "WROTE a.txt" in calls and "python3" not in calls, calls # the denied call never ran
|
||||
assert s["denies"] == 1, s
|
||||
assert not (tmp / "state/worktrees" / s["id"] / ".hx").exists()
|
||||
# the soft reason reaches the agent and says to use another way
|
||||
rows = [json.loads(l) for l in subprocess.run([orch, "audit", s["id"]], env=env, capture_output=True, text=True).stdout.splitlines()]
|
||||
assert [r["detail"]["decision"] for r in rows if r["ev"] == "tool"] == ["deny", "allow", "allow"], rows
|
||||
assert "orch-guard-soft:" in (tmp / "state/runs" / (s["id"] + ".log")).read_text()
|
||||
# hard denies stop the run even with on_deny = continue
|
||||
s = check(run("soft-hard", "soft", env=senv, body=f"CALL bash python3 -c 'x'\nCALL read {private}/auth.json\nCALL write b.txt"), "needs-human", "policy:")
|
||||
assert s["denies"] == 2 and "WROTE b.txt" not in git_show(s["branch"], "calls.txt"), s # stopped at the credential read
|
||||
assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt")
|
||||
for name, call in [("soft-push", "CALL bash git push origin main"), ("soft-meta", "CALL write .hx/config.toml"), ("soft-out", "CALL bash ls /etc")]:
|
||||
check(run(name, "soft", env=senv, body=call), "needs-human", "policy:")
|
||||
# default stop: the first soft deny ends the run (unchanged)
|
||||
s = check(run("stop-default", "ro", env=senv, body="CALL bash python3 -c 'print(1)'\nCALL write a.txt"), "needs-human", "policy:")
|
||||
assert s["denies"] == 1 and "a.txt" not in git_show(s["branch"], "calls.txt"), s
|
||||
# direct provider only emits the tool_call: soft deny with the stream check alone (NOGUARD) must not kill the run
|
||||
check(run("soft-noguard", "soft", env=senv, body="NOGUARD\nCALL bash python3 -c 'print(1)'\nCALL write a.txt"), "done")
|
||||
|
||||
# --- tokens of a run that is stopped before hx prints its final `done` line are kept ---
|
||||
tel_now = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()]
|
||||
stopped = next(r for r in reversed(tel_now) if r["task"] == "stop-default")
|
||||
assert stopped["status"] == "needs-human" and stopped["input_tokens"] == 100 and stopped["cache_read_tokens"] == 1000, stopped
|
||||
assert stopped["denies"] == 1, stopped
|
||||
|
||||
# the guard process alone (no orch kill racing it): block / continue over the extension protocol
|
||||
gwt = tmp / "gwt"
|
||||
gwt.mkdir()
|
||||
|
||||
+45
-23
@@ -10,37 +10,59 @@ if "--version" in sys.argv:
|
||||
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)
|
||||
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"):
|
||||
import subprocess
|
||||
|
||||
_bridge = {}
|
||||
|
||||
|
||||
def ask(tool, inp, tid):
|
||||
"""Ask hx whether `tool` may run (like claude with --permission-prompt-tool); returns the answer dict."""
|
||||
if "--permission-prompt-tool" not in sys.argv or os.environ.get("FAKE_CLAUDE_NOASK"):
|
||||
return {"behavior": "allow"}
|
||||
if not _bridge:
|
||||
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"]})
|
||||
_bridge["p"] = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
text=True, env={**os.environ, **cfg["env"]})
|
||||
_bridge["n"] = 0
|
||||
send("initialize", {})
|
||||
_bridge["p"].stdout.readline()
|
||||
send("tools/call", {"name": "approve", "arguments": {"tool_name": tool, "input": inp, "tool_use_id": tid}})
|
||||
return json.loads(json.loads(_bridge["p"].stdout.readline())["result"]["content"][0]["text"])
|
||||
|
||||
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", "id": "t1", "name": "Read", "input": {"file_path": target}}]}})
|
||||
def send(method, params):
|
||||
_bridge["n"] = _bridge.get("n", 0) + 1
|
||||
_bridge["p"].stdin.write(json.dumps({"jsonrpc": "2.0", "id": _bridge["n"], "method": method, "params": params}) + "\n")
|
||||
_bridge["p"].stdin.flush() # (a lambda `write(..) or flush()` never reaches flush: write returns a truthy count)
|
||||
|
||||
|
||||
def tool(tid, name, inp, run):
|
||||
"""One tool use: ask, announce, run only when allowed, report the result."""
|
||||
answer = ask(name, inp, tid)
|
||||
out({"type": "assistant", "session_id": "S1", "message": {"content": [{"type": "tool_use", "id": tid, "name": name, "input": inp}]}})
|
||||
if answer["behavior"] == "allow":
|
||||
res, err = run(), False
|
||||
else:
|
||||
res, err = "deny: " + answer.get("message", ""), True
|
||||
out({"type": "user", "session_id": "S1", "message": {"content": [
|
||||
{"type": "tool_result", "tool_use_id": tid, "content": res, "is_error": err}]}})
|
||||
return not err
|
||||
|
||||
|
||||
if os.environ.get("FAKE_CLAUDE_BASH"): # first a Bash call (may be denied softly), then a Read of $FAKE_CLAUDE_READ
|
||||
cmd = os.environ["FAKE_CLAUDE_BASH"]
|
||||
tool("b1", "Bash", {"command": cmd}, lambda: subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout)
|
||||
elif os.environ.get("FAKE_CLAUDE_READ"):
|
||||
target = os.environ["FAKE_CLAUDE_READ"]
|
||||
|
||||
def read():
|
||||
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}]}})
|
||||
return seen
|
||||
|
||||
tool("t1", "Read", {"file_path": target}, 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}})
|
||||
@@ -18,6 +18,9 @@ def guard(name, args):
|
||||
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"]
|
||||
if "CALL " in body: # a model turn that ends in tool calls is one request: its usage is streamed right away
|
||||
e({"type": "turn_start"})
|
||||
e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50, "cache_read_tokens": 1000, "cache_write_tokens": 10}}})
|
||||
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}
|
||||
|
||||
+20
-1
@@ -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", "FAKE_CLAUDE_NOASK"]'
|
||||
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")}
|
||||
@@ -100,6 +100,25 @@ try:
|
||||
|
||||
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"
|
||||
|
||||
Reference in new issue
Block a user