Files
gabrielvidal aaab115fa2 fix(sidecar): Monitor through the guard, fail-closed, scoped runs ignore project Claude settings; safe git, egress, ship from a copy
Monitor ran shell commands the guard never saw; the owner CLI, docker and ssh
rules fell to ordinary spellings (the CLI now refuses under AIA_GUEST); a guard
exception let the call through; chat-level runs still had the owner's gitea.lab
and gh credential helpers. Scoped lab runs: --setting-sources user,
--strict-mcp-config, hooks under python -I, the project CLAUDE.md appended as
text, scope.noBash. 3d-render uploads carry data: URIs only; a guest's video
URL resolves to public addresses through a vetting proxy; git on a guest repo
runs with fsmonitor, hooks, filters and textconv out of reach; the ship broker
deploys a checked copy; tokens leave argv.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

95 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""PreToolUse hook of a lean run with an allowlist (launch.py "lean runs").
Every command of a Bash call must start with an allowed program
(``--allow a,b,…``) or a read-only SAFE_CMDS one; anything else is denied
with a reason the model reads. The counterpart of the pi runner's
``extensions/folder-permissions.ts`` (PI_ALLOW_CMDS) — same parser, same
list — so a job refuses the same commands on either harness.
Claude Code's own allowlist (``dontAsk`` + ``Bash(<program>:*)``) can't carry
these jobs: it refuses any file redirect and any heredoc, i.e. most of a
digest's ``radar gather > x.json`` and ``mail send … <<'BODY'``.
"""
import json
import os
import re
import sys
SAFE_CMDS = {"cat", "head", "tail", "jq", "ls", "wc", "grep", "echo", "printf", "date",
"sort", "uniq", "cut", "tr", "true", "false", "test", "[", "pwd", "basename",
"dirname", "diff", "stat", "file", "which"}
_SKIP = {"then", "do", "done", "fi", "else", "esac"}
def programs(cmd: str) -> list[str]:
"""The programs a bash command runs: heredoc bodies and quoted strings
dropped, split on ``&&``, ``||``, ``;``, ``|``, a lone ``&``, newlines,
``$(``/backticks and process substitutions (``<(``, ``>(``), then each
segment's first word past any ``VAR=value`` —
plus, parsed the same way, what the shell still runs inside the dropped
text: ``$(…)`` and backticks in a double-quoted string or an unquoted
heredoc. Naive — defense in depth, not a sandbox."""
inner: list[str] = []
cmd = cmd.replace("\\\n", " ") # a `\`-continued line is the same command
def literal(text: str) -> str:
inner.extend(a or b for a, b in re.findall(r"\$\(([^)]*)\)|`([^`]*)`", text))
return "''"
flat = re.sub(r"<<-?\s*(['\"]?)(\w+)\1([^\n]*)\n([\s\S]*?)\n\s*\2\s*(?=\n|$)",
lambda m: m.group(3) + (" " if m.group(1) else " " + literal(m.group(4))), cmd)
# One pass, so whichever quote opens first wins (an apostrophe inside a
# double-quoted French sentence is just a letter).
flat = re.sub(r"'[^']*'|\"(?:\\.|[^\"\\])*\"",
lambda m: "''" if m.group(0)[0] == "'" else literal(m.group(0)), flat)
# A redirect's `&` is not a separator: `2>&1`, `>&2`, `<&3`, `>&-`, `&>f`.
flat = re.sub(r"\d*[<>]&\s*(\d+|-)?", " ", flat)
flat = re.sub(r"&>>?", ">", flat)
out = []
for seg in re.split(r"&&|\|\||[;|&\n]|\$\(|`|[<>]\(", flat):
words = re.sub(r"^[({]\s*", "", seg.strip()).split()
while words and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", words[0]):
words.pop(0)
if not words or re.match(r"^[)}<>]|^\d?>", words[0]) or words[0] in _SKIP:
continue
out.append(words[0].rstrip(")").rsplit("/", 1)[-1]) # `$(date)`, `>(bash)`
for sub in inner:
out += programs(sub)
return out
def refused(cmd: str, allow: list[str]) -> list[str]:
ok = {p.rsplit("/", 1)[-1] for p in allow} | SAFE_CMDS
return list(dict.fromkeys(p for p in programs(cmd) if p not in ok))
def main() -> int:
allow = sys.argv[sys.argv.index("--allow") + 1].split(",") if "--allow" in sys.argv else []
try:
event = json.load(sys.stdin)
except ValueError:
return 0
if event.get("tool_name") != "Bash" or not allow:
return 0
bad = refused(str((event.get("tool_input") or {}).get("command") or ""), allow)
if bad:
if os.environ.get("ALLOW_GUARD_LOG"): # where refusals are kept, if anywhere
with open(os.environ["ALLOW_GUARD_LOG"], "a") as f:
f.write(json.dumps({"refused": bad, "command": event["tool_input"]["command"]},
ensure_ascii=False) + "\n")
own = [p for p in allow if p not in SAFE_CMDS]
json.dump({"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
f"this scheduled job may only call {', '.join(own)} (and read-only "
f"tools like cat, jq, grep) — not {', '.join(bad)}"),
}}, sys.stdout)
return 0
if __name__ == "__main__":
sys.exit(main())