refuse allow with claude_cli instead of forcing the direct provider
This commit is contained in:
1 parent
2ff8abe7a3
commit
2751bcf27b
7 files changed
+60
-34
No files matched your search
+7
-5
@@ -39,12 +39,14 @@ hx has two ways to reach Claude. They differ in what orch can enforce:
|
||||
| mode | who runs the tools | `allow` | `max_turns` |
|
||||
|---|---|---|---|
|
||||
| `direct` (API provider) | hx | enforced (guard + stream check) | counts model turns |
|
||||
| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary; hx emits no `tool_call` events | cannot be enforced | meaningless: 1 hx request per run |
|
||||
| `claude_cli` (hx starts the `claude` binary; auto-on when `claude` is in PATH and `HX_BASE_URL` is unset) | the `claude` binary; hx emits no `tool_call` events and its permission bridge skips reads | cannot be enforced | meaningless: 1 hx request per run |
|
||||
|
||||
With `allow` set, orch writes `claude_cli = false` into the generated worktree `.hx/config.toml` (project config
|
||||
beats `~/.hx/config.toml`), so the run uses the direct provider and the allowlist holds. The direct Claude provider
|
||||
bills OAuth calls as extra usage; if that is not acceptable, profiles for `claude_cli` must go without `allow` and
|
||||
rely on `home`, the cleared environment and `sandbox = true`. orch warns for those (no allowlist).
|
||||
A profile with `allow` in `claude_cli` mode is **refused** before hx starts: the run ends `needs-human` with
|
||||
`policy: allow cannot be enforced ...`. orch never runs "guarded" without a guard and never switches providers
|
||||
silently (the direct Claude provider is not usable on every subscription). Options for such a profile:
|
||||
no `allow` plus `sandbox = true`, `home`, the cleared environment; or `claude_cli = false` in the profile's hx config
|
||||
if the direct provider works for you. Planned: make the claude_cli provider guardable in hx (permission bridge on
|
||||
the event bus, tool events), see the linked hx issue.
|
||||
|
||||
Telemetry records the mode (`provider_mode`: `claude_cli`, `direct`, `codex`; old lines `unknown`). `orch report`
|
||||
shows it as a column and `orch eval` refuses to compare files with different (or mixed) modes ("NOT COMPARABLE",
|
||||
|
||||
+3
-6
@@ -8,8 +8,8 @@
|
||||
//! must stay inside the worktree or `read_roots`. Hard rules apply to every allowed call: no `git push`
|
||||
//! (publishing is the sink's job), no secret-looking paths, file tools stay in the worktree (reads may also
|
||||
//! use `read_roots`), writes never touch `.git` or `.hx` (guard config).
|
||||
//! With `allow` set orch writes `claude_cli = false` into the generated worktree config: the `claude_cli`
|
||||
//! provider executes tools inside the `claude` binary, invisible to hx' event bus, so it cannot be guarded.
|
||||
//! Not enforceable with hx' `claude_cli` provider: the `claude` binary runs its own tools, invisible to hx' event
|
||||
//! bus. `run::execute` refuses such a run up front (see `report::provider_mode`) instead of running it unguarded.
|
||||
//! ponytail: plain `bash` is not confined (a shell cannot be parsed reliably); use `sandbox = true` for that.
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
@@ -294,10 +294,7 @@ pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) -
|
||||
}
|
||||
std::fs::create_dir_all(cfg.parent().unwrap())?;
|
||||
let exe = std::env::current_exe()?.to_string_lossy().into_owned();
|
||||
// `claude_cli = false`: with the claude_cli provider the `claude` binary runs its own tools and hx emits no
|
||||
// tool_call events, so neither the guard nor the stream check would see anything. The project config beats
|
||||
// ~/.hx/config.toml, so this holds even when the profile's home enables claude_cli.
|
||||
let ext = toml::to_string(&json!({"claude_cli": false, "extensions": [{
|
||||
let ext = toml::to_string(&json!({"extensions": [{
|
||||
"command": [exe, "guard", pp.to_string_lossy()], "timeout_secs": 10}]}))?;
|
||||
std::fs::write(cfg, format!("{MARK}\n{ext}"))?;
|
||||
Ok(pol)
|
||||
|
||||
+3
-6
@@ -47,17 +47,14 @@ fn unknown() -> String {
|
||||
"unknown".into()
|
||||
}
|
||||
|
||||
/// The mode hx will use for this profile and worktree, derived the way hx decides it: `allow` forces direct (see
|
||||
/// policy.rs); else `claude_cli` in the worktree/home config; else auto = on when the claude binary starts and no
|
||||
/// HX_BASE_URL is set. ponytail: ignores hx' remembered last provider (`last.json`), so a profile without
|
||||
/// The mode hx will use for this profile and worktree, derived the way hx decides it: `provider = "codex"`; else
|
||||
/// `claude_cli` in the worktree/home config; else auto = on when the claude binary starts and no HX_BASE_URL is
|
||||
/// set (HX_BASE_URL only counts when the profile passes it on, like hx sees it). ponytail: ignores hx' remembered last provider (`last.json`), so a profile without
|
||||
/// `provider` that hx routes to codex is still labelled claude_cli; set `provider` in profiles you compare.
|
||||
pub fn provider_mode(p: &Profile, wt: &Path) -> String {
|
||||
if p.provider.as_deref() == Some("codex") {
|
||||
return "codex".into();
|
||||
}
|
||||
if p.allow.is_some() {
|
||||
return "direct".into();
|
||||
}
|
||||
let home = p.home.clone().map(|h| h.join(".hx"));
|
||||
let explicit = [
|
||||
Some(wt.join(".hx")),
|
||||
|
||||
+10
@@ -112,6 +112,8 @@ fn usage_total(u: &Value) -> u64 {
|
||||
.sum()
|
||||
}
|
||||
|
||||
const REFUSE_CLAUDE_CLI: &str = "`allow` cannot be enforced with hx' claude_cli provider (the claude binary runs its own tools, hx sees no tool calls). Remove `allow` and use `sandbox = true`, or set `claude_cli = false` in the profile's hx config to use the direct provider.";
|
||||
|
||||
/// hx surfaces provider rejections as `api 429: ...`; also match the usual wording.
|
||||
fn is_rate_limit(reason: &str) -> bool {
|
||||
let r = reason.to_lowercase();
|
||||
@@ -169,6 +171,14 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
let mut log = std::fs::File::create(log_path(&r.id))?;
|
||||
if p.allow.is_some() && crate::report::provider_mode(p, &r.worktree) == "claude_cli" {
|
||||
// never run "guarded" without a guard: the claude binary's tools are invisible to hx and orch
|
||||
writeln!(log, "{REFUSE_CLAUDE_CLI}")?;
|
||||
r.status = Status::NeedsHuman;
|
||||
r.reason = Some(format!("policy: {REFUSE_CLAUDE_CLI}"));
|
||||
r.ended = Some(now());
|
||||
return r.save();
|
||||
}
|
||||
let mut prompt = body.clone();
|
||||
let mut session: Option<String> = None;
|
||||
loop {
|
||||
|
||||
+26
-10
@@ -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,13 +270,27 @@ g.stdin.close()
|
||||
assert g.wait(timeout=5) == 0
|
||||
assert len((tmp / "g-audit.log").read_text().splitlines()) == 4
|
||||
|
||||
# O5 follow-up (#17): the generated guard config forces the direct provider, telemetry records the mode
|
||||
s = check(run("cfgseen", "sec", env=senv, body="CALL write a.txt"), "done")
|
||||
seen = git_show(s["branch"], "cfg-seen.txt")
|
||||
assert "claude_cli = false" in seen and "orch-guard" in seen, seen
|
||||
# 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"] == "cfgseen"] == ["direct"], recs2[-3:]
|
||||
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
|
||||
s = check(run("refuse", "sec", env=cenv, body="CALL write a.txt"), "needs-human", "policy: `allow` cannot be enforced")
|
||||
assert s["attempts"] == 0 and s["hx_exit"] is None, s # hx was never started
|
||||
assert "claude_cli = false" in (tmp / "state/runs" / (s["id"] + ".log")).read_text()
|
||||
# explicit opt-out in the profile's hx config => direct, allowed again
|
||||
(work_home / ".hx").mkdir(exist_ok=True)
|
||||
(work_home / ".hx/config.toml").write_text("claude_cli = false\n")
|
||||
check(run("optout", "sec", env=cenv, body="CALL write a.txt"), "done")
|
||||
(work_home / ".hx/config.toml").unlink()
|
||||
# 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")
|
||||
@@ -371,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")
|
||||
@@ -39,7 +39,6 @@ if os.environ.get("SOLVE_DIR"):
|
||||
t = open(os.path.join(os.environ["SOLVE_DIR"], c, "task.md")).read().split("\n", 2)[2].strip()
|
||||
if t == body.strip() and c not in os.environ.get("SOLVE_SKIP", "").split(","):
|
||||
subprocess.run(["cp", "-R", os.path.join(os.environ["SOLVE_DIR"], c, "solution") + "/.", "."], check=True)
|
||||
if os.path.exists(".hx/config.toml"): open("cfg-seen.txt", "w").write(open(".hx/config.toml").read())
|
||||
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:
|
||||
|
||||
+11
-6
@@ -74,21 +74,26 @@ try:
|
||||
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`: orch forces the direct provider, the claude binary never starts, the guard denies the Read
|
||||
# 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", "gd")
|
||||
st, seen, p = go("guarded", "gd2")
|
||||
finally:
|
||||
srv2.terminate()
|
||||
assert len((tmp / "argv.log").read_text().splitlines()) == n_calls, "claude binary was started despite allow"
|
||||
assert seen is None or "PRIVATE-TOKEN-123" not in seen, seen
|
||||
assert st["status"] == "needs-human" and st["reason"].startswith("policy:"), (st, p.stdout, p.stderr)
|
||||
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 forces direct, secret not read")
|
||||
print("claude_cli mode ok: allow refused with claude_cli, enforced with direct")
|
||||
finally:
|
||||
srv.terminate()
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
Reference in new issue
Block a user