# Conflicts: # backend/plugins/manifest.py # sidecar/launch.py # sidecar/test_claude_args.py # sidecar/test_gcloud_reauth.py
181 lines
9.2 KiB
Python
181 lines
9.2 KiB
Python
"""plugin_hooks: live plugins' harnessHooks on this machine — the declarative
|
|
evaluator, the ``--settings`` entries a claude launch gets, and the worker's
|
|
``/sync`` writer (labsync.write_hooks)."""
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
|
|
import claude_launch
|
|
import labsync
|
|
import plugin_hooks as ph
|
|
|
|
GCLOUD = {
|
|
"plugin": "gcloud-reauth", "id": "gcloud-expired", "harness": "claude",
|
|
"event": "PostToolUse", "matcher": "Bash", "guestAllowed": False,
|
|
"excludeCommandRegex": r"gcloud\s+auth\b",
|
|
"outputRegex": (r"invalid_rapt|reauthentication failed|reauthentication required"
|
|
r"|gcloud\s+auth\s+login|gcloud\s+auth\s+application-default\s+login"),
|
|
"message": "Google sign-in expired on this machine: use the gcloud-login skill "
|
|
"(it sends Gabriel a form; he never runs a command), then retry.",
|
|
"ignoreCase": True,
|
|
}
|
|
EXPIRED = ("ERROR: (gcloud.projects.list) There was a problem refreshing your current "
|
|
"auth tokens: Reauthentication failed. cannot prompt during non-interactive "
|
|
"execution.\nPlease run:\n\n $ gcloud auth login\n\nto obtain new credentials.")
|
|
|
|
|
|
def _payload(out="", command="gcloud projects list"):
|
|
return {"hook_event_name": "PostToolUse", "tool_name": "Bash",
|
|
"tool_input": {"command": command},
|
|
"tool_response": {"stdout": "", "stderr": out}}
|
|
|
|
|
|
def _index(tmp_path, rules, files=None):
|
|
root = tmp_path / "hooks"
|
|
root.mkdir()
|
|
(root / "index.json").write_text(json.dumps({"hash": "x", "hooks": rules}))
|
|
for rel, text in (files or {}).items():
|
|
p = root / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text(text)
|
|
return root
|
|
|
|
|
|
# ── the evaluator ─────────────────────────────────────────────────────────────
|
|
def test_gcloud_expiry_points_at_the_skill():
|
|
out = ph.check([GCLOUD], _payload(EXPIRED), "PostToolUse", "Bash")
|
|
h = json.loads(out)["hookSpecificOutput"]
|
|
assert h["hookEventName"] == "PostToolUse"
|
|
assert "gcloud-login skill" in h["additionalContext"]
|
|
# invalid_rapt in JSON output, any case
|
|
assert ph.check([GCLOUD], _payload('{"error": "INVALID_RAPT"}'), "PostToolUse", "Bash")
|
|
|
|
|
|
def test_left_alone():
|
|
assert ph.check([GCLOUD], _payload("all good"), "PostToolUse", "Bash") is None
|
|
# the skill's own login flow prints "gcloud auth login" hints itself
|
|
assert ph.check([GCLOUD], _payload(EXPIRED, command="gcloud auth login --no-browser"),
|
|
"PostToolUse", "Bash") is None
|
|
# another event / matcher, a guest run on a rule not guestAllowed
|
|
assert ph.check([GCLOUD], _payload(EXPIRED), "PreToolUse", "Bash") is None
|
|
assert ph.check([GCLOUD], _payload(EXPIRED), "PostToolUse", "Edit") is None
|
|
assert ph.check([GCLOUD], _payload(EXPIRED), "PostToolUse", "Bash", guest=True) is None
|
|
assert ph.check([{**GCLOUD, "guestAllowed": True}], _payload(EXPIRED),
|
|
"PostToolUse", "Bash", guest=True)
|
|
|
|
|
|
def test_only_the_tail_of_a_long_output_is_scanned():
|
|
head = "gcloud auth login\n" + "x" * (ph.MAX_SCAN + 10)
|
|
assert ph.check([GCLOUD], _payload(head), "PostToolUse", "Bash") is None
|
|
assert ph.check([GCLOUD], _payload("x" * (ph.MAX_SCAN * 2) + "invalid_rapt"),
|
|
"PostToolUse", "Bash")
|
|
|
|
|
|
def test_command_rules_and_dedup():
|
|
rule = {"event": "PreToolUse", "matcher": "Bash", "commandRegex": r"\bnpm\s+publish\b",
|
|
"message": "Don't publish.", "ignoreCase": False}
|
|
p = _payload(command="npm publish --dry-run")
|
|
out = json.loads(ph.check([rule, dict(rule, id="dup")], p, "PreToolUse", "Bash"))
|
|
assert out["hookSpecificOutput"]["additionalContext"] == "Don't publish."
|
|
assert ph.check([rule], _payload(command="NPM PUBLISH"), "PreToolUse", "Bash") is None
|
|
# a broken regex never raises
|
|
assert ph.check([dict(rule, commandRegex="(")], p, "PreToolUse", "Bash") is None
|
|
|
|
|
|
def test_the_cli_always_exits_0(tmp_path):
|
|
root = _index(tmp_path, [GCLOUD])
|
|
base = [sys.executable, "-I", ph.__file__, "--index", str(root / "index.json"),
|
|
"--event", "PostToolUse", "--matcher", "Bash"]
|
|
r = subprocess.run(base, input=json.dumps(_payload(EXPIRED)),
|
|
capture_output=True, text=True, timeout=10)
|
|
assert r.returncode == 0 and "gcloud-login" in r.stdout
|
|
for junk in ("not json", "[]", ""):
|
|
r = subprocess.run(base, input=junk, capture_output=True, text=True, timeout=10)
|
|
assert r.returncode == 0 and r.stdout == ""
|
|
r = subprocess.run(base[:4] + [str(tmp_path / "missing.json")] + base[5:],
|
|
input=json.dumps(_payload(EXPIRED)), capture_output=True, text=True,
|
|
timeout=10)
|
|
assert r.returncode == 0 and r.stdout == ""
|
|
|
|
|
|
# ── the settings entries ──────────────────────────────────────────────────────
|
|
def test_settings_hooks_group_rules_and_wire_scripts(tmp_path):
|
|
script = {"plugin": "p", "id": "custom", "event": "PostToolUse", "matcher": "Bash",
|
|
"script": "p/hooks/my_hook.py", "timeoutSec": 7, "guestAllowed": True}
|
|
escape = dict(script, id="bad", script="../evil.py")
|
|
root = _index(tmp_path, [GCLOUD, dict(GCLOUD, id="second"), script, escape],
|
|
{"p/hooks/my_hook.py": "print('hi')\n"})
|
|
s = ph.settings_hooks(root, "/usr/bin/python3")
|
|
post = s["PostToolUse"]
|
|
cmds = [e["hooks"][0]["command"] for e in post]
|
|
assert len(post) == 2 # one declarative group + the one valid script
|
|
assert any(c.endswith(str(root / "p/hooks/my_hook.py")) and " -I " in c for c in cmds)
|
|
decl = next(e for e in post if "plugin_hooks.py" in e["hooks"][0]["command"])
|
|
assert decl["matcher"] == "Bash" and "--event PostToolUse" in decl["hooks"][0]["command"]
|
|
assert next(e for e in post if "my_hook" in e["hooks"][0]["command"])["hooks"][0]["timeout"] == 7
|
|
# a scoped run: only guestAllowed ones, and the evaluator is told
|
|
scoped = ph.settings_hooks(root, "/usr/bin/python3", scoped=True)["PostToolUse"]
|
|
assert [e["hooks"][0]["command"] for e in scoped] == [c for c in cmds if "my_hook" in c]
|
|
# code mode: a failing hook never refuses the call
|
|
cm = ph.settings_hooks(root, "/usr/bin/python3", code_mode=True)["PostToolUse"]
|
|
assert all(e["hooks"][0]["onFailure"] == "continue" for e in cm)
|
|
assert ph.settings_hooks(tmp_path / "nowhere", "/usr/bin/python3") == {}
|
|
|
|
|
|
def _plugin_entries(settings):
|
|
return [e for e in settings.get("hooks", {}).get("PostToolUse", [])
|
|
if "plugin_hooks.py" in e["hooks"][0]["command"]]
|
|
|
|
|
|
def test_claude_settings_inject_the_live_hooks(tmp_path, monkeypatch):
|
|
root = _index(tmp_path, [GCLOUD])
|
|
monkeypatch.setenv("SIDECAR_LIVE_HOOKS_DIR", str(root))
|
|
(entry,) = _plugin_entries(claude_launch._claude_settings())
|
|
assert entry["matcher"] == "Bash" and " -I " in entry["hooks"][0]["command"]
|
|
assert not _plugin_entries(claude_launch._claude_settings(["/tmp/x"])) # scoped: not guestAllowed
|
|
monkeypatch.setattr(claude_launch, "PLUGIN_HOOKS_ENABLED", False)
|
|
assert not _plugin_entries(claude_launch._claude_settings())
|
|
monkeypatch.setattr(claude_launch, "PLUGIN_HOOKS_ENABLED", True)
|
|
(root / "index.json").write_text("{broken")
|
|
assert not _plugin_entries(claude_launch._claude_settings())
|
|
|
|
|
|
def test_root_by_machine(monkeypatch):
|
|
monkeypatch.delenv("SIDECAR_LIVE_HOOKS_DIR", raising=False)
|
|
assert ph.root(True) == pathlib.Path(os.path.expanduser("~/.ai-agent-worker/hooks"))
|
|
assert ph.root(False).name == "live-hooks"
|
|
|
|
|
|
# ── the worker's /sync writer ─────────────────────────────────────────────────
|
|
def test_write_hooks(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(labsync, "_guest_computer", lambda: False)
|
|
root = tmp_path / "hooks"
|
|
script = {"plugin": "p", "id": "s", "event": "Stop", "script": "p/hooks/h.py"}
|
|
files = {"p/hooks/h.py": base64.b64encode(b"print(1)\n").decode()}
|
|
out = labsync.write_hooks({"hash": "h1", "rules": [GCLOUD, script], "files": files}, root)
|
|
assert out == {"hash": "h1", "rules": 2}
|
|
assert len(ph.load(root / "index.json")) == 2
|
|
assert (root / "p/hooks/h.py").read_text() == "print(1)\n"
|
|
# a script rule whose file didn't come is dropped; {} clears
|
|
labsync.write_hooks({"hash": "h2", "rules": [script], "files": {}}, root)
|
|
assert ph.load(root / "index.json") == [] and not (root / "p").exists()
|
|
labsync.write_hooks({}, root)
|
|
assert ph.load(root / "index.json") == []
|
|
# a path that escapes is refused
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
with pytest.raises(HTTPException):
|
|
labsync.write_hooks({"rules": [], "files": {"../x.py": files["p/hooks/h.py"]}}, root)
|
|
|
|
|
|
def test_a_guest_computer_keeps_only_guest_allowed(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(labsync, "_guest_computer", lambda: True)
|
|
root = tmp_path / "hooks"
|
|
labsync.write_hooks({"hash": "h", "rules": [GCLOUD, dict(GCLOUD, id="g", guestAllowed=True)]},
|
|
root)
|
|
assert [r["id"] for r in ph.load(root / "index.json")] == ["g"]
|