backend/ship/ (store, service, routes), /api/ship/* (authz + golden matrix), DEPS.deploy_hosts, the guard's ship-deploy catch (_SHIP / ship()) and the guest prompt's hardcoded ship-deploy line are gone: the managed ship plugin (ai-agent-plugins) decides who deploys where and its skill supplies the instructions. carryover.ship copies /data/deploy-hosts.json into the plugin's shared dir once (then ….migrated). GUARD_SHIP_TIMEOUT_S becomes GUARD_BROKER_TIMEOUT_S — the ai-agent CLI broker still needs it. Kept: sidecar/ship.py (the ship.run bridge's /ship/deploy), deploycmd.py, DeployWidget / DeployGizmo, the ship project level. openapi.json is not re-dumped here (the coordinator does it after Batch 1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
469 lines
23 KiB
Python
469 lines
23 KiB
Python
#!/usr/bin/env python3
|
|
"""Claude Code ``PreToolUse`` hook on every sidecar run: the **guard**.
|
|
|
|
It reads the tool call about to run (Bash, Monitor — which runs a shell
|
|
command too —, Edit, Write, MultiEdit, NotebookEdit) and matches it against a short list of rules in four families
|
|
(Gabriel's picks, docs/security.md):
|
|
|
|
* ``persistence`` — writing where code runs later on its own: shell rc files,
|
|
``~/.claude`` settings / hooks / CLAUDE.md, systemd user units, crontab,
|
|
``authorized_keys`` and ``~/.ssh``, git hooks;
|
|
* ``destructive`` — ``rm -rf`` of the home, ``/`` or a top-level tree
|
|
(``~/homelab``, ``~/projects``, ``~/.claude``…), force-pushing or deleting
|
|
``main``/``master``, deleting a repo, docker volumes, ``mkfs``/``dd`` to a disk;
|
|
* ``exfil`` — a credential (SSH key, Claude login, Gitea token, ``.env``,
|
|
``/proc/*/environ``…) or the whole environment in the same command as a
|
|
network tool aimed at a host outside the lab;
|
|
* ``docker`` — a container that is the host's root: ``--privileged``, the host
|
|
pid namespace, ``/`` or the docker socket mounted, ``nsenter``.
|
|
|
|
A **scoped** run (a guest's) adds the ``guest`` family — docker at all, sudo,
|
|
ssh/scp/rsync to another machine (the owner's keys), the hub and sidecar
|
|
ports on this host, the ``ai-agent`` CLI, other processes' environments, the
|
|
run's git config variables, and a project's own Claude settings (hooks an
|
|
owner's later run there would execute).
|
|
|
|
``--mode block`` (scoped runs) refuses the call: the model reads why. ``--mode
|
|
report`` (the owner's runs) lets it through. Either way the hit goes to the
|
|
hub's security log (``POST /api/security/events``), which pushes the owner
|
|
for the kinds he picked. A pattern list is not a boundary (the sandbox is);
|
|
it stops accidents and naive injected payloads, and it leaves evidence.
|
|
|
|
``post`` (a ``PostToolUse`` hook on Bash, scoped sandboxed runs) reports the
|
|
sandbox's denials it reads in a command's output.
|
|
|
|
An owner's run is never in the way: any failure prints nothing and exits 0.
|
|
A scoped run **fails closed**: if the hook itself breaks before it has
|
|
decided (a broker that raised, input it can't read), the call is refused.
|
|
Stdlib only.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import shlex
|
|
import subprocess
|
|
import sys
|
|
|
|
HOME = os.path.expanduser("~")
|
|
HUB = (os.environ.get("AI_AGENT_URL") or "http://127.0.0.1:8096").rstrip("/")
|
|
|
|
|
|
def _norm(text: str) -> str:
|
|
"""``$HOME``, ``${HOME}`` and the home's absolute path all read ``~``."""
|
|
text = text.replace("${HOME}", "~").replace("$HOME", "~")
|
|
return text.replace(HOME, "~") if HOME and HOME != "/" else text
|
|
|
|
|
|
# ── persistence ──────────────────────────────────────────────────────────────
|
|
_PERSIST_PATHS = [
|
|
("shell-rc", r"~/\.(bashrc|bash_profile|bash_login|bash_logout|profile|zshrc|zprofile|zshenv)\b"),
|
|
("claude-config", r"~/\.claude(-work|-guests/[^/\s]+)?/(settings(\.local)?\.json|hooks\b|CLAUDE\.md)"),
|
|
("systemd", r"(~/\.config/systemd/|/etc/systemd/)"),
|
|
("autostart", r"~/\.config/autostart/"),
|
|
("ssh", r"~/\.ssh/(authorized_keys|config|rc)\b"),
|
|
("git-hooks", r"\.git/hooks/"),
|
|
]
|
|
# A write *to* a path: redirected into, tee'd, copied / moved / linked onto
|
|
# (the path is the last argument), edited in place, opened for writing.
|
|
_WRITE_TO = [
|
|
r"(>>?|\btee\s+(-a\s+)?)\s*[\"']?{p}",
|
|
r"\b(cp|mv|ln|install|rsync)\b[^|;&\n]*\s[\"']?{p}[^\s|;&]*[\"']?\s*($|[;&|\n])",
|
|
r"\bsed\s+(-\w+\s+)*-[a-zA-Z]*i[^|;&\n]*{p}",
|
|
r"\bopen\([^)\n]*{p}[^)\n]*,\s*[\"'][aw]",
|
|
r"\b(write_text|write_bytes)\b[^\n]*{p}|{p}[^\n]*\.(write_text|write_bytes)\(",
|
|
]
|
|
|
|
|
|
def _writes_to(c: str, path_rx: str) -> bool:
|
|
return any(re.search(w.replace("{p}", f"(?:{path_rx})"), c) for w in _WRITE_TO)
|
|
|
|
|
|
_PERSIST_CMDS = [
|
|
("crontab", re.compile(r"\bcrontab\s+(?!-l\b)\S")),
|
|
("systemd-enable", re.compile(r"\bsystemctl\s+--user\s+(enable|link|edit)\b")),
|
|
("git-hooks-path", re.compile(r"\bgit\b[^|;&]*\bconfig\b[^|;&]*\bcore\.hooksPath\b")),
|
|
]
|
|
|
|
# ── destructive ──────────────────────────────────────────────────────────────
|
|
_TOP = r"(~|/|/home|~/(homelab|projects|worktrees|\.claude|\.ssh|\.config|\.local))"
|
|
_RM_RF = re.compile(
|
|
r"\brm\b(?=[^|;&]*\s-(?:[a-zA-Z]*r[a-zA-Z]*f|[a-zA-Z]*f[a-zA-Z]*r|-recursive))"
|
|
r"[^|;&]*?\s[\"']?" + _TOP + r"/?\*?[\"']?(\s|$|;|&|\|)")
|
|
_DESTRUCTIVE_CMDS = [
|
|
("force-push-main", re.compile(
|
|
r"\bgit\s+push\b[^|;&]*(\s(-f|--force(-with-lease)?)\b[^|;&]*\b(main|master)\b"
|
|
r"|\b(main|master)\b[^|;&]*\s(-f|--force(-with-lease)?)\b|\s\+(main|master)\b"
|
|
r"|\s:(main|master)\b|--delete\s+(main|master)\b|--mirror\b)")),
|
|
("repo-delete", re.compile(
|
|
r"\b(gh|tea)\s+repos?\s+delete\b|-X\s*DELETE\b[^|;&]*/repos/")),
|
|
("docker-volumes", re.compile(
|
|
r"\bdocker\s+(volume\s+(rm|prune)|system\s+prune\b[^|;&]*--volumes)")),
|
|
("disk", re.compile(r"\bmkfs(\.\w+)?\s|\bdd\b[^|;&]*\bof=/dev/(sd|nvme|vd|mmcblk)")),
|
|
]
|
|
|
|
# ── exfiltration ─────────────────────────────────────────────────────────────
|
|
_SECRET_PATH = (r"(~/\.ssh/id_[\w.-]*|[\w./~-]*\.credentials\.json|[\w./~-]*homelab-gitea[\w-]*token|"
|
|
r"~/\.config/(tea|gh)/\S*|[\w./~-]*\.git-credentials|~/\.netrc|~/\.aws/\S*|"
|
|
r"/proc/[\w*$]+/environ|[\w./~-]*claude-sidecar\.service|[\w./~-]*\.env(\.[\w.-]+)?)")
|
|
_NET_TOOL = (r"\b(curl|wget|nc|ncat|netcat|socat|scp|sftp|telnet|ftp|ssh|rsync|openssl\s+s_client)\b"
|
|
r"|/dev/(tcp|udp)/")
|
|
# The secret itself leaves: uploaded as a file (curl -d @f / -F x=@f / -T f),
|
|
# fed in (< f), piped from a reader (cat f | curl), copied to a host (scp f h:),
|
|
# or the whole environment piped out.
|
|
_EXFIL = [
|
|
re.compile(r"@" + _SECRET_PATH + r"\b"),
|
|
re.compile(r"(--upload-file|-T)\s+[\"']?" + _SECRET_PATH),
|
|
re.compile(r"(" + _NET_TOOL + r")[^|;&\n]*<\s*[\"']?" + _SECRET_PATH),
|
|
re.compile(r"\b(cat|base64|xxd|gzip|tar|zip|head|tail|openssl\s+enc)\b[^|;&\n]*"
|
|
+ _SECRET_PATH + r"[^|;&\n]*\|[^;&\n]*(" + _NET_TOOL + r")"),
|
|
re.compile(r"\b(scp|rsync)\b[^|;&\n]*" + _SECRET_PATH + r"[^|;&\n]*\s[\w.@-]+:"),
|
|
re.compile(r"\b(env|printenv|set)\s*\|[^;&\n]*(" + _NET_TOOL + r")"),
|
|
re.compile(r"\bopen\([^)\n]*" + _SECRET_PATH + r"[^\n]*(urlopen|requests\.(post|put)|socket)"
|
|
r"|(urlopen|requests\.(post|put)|socket)[^\n]*\bopen\([^)\n]*" + _SECRET_PATH),
|
|
]
|
|
_HOST = re.compile(r"https?://(?:[^/\s'\"`@]+@)?([^/\s'\"`:]+)|(?:^|[\s@])((?:\d{1,3}\.){3}\d{1,3}|"
|
|
r"(?:[\w-]+\.)+[a-z]{2,})(?=[:/\s'\"]|$)|(?:^|[\s;&|(])(?:ssh|scp|rsync)\s[^|;&\n]*?\s(?:[\w.-]+@)?([\w-]+):")
|
|
_LAB_HOST = re.compile(
|
|
r"^(localhost|[\w-]+|.*\.gabvdl\.xyz|.*\.gabriel\.vidal--ayrinhac\.xyz|.*\.ts\.net|"
|
|
r"127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|"
|
|
r"172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+)$")
|
|
# Not hosts, though they look like one: file names a command mentions.
|
|
_NOT_HOST = re.compile(r"\.(json|jsonl|ya?ml|md|txt|py|ts|tsx|js|sh|env|log|toml|lock|html|css|png|jpe?g|webp|svg|service)$")
|
|
|
|
|
|
def _outside_hosts(c: str) -> list[str]:
|
|
hosts = [next(g for g in m.groups() if g) for m in _HOST.finditer(c)]
|
|
return [h for h in hosts if not _LAB_HOST.match(h.lower()) and not _NOT_HOST.search(h.lower())]
|
|
|
|
|
|
# ── docker escapes ───────────────────────────────────────────────────────────
|
|
_DOCKER_RUN = re.compile(r"\b(docker|podman)\s+(container\s+)?(run|create)\b|\bdocker\s+compose\b[^|;&]*\brun\b")
|
|
_DOCKER_ESCAPE = re.compile(
|
|
r"--privileged\b|--pid[= ]host\b|--userns[= ]host\b|--cap-add[= ]?(SYS_ADMIN|ALL)\b|"
|
|
r"(-v|--volume|--mount\s+\S*source=)[= ]?[\"']?(/|/etc|/root|/home|/proc|/sys|~|"
|
|
r"/var/run/docker\.sock|/run/docker\.sock)[\"']?(:|,|\s)")
|
|
|
|
# ── a guest's run only ───────────────────────────────────────────────────────
|
|
_AT_CMD = (r"(?:^|[;&|({`\n]|\$\(|\b(?:then|do|else)\s)\s*"
|
|
r"(?:(?:env|command|nohup|nice|eval|builtin|timeout(?:\s+\S+)?)\s+(?:-\S+\s+)*)*"
|
|
r"(?:\w+=\S*\s+)*(?:time\s+|exec\s+|xargs\s+(?:-\S+\s+)*)?"
|
|
# the program by its path, or backslash-escaped (`/usr/bin/docker`, `\\docker`)
|
|
r"\\?(?:[\w.~-]*/)*")
|
|
# Matched on the command with its quoted strings and heredoc bodies taken
|
|
# out (``which docker``, a ``docker/`` folder or French prose in a script
|
|
# are not the command): what runs is at a command position.
|
|
_GUEST_CMDS = [
|
|
("docker", re.compile(_AT_CMD + r"(sudo\s+)?(?:[\w.~-]*/)*(docker|podman|nerdctl)\b(?!/)")),
|
|
("sudo", re.compile(_AT_CMD + r"(sudo|su|doas|pkexec)\b(\s|$)")),
|
|
("ssh", re.compile(_AT_CMD + r"(ssh|scp|sftp|ssh-add)\s|" + _AT_CMD + r"rsync\b[^|;&\n]*\s[\w.@-]+:")),
|
|
("ai-agent", re.compile(_AT_CMD + r"ai-agent\s")),
|
|
("systemd", re.compile(_AT_CMD + r"(systemctl|journalctl|loginctl|systemd-run)\b")),
|
|
]
|
|
# …and these on the whole text: the hub and the sidecar on this host, other
|
|
# processes' environments, the docker socket.
|
|
_GUEST_ANYWHERE = [
|
|
("hub", re.compile(r"(127(?:\.\d+){1,3}|localhost|0\.0\.0\.0|\b0|172\.17\.0\.1|\[::1\]):['\"]?(8096|8790)\b")),
|
|
# the CLI run around the broker (it would call as the owner): its script,
|
|
# or the command inside a `sh -c '…'`
|
|
("ai-agent", re.compile(r"\bai_agent\.py\b|\s-c\s+['\"]\s*ai-agent\s")),
|
|
("environ", re.compile(r"/proc/[\w*$]+/(environ|cmdline|mem)\b")),
|
|
("docker", re.compile(r"docker\.sock")),
|
|
# the run's git is confined through these (guest_git.py): no owner helper
|
|
("git-config", re.compile(r"\bGIT_CONFIG_(GLOBAL|SYSTEM|NOSYSTEM|COUNT|KEY_\d+|VALUE_\d+)\b")),
|
|
]
|
|
# A project's own Claude config: a scoped run doesn't load it (launch.py
|
|
# `--setting-sources user`), but the owner's next run in that folder would —
|
|
# hooks and MCP servers that run as him.
|
|
_PROJECT_CLAUDE = r"[\w./~-]*(\.claude/settings(\.local)?\.json|\.mcp\.json)"
|
|
|
|
_GUEST_REASONS = {
|
|
"git-config": "changes the git configuration this session runs with",
|
|
"ai-agent": "runs `ai-agent` some other way than as a plain `ai-agent …` command on "
|
|
"its own line — the only way the hub runs it for a guest's session",
|
|
}
|
|
|
|
|
|
# A commit / tag message names paths and tools without touching them.
|
|
_MESSAGE_ONLY = re.compile(r"^\s*(cd\s+[^;&|]+&&\s*)?(git\s+(-C\s+\S+\s+)?(commit|tag|notes)\b)")
|
|
|
|
|
|
_HEREDOC = re.compile(r"<<-?\s*['\"]?(\w+)['\"]?[^\n]*\n.*?\n\s*\1\b", re.S)
|
|
_QUOTED = re.compile(r"'[^']*'|\"(?:[^\"\\]|\\.)*\"", re.S)
|
|
|
|
|
|
def _without_message(c: str) -> str:
|
|
"""A ``git commit``'s command with its message taken out (heredoc bodies
|
|
and quoted strings) — what it *does* is what's left."""
|
|
if not _MESSAGE_ONLY.match(c):
|
|
return c
|
|
return _QUOTED.sub("''", _HEREDOC.sub("<<EOF", c))
|
|
|
|
|
|
def check_command(cmd: str, scoped: bool) -> tuple[str, str] | None:
|
|
"""``(rule, reason)`` for the first rule a Bash command trips, else None."""
|
|
c = _without_message(_norm(cmd or ""))
|
|
for name, rx in _PERSIST_PATHS:
|
|
if _writes_to(c, rx):
|
|
return f"persistence.{name}", "writes where code runs later on its own"
|
|
for name, rx in _PERSIST_CMDS:
|
|
if rx.search(c):
|
|
return f"persistence.{name}", "installs something that runs later on its own"
|
|
if _RM_RF.search(c):
|
|
return "destructive.rm-rf", "recursively deletes a top-level directory"
|
|
for name, rx in _DESTRUCTIVE_CMDS:
|
|
if rx.search(c):
|
|
return f"destructive.{name}", "destroys history or data that can't be recovered"
|
|
if any(rx.search(c) for rx in _EXFIL):
|
|
outside = _outside_hosts(c)
|
|
if outside or not re.search(_HOST, c):
|
|
where = ", ".join(outside[:3]) if outside else "an unknown host"
|
|
return "exfil.credential", f"sends a credential or the environment to {where}"
|
|
if _DOCKER_RUN.search(c) and _DOCKER_ESCAPE.search(c):
|
|
return "docker.escape", "starts a container that is root on the host"
|
|
if re.search(r"\bnsenter\b", c):
|
|
return "docker.nsenter", "enters the host's namespaces"
|
|
if scoped:
|
|
bare = _QUOTED.sub("''", _HEREDOC.sub("<<EOF", c))
|
|
for name, rx in _GUEST_CMDS:
|
|
if rx.search(bare):
|
|
return f"guest.{name}", _GUEST_REASONS.get(name, "isn't open to a guest's session")
|
|
for name, rx in _GUEST_ANYWHERE:
|
|
if rx.search(c):
|
|
return f"guest.{name}", _GUEST_REASONS.get(name, "isn't open to a guest's session")
|
|
if _writes_to(c, _PROJECT_CLAUDE):
|
|
return "guest.claude-config", "writes Claude settings that would run code in a later session"
|
|
return None
|
|
|
|
|
|
def check_path(path: str, scoped: bool = False) -> tuple[str, str] | None:
|
|
"""A file tool's target (Edit / Write…)."""
|
|
p = _norm(path or "")
|
|
for name, rx in _PERSIST_PATHS:
|
|
if re.search(rx, p):
|
|
return f"persistence.{name}", "writes where code runs later on its own"
|
|
if scoped and re.search(_PROJECT_CLAUDE + r"$", p):
|
|
return "guest.claude-config", "writes Claude settings that would run code in a later session"
|
|
return None
|
|
|
|
|
|
# Tools that run a shell command: Bash, and Monitor (its ``command`` "runs in
|
|
# the same shell environment as Bash"; its ``ws`` source opens a socket).
|
|
SHELL_TOOLS = ("Bash", "Monitor")
|
|
|
|
|
|
def shell_text(tool_input: dict) -> str:
|
|
"""What a shell tool is about to run, as one text: its command, and a
|
|
Monitor's WebSocket URL (so the hub's port in it is seen too)."""
|
|
cmd = str(tool_input.get("command") or "")
|
|
ws = tool_input.get("ws")
|
|
url = str(ws.get("url") or "") if isinstance(ws, dict) else ""
|
|
return f"{cmd}\nws {url}" if url else cmd
|
|
|
|
|
|
def check(tool: str, tool_input: dict, scoped: bool) -> tuple[str, str] | None:
|
|
if tool in SHELL_TOOLS:
|
|
return check_command(shell_text(tool_input), scoped)
|
|
if tool in ("Edit", "Write", "MultiEdit", "NotebookEdit"):
|
|
return check_path(str(tool_input.get("file_path") or tool_input.get("notebook_path") or ""),
|
|
scoped)
|
|
return None
|
|
|
|
|
|
# ── sandbox denials (post) ───────────────────────────────────────────────────
|
|
_DENIAL = re.compile(
|
|
r"(Operation not permitted|Read-only file system|Permission denied|"
|
|
r"blocked by (the )?(sandbox|network)|not allowed by (the )?sandbox|"
|
|
r"Connection blocked|403 Forbidden[^\n]*proxy|bwrap: )", re.IGNORECASE)
|
|
|
|
|
|
def denial_in(response) -> str | None:
|
|
text = response if isinstance(response, str) else json.dumps(response or {})
|
|
m = _DENIAL.search(text)
|
|
if not m:
|
|
return None
|
|
start = max(0, m.start() - 120)
|
|
return text[start:m.end() + 80].replace("\\n", " ")
|
|
|
|
|
|
# ── the ai-agent CLI broker (a guest's run) ──────────────────────────────────
|
|
# A plain `ai-agent …` in a scoped run: the hook — outside the session and its
|
|
# sandbox — runs the CLI itself with AIA_AS_SESSION = the run's session id, so
|
|
# the hub answers as the guest the run is for (backend users/cli.py), and
|
|
# hands back what it printed. The CLI runs from its argv, never through a
|
|
# shell: a command a shell would read differently (a pipe, `&&`, a redirect,
|
|
# `$VAR`, `$(…)`) is refused rather than silently meaning something else.
|
|
CLI = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
|
"cli", "ai_agent.py")
|
|
CLI_WAIT_S = 280 # under the hook's timeout (GUARD_BROKER_TIMEOUT_S)
|
|
CLI_OUT_MAX = 12000 # what the model reads back; `show --tail N` for less
|
|
_CLI_HEAD = re.compile(r"^\s*ai-agent(\s|$)")
|
|
_SHELL_PUNCT = ";&|<>()\n"
|
|
_EXPANDS = re.compile(r"\$[\w{(\[]|`")
|
|
_SID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
|
|
|
|
class NotPlain(ValueError):
|
|
pass
|
|
|
|
|
|
def cli_argv(cmd: str) -> list[str] | None:
|
|
"""The argv of a plain ``ai-agent …`` command; None when the command
|
|
isn't an ai-agent call; :class:`NotPlain` when a shell would read it
|
|
differently than its words."""
|
|
if not _CLI_HEAD.match(cmd or ""):
|
|
return None
|
|
s = cmd.strip().replace("\\\n", " ")
|
|
if _EXPANDS.search(re.sub(r"'[^']*'", "''", s)):
|
|
raise NotPlain("it expands something ($VAR, $(…), `…`)")
|
|
lex = shlex.shlex(s, posix=True, punctuation_chars=_SHELL_PUNCT)
|
|
lex.whitespace = " \t"
|
|
lex.whitespace_split = True
|
|
try:
|
|
argv = list(lex)
|
|
except ValueError as e:
|
|
raise NotPlain(str(e)) from None
|
|
if any(t and not t.strip(_SHELL_PUNCT) for t in argv):
|
|
raise NotPlain("it chains, pipes or redirects")
|
|
return argv
|
|
|
|
|
|
def _clip(text: str) -> str:
|
|
if len(text) <= CLI_OUT_MAX:
|
|
return text
|
|
head = CLI_OUT_MAX // 3
|
|
return (f"{text[:head]}\n… {len(text) - CLI_OUT_MAX} characters cut — narrow it "
|
|
f"(`show ID --tail 5`, `ls --limit 10`) …\n{text[-(CLI_OUT_MAX - head):]}")
|
|
|
|
|
|
def run_cli(sid: str, argv: list[str]) -> str:
|
|
"""Run the CLI as the guest of session ``sid`` and say what it printed."""
|
|
if not _SID.match(sid or ""):
|
|
return "ai-agent: no session to act for — not run" # never as the owner
|
|
env = {"PATH": "/usr/bin:/bin", "HOME": HOME, "LANG": "C.UTF-8",
|
|
"AI_AGENT_URL": HUB, "AIA_AS_SESSION": sid, "CLAUDE_SESSION_ID": sid,
|
|
"AIA_GUEST_MAX_WAIT_S": str(CLI_WAIT_S - 40)}
|
|
try:
|
|
p = subprocess.run([sys.executable, "-I", CLI, *argv[1:]], env=env, cwd="/",
|
|
stdin=subprocess.DEVNULL, capture_output=True, text=True,
|
|
timeout=CLI_WAIT_S)
|
|
except subprocess.TimeoutExpired:
|
|
return f"ai-agent: no answer within {CLI_WAIT_S}s — the run goes on; check it with `ai-agent ls --running`"
|
|
except (OSError, ValueError) as e: # ValueError: a NUL or a lone surrogate in an argument
|
|
return f"ai-agent: couldn't run ({e.__class__.__name__}: {e})"
|
|
out = "\n".join(x for x in (p.stdout.strip(), p.stderr.strip()) if x)
|
|
return (f"`ai-agent` ran outside your session (that is why the call shows as "
|
|
f"blocked) — exit {p.returncode}:\n{_clip(out) or '(no output)'}")
|
|
|
|
|
|
def cli_refused(why: str) -> str:
|
|
return (f"ai-agent: not run — {why}. The hub runs the CLI for you only as a plain "
|
|
"`ai-agent …` command on its own: no pipes, `&&`, redirects, variables or "
|
|
"`$(…)`; quote the prompt (single quotes keep it literal, newlines are fine "
|
|
"inside them).")
|
|
|
|
|
|
# ── reporting ────────────────────────────────────────────────────────────────
|
|
def report(event: dict) -> None:
|
|
"""To the hub's security log — on the lab. A worker's runs can't reach the
|
|
hub (it pulls); their hits stay in the hook's stderr for now."""
|
|
if os.environ.get("AI_AGENT_OUTBOX_URL"):
|
|
sys.stderr.write(f"guard: {json.dumps(event)}\n")
|
|
return
|
|
import urllib.request
|
|
req = urllib.request.Request(
|
|
f"{HUB}/api/security/events", data=json.dumps(event).encode(),
|
|
headers={"Content-Type": "application/json"}, method="POST")
|
|
try:
|
|
urllib.request.urlopen(req, timeout=3).read()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _deny(reason: str) -> None:
|
|
print(json.dumps({"hookSpecificOutput": {
|
|
"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
"permissionDecisionReason": reason}}))
|
|
|
|
|
|
def _args(argv: list[str]) -> tuple[str, str]:
|
|
phase = argv[1] if len(argv) > 1 else "pre"
|
|
mode = argv[argv.index("--mode") + 1] if "--mode" in argv[:-1] else "report"
|
|
return phase, mode
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
phase, mode = _args(argv)
|
|
try:
|
|
hook = json.loads(sys.stdin.read() or "{}")
|
|
if not isinstance(hook, dict):
|
|
raise ValueError("not an object")
|
|
except ValueError:
|
|
if mode == "block" and phase == "pre":
|
|
raise # a scoped run fails closed (see __main__)
|
|
return 0
|
|
tool = hook.get("tool_name") or ""
|
|
tool_input = hook.get("tool_input") or {}
|
|
if not isinstance(tool_input, dict):
|
|
tool_input = {}
|
|
shown = str((shell_text(tool_input) if tool in SHELL_TOOLS else "")
|
|
or tool_input.get("file_path") or tool_input.get("notebook_path") or "")[:600]
|
|
base = {"sessionId": hook.get("session_id"), "tool": tool, "input": shown,
|
|
"cwd": hook.get("cwd")}
|
|
if phase == "post":
|
|
if tool == "Bash" and (what := denial_in(hook.get("tool_response"))):
|
|
report({**base, "kind": "sandbox_denial", "rule": "sandbox", "reason": what})
|
|
return 0
|
|
shell = tool in SHELL_TOOLS
|
|
if mode == "block" and shell and not os.environ.get("AI_AGENT_OUTBOX_URL"):
|
|
try:
|
|
argv = cli_argv(str(tool_input.get("command") or ""))
|
|
said = run_cli(hook.get("session_id") or "", argv) if argv else None
|
|
except NotPlain as e:
|
|
said = cli_refused(str(e))
|
|
if said:
|
|
_deny(said)
|
|
return 0
|
|
hit = check(tool, tool_input, scoped=mode == "block")
|
|
if not hit:
|
|
return 0
|
|
rule, reason = hit
|
|
if mode == "block":
|
|
# the refusal first: a report that breaks must not let the call through
|
|
_deny(f"Blocked by the ai-agent guard ({rule}): this command {reason}. "
|
|
"It isn't allowed in this session, so don't try to work around it — "
|
|
"if the task truly needs it, ask the person you're working for.")
|
|
sys.stdout.flush()
|
|
try:
|
|
report({**base, "kind": "guard_block", "rule": rule, "reason": reason})
|
|
except Exception:
|
|
pass
|
|
return 0
|
|
report({**base, "kind": "guard_owner", "rule": rule, "reason": reason})
|
|
return 0
|
|
|
|
|
|
def run(argv: list[str]) -> int:
|
|
""":func:`main`, with the hook's two failure modes: an owner's run is
|
|
never held up by a broken hook (nothing printed, exit 0); a scoped run's
|
|
call is **refused** when the hook broke before deciding — a guard that
|
|
crashes must not be a way past it."""
|
|
try:
|
|
return main(argv)
|
|
except Exception as e:
|
|
try:
|
|
phase, mode = _args(argv)
|
|
except Exception:
|
|
phase, mode = "pre", "report"
|
|
if mode == "block" and phase == "pre":
|
|
_deny("Blocked by the ai-agent guard: it couldn't check this call "
|
|
f"({e.__class__.__name__}). Rephrase the command in plain ASCII, "
|
|
"one step at a time.")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(run(sys.argv))
|