diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index f0467d2..e156eb9 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -59,7 +59,7 @@ { "name": "delivery", "description": "Agents and skills for taking a change from spec to a verified merge through tracker-gated stages.", - "version": "0.1.0", + "version": "0.2.0", "category": "Developer Tools", "source": "./plugins/delivery" }, diff --git a/.gitignore b/.gitignore index 64a54f4..f24683f 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,8 @@ build/ # to the file, not the directory: the sibling .claude-plugin/marketplace.json is # compiled output that IS committed and must stay tracked. /.claude-plugin/plugin.json + +# Python bytecode. plugins/delivery ships a Python hook (.apm/hooks/guard.py); +# apm copies the whole hooks directory, so a stray cache would deploy with it. +__pycache__/ +*.pyc diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6de458c..b7ca9e6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -70,8 +70,8 @@ repos: always_run: true - id: check-executables-allow-sync - name: Check executables allow key sync - description: Verify root apm.yml's executables.allow key names kyberforge's actual version -- apm matches that key by exact "#" lookup, so a version bump on one side alone silently stops deploying kyberforge's hooks/ and bin/ and lets the apm install go stale (see ADR-0019) + name: Check executables allow keys sync + description: Verify root apm.yml's executables.allow carries a "#" key matching the apm.yml version of every plugin that ships executables (plugins//.apm/hooks/ or bin/), reporting every out-of-sync package in one run. apm's grant is version-blind, so a stale key still deploys; this is a record-keeping gate that fails a version bump made without the matching key edit, keeping each key an accurate record of what was approved (see ADR-0019's 2026-09-19 correction and docs/spec/gates.md) entry: bash scripts/check-executables-allow-sync.sh language: system stages: [pre-push] diff --git a/apm.yml b/apm.yml index cf39f47..9bf54fb 100644 --- a/apm.yml +++ b/apm.yml @@ -71,6 +71,10 @@ executables: kyberforge#2.2.1: hooks: true bin: true + # delivery ships the guard hook (ADR-0032 enforcement layer 2). Same + # version-in-key convention as above, kept by the same sync check. + delivery#0.2.0: + hooks: true marketplace: # apm's Claude marketplace mapper only emits description:/version: into the diff --git a/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md b/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md index 918f24d..23f3296 100644 --- a/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md +++ b/docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md @@ -92,6 +92,17 @@ running it in CI on a bot PR hands the bot those credentials. Decided in user) pushes same-repo branches; Gitea runs a `pull_request` workflow from the PR branch's own copy and gives same-repo PRs the repo secrets, so a bot branch can read them. Protected file patterns block the merge, not the run. +- **Accepted risk:** Copilot CLI's TUI auto-approves a hook `ask` (github/copilot-cli#3590, open + since v1.0.53), so on Copilot an odd-job ask may run without a human answer. The owner kept ask + on Copilot rather than deny; Copilot is untested in v1 and the credential boundary still holds. +- The guard hook (`plugins/delivery/.apm/hooks/guard.py`) also checks file-tool paths (Read, Grep, + Edit, Write, Copilot's `view`, Codex's `apply_patch`) against the secret-path globs, not only + shell commands. `kubectl`, `helm`, `flux` and `tofu` are allowlists of subcommands that change no + cluster or state and print no secret: anything not on the list is denied, so an unlisted mutating + subcommand fails safe. Codex cannot ask, so odd jobs are + denied there; an unrecognised runtime is treated the same way. +- *Amended 2026-11-23 ([delivery guard hook](https://git.rkdr.net/Mortis/Holocron/issues/190)): Copilot ask kept + as an accepted risk; the guard covers file tools and uses read-verb allowlists.* - *Amended 2026-11-22 ([Credential boundary setup in ansible-homelab-mono](https://git.rkdr.net/Mortis/Holocron/issues/184)): test paths left the protected file patterns for the test-path check; the Flux dry run became an offline render, and live `kubectl diff` left the Read tier; diff --git a/docs/spec/gates.md b/docs/spec/gates.md index 167e24a..fb04948 100644 --- a/docs/spec/gates.md +++ b/docs/spec/gates.md @@ -55,7 +55,7 @@ Nine hooks, grouped below by what they guard rather than by the order `.pre-comm | Hook | Guards | |---|---| | `check-scope-walkup-sync` | `validate.sh`, `validate-provenance.sh`, `new-agent.sh` and `new-skill.sh`'s four independent `$HOME`/`.git`/`apm.yml` walk-up ports still agree behaviorally | -| `check-executables-allow-sync` | root `apm.yml`'s `executables.allow` key names kyberforge's actual version (see [apm gates](#apm-gates)) | +| `check-executables-allow-sync` | root `apm.yml`'s `executables.allow` carries a `#` key naming the actual version of every plugin that ships executables (`.apm/hooks/` or `bin/`) (see [apm gates](#apm-gates)) | `check-executables-allow-sync` is the odd one in this group: the drift it guards is in a hand-written key rather than in generated text, and it is a record-keeping gate — the grant itself is @@ -1249,22 +1249,32 @@ it is never called with a single key: `install/exec_gate.py` builds a candidate the version-blind name alongside `#`, and `materialize_exec_map` stores every approved key **under its version-blind name as well**. `_map_grants` matches the same three ways. -**Correction (2026-09-19):** verified against apm 0.28.0, a kyberforge version bump therefore does +**Correction (2026-09-19):** verified against apm 0.28.0, a package version bump therefore does *not* stop the entry matching — approving `owner/repo#2.0.0` also covers `owner/repo#2.1.0` through the version-blind alias. The earlier claim here ("no wildcard and no version-less form", so the entry silently stops matching and the `SessionStart` hook stops deploying) described apm's behaviour wrongly, and ADR-0019 carries the same correction. -The gate is still required, for a repo-level reason rather than an apm-level one: -`scripts/check-executables-allow-sync.sh` asserts the key matches `plugins/kyberforge/apm.yml`'s -`version:`, so a bump without a key edit fails *this repo's* pre-push, and the key stays an accurate -record of what was approved. +The gate is still required, for a repo-level reason rather than an apm-level one: it asserts each +key matches its plugin's `version:`, so a bump without a key edit fails *this repo's* pre-push, and +every key stays an accurate record of what was approved. -`scripts/check-executables-allow-sync.sh` parses `version:` out of `plugins/kyberforge/apm.yml` and -asserts root `apm.yml` carries the matching `kyberforge#` key. A comment in the -`executables:` block stays as the human-facing pointer; the hook is what actually holds. It parses -with PyYAML where importable and falls back to a two-shape scan otherwise, so a missing pip package -cannot become the thing that blocks every push. +It covers every plugin that ships executables, not one named package. The script scans +`plugins/*/` and treats a plugin as shipping executables when `plugins//.apm/hooks/` or +`plugins//bin/` exists — kyberforge ships both, delivery ships a guard hook. For each one it +reads `name:` and `version:` from `plugins//apm.yml` and asserts root `apm.yml` carries the +`#` key under `executables.allow`. Keys use the package name, so a `name:` that +differs from the directory name fails rather than being guessed at. Every failing package is +reported in one run, each with its own Why/Fix block; a stale `#` key is quoted +back as "found instead". It also fails on a shipping plugin with no `apm.yml`, a missing `version:`, +a missing root `apm.yml`, or no `executables.allow` mapping. A repo with no executable-shipping +plugin at all is the one no-op, and a plugin with neither directory needs no key. + +A comment in the `executables:` block stays as the human-facing pointer; the hook is what actually +holds. It parses with PyYAML where importable and falls back to a two-shape scan otherwise, so a +missing pip package cannot become the thing that blocks every push. The PyYAML reader refuses an +unquoted two-component version, which YAML reads as a float, instead of comparing a form the reader +invented. ## `.claude/settings.json` diff --git a/plugins/delivery/.apm/hooks/guard.py b/plugins/delivery/.apm/hooks/guard.py new file mode 100755 index 0000000..0c8a188 --- /dev/null +++ b/plugins/delivery/.apm/hooks/guard.py @@ -0,0 +1,1939 @@ +#!/usr/bin/env python3 +"""delivery guard hook: ADR-0032 enforcement layer 2. + +A pre-tool-use hook. It denies the Never tier on every runtime and asks before +Odd-job commands where the runtime honours `ask` (Claude Code, Copilot CLI), +denying them elsewhere. It is a guardrail, not the boundary: credentials the +agent does not hold are the boundary (ADR-0032). Anything this script cannot +see (a script the agent writes then runs, `python -c`, a subprocess, an MCP +tool) gets past it by construction. + +Self-contained on purpose: standard library only, one file, no network. A hook +that fails to start blocks the call on Claude Code (`onFailure: block`) and on +Copilot CLI (non-zero exit denies), so the cost of a broken guard is a stopped +session, never a silent pass, except on Codex, which may let an errored hook's +call through. + +Runtime detection is by where apm deployed this file: + .claude/hooks/... Claude Code ask honoured + .github/hooks/scripts/... Copilot CLI ask honoured (see ADR-0032 risks) + .codex/hooks/... Codex ask unsupported, so deny + anywhere else unknown deny +The payload's shape (camelCase `toolName` or snake_case `tool_name`) picks only +how the payload is read, never the runtime. +""" + +import fnmatch +import json +import os +import re +import sys + +# -------------------------------------------------------------------------- +# Decisions +# -------------------------------------------------------------------------- + +ALLOW, ASK, DENY = "allow", "ask", "deny" +_RANK = {ALLOW: 0, ASK: 1, DENY: 2} + +HANDOFF = ( + " This is an Odd job (ADR-0032): run it only in a HITL session the human " + "started for it; otherwise hand the command to the human." +) + + +class Verdict: + def __init__(self, decision=ALLOW, reason=""): + self.decision = decision + self.reason = reason + + def merge(self, other): + if _RANK[other.decision] > _RANK[self.decision]: + return other + return self + + +def deny(reason): + return Verdict(DENY, "delivery guard: Never tier (ADR-0032). " + reason) + + +def ask(reason): + return Verdict(ASK, "delivery guard: " + reason + HANDOFF) + + +OK = Verdict() + +HOOK_BYPASS = "never bypass the repo's gates." + +# Copilot lets a timed-out hook's call through, so the guard refuses input too +# big to read quickly instead of trying. +MAX_COMMAND = 256 * 1024 +# Bounds that keep the guard linear on pathological input: words in one simple +# command, and wrappers unwrapped inside one another (`sudo sudo sudo …`). +MAX_WORDS = 2000 +MAX_COMMANDS = 5000 +MAX_UNWRAP = 32 + +# -------------------------------------------------------------------------- +# Secret material: paths an agent never reads +# -------------------------------------------------------------------------- + +SECRET_BASENAME_GLOBS = ( + ".vault_pass*", ".vault-pass*", + "*.tfstate", "*.tfstate.*", + "id_rsa*", "id_dsa*", "id_ecdsa*", "id_ed25519*", + "*.key", "key.pem", "*-key.pem", "*_key.pem", "*.key.pem", "privkey*.pem", + "*private*.pem", "*.p12", "*.pfx", ".git-credentials*", +) +# Names that also fit source and docs about the secret (`vault_password.yml`, +# `test_vault_password.py`). A doc or data suffix exempts them. A code suffix +# exempts only a test file: `vault_pass.py` / `vault-pass.sh` is the usual name +# of an Ansible vault-password script, and running it prints the password. +SECRET_NAME_GLOBS = ("vault_pass*", "vault-pass*", "*vault_password*", + "*vault-password*", "*deploy_key*") +DOC_SUFFIXES = (".yml", ".yaml", ".md", ".rst", ".j2", ".adoc", ".html") +CODE_SUFFIXES = (".py", ".sh", ".go", ".rs", ".js", ".ts") + + +def _is_doc_or_test(base): + if base.endswith(DOC_SUFFIXES): + return True + if base.endswith(CODE_SUFFIXES): + stem = base.rsplit(".", 1)[0] + return stem.startswith(("test_", "test-")) or stem.endswith(("_test", "-test")) + return False +# Secret files whose basename alone is too common to match on. +SECRET_PATH_SUFFIXES = ("/sops/age/keys.txt", "/rancher/k3s/k3s.yaml", + "/kubernetes/admin.conf") +# Directories whose contents are secret as a whole: naming the directory, or +# any glob inside it, counts. +SECRET_DIRS = (".kube", ".ssh") +# Representative secret names, used to decide whether a shell glob the agent +# wrote (`cat .vault_pa*`) could expand to secret material. +SECRET_SAMPLES = ( + ".vault_pass", ".vault-pass", "vault_pass.txt", "vault_password", + ".vault_password_file", "terraform.tfstate", "terraform.tfstate.backup", + "id_rsa", "id_ed25519", "id_ecdsa", "server.key", "privkey.pem", + "tls-key.pem", "sealed-secrets-key.pem", "cert.p12", ".git-credentials", + "deploy_key", +) +GLOB_CHARS = set("*?[") + + +def _literal_count(pattern): + return sum(1 for ch in pattern if ch not in "*?[]!") + + +def is_secret_path(word): + if not word: + return False + candidates = {word} + # --flag=value, NAME=value, curl's @file + if "=" in word: + candidates.add(word.rsplit("=", 1)[1]) + if word.startswith("@"): + candidates.add(word[1:]) + # git's REV:path (`git show HEAD:.vault_pass`) + if ":" in word: + candidates.add(word.split(":", 1)[1]) + for cand in candidates: + norm = cand.strip().replace("\\", "/").rstrip("/") + if not norm: + continue + parts = norm.split("/") + base = parts[-1].lower() + parent = parts[-2].lower() if len(parts) > 1 else "" + if base in SECRET_DIRS: + return True + if parent in SECRET_DIRS and GLOB_CHARS & set(base): + return True + # the admin kubeconfig and its backups; other kubeconfigs are fine + if parent == ".kube" and (base == "config" or base.startswith("config.") + or base == "config~"): + return True + if ("/" + norm.lower()).endswith(SECRET_PATH_SUFFIXES): + return True + if base.endswith(".pub"): + continue + if any(fnmatch.fnmatchcase(base, g) for g in SECRET_BASENAME_GLOBS): + return True + if not _is_doc_or_test(base) and \ + any(fnmatch.fnmatchcase(base, g) for g in SECRET_NAME_GLOBS): + return True + if GLOB_CHARS & set(base) and len(base) < 256 and _literal_count(base) >= 3: + if any(fnmatch.fnmatchcase(s, base) for s in SECRET_SAMPLES): + return True + return False + + +HOOKS_DIR = re.compile(r"(?:^|/)\.git/hooks(?:/|$)") + + +def is_hooks_path(word): + return bool(HOOKS_DIR.search(word.replace("\\", "/"))) + + +# -------------------------------------------------------------------------- +# Shell tokenising +# -------------------------------------------------------------------------- + +# Longest first, so `&&` wins over `&` and `<<<` over `<<`. +OPERATORS = re.compile(r"&&|\|\||;;|\|&|[;|&\n()]") +REDIRECTS = re.compile(r"<<<|<<-|<<|&>>|>>|&>|>&|<&|<>|>\||[<>]") +WORD_END = set(" \t\r\n;&|()<>") +# Runs of characters with no special meaning inside a word. +PLAIN = re.compile(r"[^\s;&|()<>\\'\"`$@{]+") +PS_PLAIN = re.compile(r"[^\s;&|()<>`'\"$@{]+") +FD_PREFIX = re.compile(r"[0-9]+(?=[<>])") +PS_FD_PREFIX = re.compile(r"(?:[0-9]+|\*)(?=>)") +VAR_START = re.compile(r"[A-Za-z_{0-9@*#?!$-]") +MAX_NESTING = 40 + + +class TooComplex(Exception): + pass + + +class Word(str): + """A shell word after unquoting. + + dynamic: it still holds an expansion, so its value is only known at run + time. brace: its unquoted text has a brace expansion (`{a,b}`, `{1..3}`). + """ + dynamic = False + brace = False + + def __new__(cls, text, dynamic=False, brace=False): + word = str.__new__(cls, text) + word.dynamic = dynamic + word.brace = brace + return word + + +def _has_brace(text): + # Linear: an opening brace, then a comma or `..`, then the closing brace, + # with no other brace between. + if "{" not in text: + return False + open_, list_, prev = False, False, "" + for ch in text: + if ch == "{": + open_, list_ = True, False + elif ch == "}": + if open_ and list_: + return True + open_ = False + elif open_ and (ch == "," or (ch == "." and prev == ".")): + list_ = True + prev = ch + return False + + +class Command: + """One simple command: its words, its redirections, and what it reads on + stdin from here-documents and here-strings.""" + + def __init__(self): + self.words = [] + self.redirects = [] # (operator, target word) + self.stdin = [] + + +class Shell: + """Splits a command line into simple commands. + + Not a full shell parser. It understands quoting, escapes, the control + operators, redirections, here-documents, arithmetic and command / process + substitution. A substitution's body is parsed by a nested Shell over the + same text, so the end of `$(...)` is found by the same rules as the rest + of the line, here-documents included. Here-document bodies are data, + except that an unquoted delimiter's body still runs its substitutions. + `ps` switches to PowerShell quoting: backtick escapes, backslash does not. + """ + + def __init__(self, text, ps=False, depth=0, arith=False, start=0): + if depth > MAX_NESTING: + raise TooComplex() + self.text = text + self.ps = ps + self.depth = depth + self.arith = arith # inside (( )) or $(( )): no commands, no here-docs + self.i = start + self.commands = [] + self.nested = [] # Shells of substitutions and here-doc bodies + self.pending = [] # here-docs whose bodies start at the next newline + + def _child(self, start, arith=False): + return Shell(self.text, self.ps, self.depth + 1, arith, start) + + def parse(self, closer=False): + """Parse to the end, or with closer=True to the first unmatched ')'.""" + text, n = self.text, len(self.text) + cur = Command() + parens = 0 + while self.i < n: + c = text[self.i] + if c in " \t\r": + self.i += 1 + continue + if text.startswith("`\n" if self.ps else "\\\n", self.i): + self.i += 2 + continue + if c == "#" and self._at_word_start(): + end = text.find("\n", self.i) + self.i = n if end == -1 else end + continue + if self.ps and text.startswith("<#", self.i): + end = text.find("#>", self.i) + self.i = n if end == -1 else end + 2 + continue + if text.startswith("((", self.i) and not (cur.words or self.ps or self.arith): + self._arith(self.i + 2) + continue + op = self._match(OPERATORS) + if op: + self.i += len(op) + if op == "(": + parens += 1 + elif op == ")": + if parens == 0 and closer: + break + parens = max(0, parens - 1) + elif op == "\n" and self.pending: + self._read_heredocs() + self._end(cur) + cur = Command() + continue + if not self.ps and text.startswith(("<(", ">("), self.i): + self._nest(self.i + 2) + cur.words.append(Word("/dev/fd/63", dynamic=True)) + continue + fd = (PS_FD_PREFIX if self.ps else FD_PREFIX).match(text, self.i) + if fd: + self.i = fd.end() + red = self._match(REDIRECTS) + if red: + self.i += len(red) + self._redirect(red, cur) + continue + cur.words.append(self._word()) + if len(cur.words) > MAX_WORDS: + raise TooComplex() + self._end(cur) + return self + + def _end(self, cmd): + if cmd.words or cmd.redirects or cmd.stdin: + self.commands.append(cmd) + if len(self.commands) > MAX_COMMANDS: + raise TooComplex() + + def _nest(self, start, arith=False): + sub = self._child(start, arith).parse(closer=True) + self.nested.append(sub) + self.i = sub.i + return sub + + def _arith(self, start): + # (( ... )) / $(( ... )): `<<` is a shift, not a here-doc + self._nest(start, arith=True) + if self.text.startswith(")", self.i): + self.i += 1 + + def _redirect(self, red, cmd): + if self.arith: + return + while self.i < len(self.text) and self.text[self.i] in " \t": + self.i += 1 + start = self.i + target = self._word() + if red in ("<<", "<<-") and not self.ps: + raw = self.text[start:self.i] + expands = not any(q in raw for q in "'\"\\") + self.pending.append((str(target), red == "<<-", expands, cmd)) + elif red == "<<<": + cmd.stdin.append(target) + else: + cmd.redirects.append((red, target)) + + def _read_heredocs(self): + text, n = self.text, len(self.text) + for delim, strip_tabs, expands, cmd in self.pending: + lines = [] + while self.i < n: + end = text.find("\n", self.i) + end = n if end == -1 else end + line = text[self.i:end] + self.i = min(end + 1, n) + if (line.lstrip("\t") if strip_tabs else line) == delim: + break + lines.append(line) + body = "\n".join(lines) + cmd.stdin.append(body) + if expands: + sub = Shell(body, self.ps, self.depth + 1) + sub._dquote(None) + self.nested.append(sub) + self.pending = [] + + def _at_word_start(self): + return self.i == 0 or self.text[self.i - 1] in " \t\n;&|()" + + def _match(self, ops): + m = ops.match(self.text, self.i) + return m.group() if m else None + + def _substitution(self): + # self.i is at "$(" (bash or PowerShell) + if not self.ps and self.text.startswith("$((", self.i): + self._arith(self.i + 3) + else: + self._nest(self.i + 2) + + def _backtick(self): + text, n = self.text, len(self.text) + j = self.i + 1 + out = [] + while j < n and text[j] != "`": + if text[j] == "\\" and j + 1 < n: + out.append(text[j + 1] if text[j + 1] in "$`\\" else text[j:j + 2]) + j += 2 + continue + out.append(text[j]) + j += 1 + self.i = j + 1 + self.nested.append(Shell("".join(out), self.ps, self.depth + 1).parse()) + + def _dquote(self, stop): + """Read double-quoted text (or a here-doc body, stop=None) up to stop. + + Returns (text, dynamic). Substitutions inside are parsed as nested. + """ + text, n = self.text, len(self.text) + esc = "`" if self.ps else "\\" + out = [] + dynamic = False + while self.i < n: + d = text[self.i] + if stop and d == stop: + if self.ps and text.startswith(stop * 2, self.i): + out.append(stop) + self.i += 2 + continue + self.i += 1 + break + if d == esc and self.i + 1 < n: + nxt = text[self.i + 1] + if self.ps or nxt in '"\\$`\n': + if nxt != "\n": + out.append(nxt) + self.i += 2 + continue + if text.startswith("$(", self.i): + self._substitution() + dynamic = True + continue + if d == "`" and not self.ps: + self._backtick() + dynamic = True + continue + if d == "$" and self.i + 1 < n and VAR_START.match(text[self.i + 1]): + dynamic = True + out.append(d) + self.i += 1 + return "".join(out), dynamic + + def _single(self): + # self.i is at the opening quote; PowerShell doubles a quote to escape it + text, n = self.text, len(self.text) + out = [] + j = self.i + 1 + while True: + end = text.find("'", j) + if end == -1: + out.append(text[j:]) + self.i = n + return "".join(out) + out.append(text[j:end]) + if self.ps and text.startswith("''", end): + out.append("'") + j = end + 2 + continue + self.i = end + 1 + return "".join(out) + + def _ansi_c(self): + # $'...': backslash escapes, including \' + text, n = self.text, len(self.text) + j = self.i + 2 + while j < n and text[j] != "'": + j += 2 if text[j] == "\\" else 1 + raw = text[self.i + 2:min(j, n)] + self.i = j + 1 + try: + return raw.encode("latin-1", "backslashreplace").decode("unicode_escape") + except Exception: + return raw + + def _ps_herestring(self): + # @' ... '@ and @" ... "@: the terminator sits at the start of a line + quote = self.text[self.i + 1] + start = self.i + 2 + end = self.text.find("\n" + quote + "@", start) + end = len(self.text) if end == -1 else end + body = self.text[start:end] + self.i = end + 3 + if quote == "'": + return body, False + sub = Shell(body, True, self.depth + 1) + out, dynamic = sub._dquote(None) + self.nested.append(sub) + return out, dynamic + + def _word(self): + text, n = self.text, len(self.text) + out = [] + unquoted = [] + dynamic = False + plain = PS_PLAIN if self.ps else PLAIN + while self.i < n: + run = plain.match(text, self.i) + if run: + out.append(run.group()) + unquoted.append(run.group()) + self.i = run.end() + continue + c = text[self.i] + if c in WORD_END: + break + if self.ps and c == "`" or not self.ps and c == "\\": + if self.i + 1 < n and text[self.i + 1] != "\n": + out.append(text[self.i + 1]) + self.i += 2 # an escaped newline is a line continuation + elif c == "'": + out.append(self._single()) + elif c == '"' or (not self.ps and text.startswith('$"', self.i)): + self.i += 1 if c == '"' else 2 + part, dyn = self._dquote('"') + out.append(part) + dynamic = dynamic or dyn + elif self.ps and text.startswith(("@'", '@"'), self.i): + part, dyn = self._ps_herestring() + out.append(part) + dynamic = dynamic or dyn + elif not self.ps and text.startswith("$'", self.i): + out.append(self._ansi_c()) + elif text.startswith("$(", self.i): + self._substitution() + dynamic = True + elif c == "`" and not self.ps: + self._backtick() + dynamic = True + else: + if c == "$" and self.i + 1 < n and VAR_START.match(text[self.i + 1]): + dynamic = True + out.append(c) + unquoted.append(c) + self.i += 1 + return Word("".join(out), dynamic, _has_brace("".join(unquoted))) + + +# -------------------------------------------------------------------------- +# Unwrapping: find the program a simple command really runs +# -------------------------------------------------------------------------- + +SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "fish"} +SHELL_VALUE_OPTS = {"-o", "+o", "-O", "+O", "--rcfile", "--init-file"} +PWSH = {"powershell", "pwsh"} +PWSH_VALUE_OPTS = {"-executionpolicy", "-ep", "-ex", "-workingdirectory", "-wd", + "-windowstyle", "-w", "-outputformat", "-of", "-o", + "-inputformat", "-if", "-i", "-configurationname", "-version", + "-v", "-settingsfile", "-psconsolefile"} +EVALS = {"eval", "iex", "invoke-expression"} +# Words that only prefix the real command. Matched on the basename, so +# /usr/bin/time and /usr/bin/nohup count. +KEYWORDS = {"!", "{", "}", "then", "do", "done", "else", "elif", "if", "while", + "until", "time", "coproc", "exec", "command", "builtin", "nohup", + "setsid", "chronic", "unbuffer", "caffeinate"} +KEYWORD_VALUE_OPTS = {("exec", "-a"), ("time", "-f"), ("time", "-o"), + ("time", "--format"), ("time", "--output")} +# wrapper -> options that consume the next word +WRAPPERS = { + "env": {"-u", "--unset", "-C", "--chdir", "-S", "--split-string"}, + "sudo": {"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "-T", "--user", + "--group", "--chdir", "--host", "--prompt", "--role", "--type"}, + "doas": {"-u", "-C"}, + "nice": {"-n", "--adjustment"}, + "ionice": {"-c", "-n", "-p"}, + "timeout": {"-s", "--signal", "-k", "--kill-after"}, + "stdbuf": {"-i", "-o", "-e"}, + "xargs": {"-I", "-L", "-n", "-P", "-s", "-d", "-E", "-a", "--replace", + "--max-lines", "--max-args", "--max-procs", "--max-chars", + "--delimiter", "--eof", "--arg-file"}, + "watch": {"-n", "--interval", "-d"}, + "strace": {"-o", "-e", "-p", "-s", "-u"}, + "ltrace": {"-o", "-e", "-p", "-s", "-u"}, + "taskset": set(), + "chrt": set(), + "flock": {"-w", "-E", "--timeout", "--conflict-exit-code"}, + "unshare": set(), + "systemd-run": {"-p", "--property", "-u", "--unit", "-E", "--setenv"}, + "su": {"-s", "--shell", "-g", "--group"}, + "runuser": {"-u", "-g", "-s"}, + "script": {"-c", "--command"}, + "parallel": {"-j", "--jobs", "-S", "--sshlogin", "--joblog", "-a", + "--arg-file", "--delay", "--timeout", "-I", "--colsep"}, + "ssh": {"-B", "-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", + "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w"}, + "chroot": {"--userspec", "--groups"}, +} +# Tool runners: ... args. The program is the +# first word the guard knows, or whatever follows `--`. +RUNNERS = { + "uv": {"run", "tool"}, "poetry": {"run"}, "pipenv": {"run"}, "pdm": {"run"}, + "hatch": {"run"}, "pipx": {"run"}, "direnv": {"exec"}, "mise": {"exec", "x"}, + "devbox": {"run"}, "uvx": None, "aws-vault": {"exec"}, "op": {"run"}, + "doppler": {"run"}, +} +# Distributions that bundle a tool as a subcommand: `k3s kubectl ...`. +BUNDLES = {"busybox", "k3s", "microk8s"} +TMUX_RUN = {"new-session", "new", "new-window", "neww", "split-window", "splitw", + "respawn-pane", "respawnp", "respawn-window", "respawnw"} +TMUX_VALUE_OPTS = {"-s", "-n", "-c", "-x", "-y", "-t", "-e", "-F", "-l", "-f"} +ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=") +# Assignments whose value is a command line git runs. +COMMAND_VARS = {"GIT_SSH_COMMAND"} +GUARDED = re.compile( + r"(? 1: + idx += 1 + elif prog == "yq" and a in YQ_SUBS: + idx += 1 + else: + return {idx} + return set() + + +# Options whose value is prose: a title, a body, release notes. +MESSAGE_OPTS = { + "gh": {"-t", "--title", "-b", "--body", "-n", "--notes", "--subject"}, + "tea": {"-t", "--title", "-d", "--description", "--body"}, +} +# Programs that only print their arguments or look at file metadata. +NEUTRAL = {"echo", "printf", "ls", "stat", "test", "[", "[[", "true", ":"} +# Programs that hand a key to ssh rather than print it. +SSH_KEY_USERS = {"scp", "sftp"} +# Programs that change the files they name. Copiers change only the last one. +HOOK_WRITERS = {"rm", "rmdir", "unlink", "shred", "mv", "chmod", "chown", + "chgrp", "truncate", "tee", "sed"} +HOOK_COPIERS = {"cp", "ln", "install", "rsync"} + + +def _takes_value(word, takes_value): + """True when the option word consumes the next word: it is a value option, + or a short cluster (`-iu`) whose last letter is one.""" + if word in takes_value: + return True + return (len(word) > 2 and word[0] == "-" and word[1] != "-" + and "-" + word[-1] in takes_value) + + +def prog_name(word, ps=False): + base = os.path.basename(word.replace("\\", "/")) + low = base.lower() + if low.endswith(".exe"): + return low[:-4] + return low if ps else base + + +def option_values(args, opts): + """Indexes of the values of `opts`: the next word, or an inline value.""" + found = set() + for idx, a in enumerate(args): + if a in opts: + found.add(idx + 1) + elif "=" in a and a.split("=", 1)[0] in opts: + found.add(idx) + elif len(a) > 2 and a[:2] in opts and not a.startswith("--"): + found.add(idx) + return found + + +def search_pattern_indexes(args, value_opts): + """Indexes of args that are a search pattern rather than a file.""" + explicit = any(a in ("-e", "--regexp", "-f", "--file") or + a.startswith(("--regexp=", "--file=")) for a in args) + skip = set() + idx = 0 + while idx < len(args): + a = args[idx] + if a in ("-e", "--regexp") and idx + 1 < len(args): + skip.add(idx + 1) + idx += 2 + continue + if a in value_opts: + skip.add(idx + 1) + idx += 2 + continue + if a == "--": + if not explicit and idx + 1 < len(args): + skip.add(idx + 1) + break + if not a.startswith("-"): + if not explicit: + skip.add(idx) + break + idx += 1 + return skip + + +def exempt_indexes(prog, args): + """Indexes of args that name no file (patterns, prose, values a tool reads + itself), or None when the program's arguments are never read as files.""" + if prog == "git": + sub_idx = _git_sub_index(args) + if sub_idx is None: + return option_values(args, {"-c"}) + sub = args[sub_idx] + if sub in ("rm", "check-ignore", "ls-files", "status"): + return None + skip = option_values(args[:sub_idx], {"-c"}) + rest = args[sub_idx + 1:] + inner = set() + if sub == "grep": + inner = search_pattern_indexes(rest, SEARCH_VALUE_OPTS) + elif sub in GIT_MESSAGE_SUBS: + inner = _git_message_indexes(rest) + return skip | {i + sub_idx + 1 for i in inner} + if prog in SEARCHERS: + value_opts = SEARCH_VALUE_OPTS | ({"-T"} if prog == "rg" else set()) + return search_pattern_indexes(args, value_opts) | option_values(args, SEARCH_GLOB_OPTS) + if prog in MESSAGE_OPTS: + return option_values(args, MESSAGE_OPTS[prog]) + if prog == "find": + if _find_acts(args): + return set() # it deletes or runs something: every name counts + return option_values(args, FIND_PATTERN_OPTS) + if prog in ANSIBLE_RUNS: + return option_values(args, SECRET_ARG_EXEMPT) + if prog in JQ_LIKE: + return _jq_filter_index(prog, args) + if prog in ("pytest", "py.test") or (prog.startswith("python") and + args[:2] == ["-m", "pytest"]): + return option_values(args, {"-k", "-m"}) + if prog in SSH_KEY_USERS: + return option_values(args, {"-i"}) + if prog == "ssh-add": + return None + return set() + + +def secret_words(prog_word, prog, args): + if prog in NEUTRAL: + return OK + if is_secret_path(prog_word): + return deny("'%s' is secret material; agents never run or read it." % prog_word) + skip = exempt_indexes(prog, args) + if skip is None: + return OK + for idx, w in enumerate(args): + if idx in skip: + continue + if w.startswith("-"): + # an option name is never a path; only an inline value can be + if "=" not in w: + continue + w = w.split("=", 1)[1] + if is_secret_path(w): + return deny("'%s' is secret material (vault password, private key, " + "admin kubeconfig or tofu state); agents never read, copy " + "or commit it." % w) + return OK + + +def _find_acts(args): + return any(a in FIND_ACTIONS for a in args) + + +def hook_writes(prog, args): + if prog == "find" and _find_acts(args): + targets = args + elif prog in HOOK_WRITERS: + if prog == "sed" and not any(a.startswith(("-i", "--in-place")) for a in args): + return OK + targets = [a for a in args if not a.startswith("-")] + elif prog in HOOK_COPIERS: + targets = [a for a in args if not a.startswith("-")][-1:] + else: + return OK + for t in targets: + if is_hooks_path(t): + return deny("Changing '%s' turns the repo's git hooks off; %s" % (t, HOOK_BYPASS)) + return OK + + +def redirect_verdict(redirects): + for op, target in redirects: + if op in (">&", "<&") and (target.isdigit() or target == "-"): + continue + if op != "<" and is_hooks_path(target): + return deny("Writing '%s' changes the repo's git hooks; %s" % (target, HOOK_BYPASS)) + if is_secret_path(target): + return deny("'%s' is secret material; agents never read or write it." % target) + return OK + + +class Ctx: + """What a simple command carries besides its words. + + guarded: the line it came from mentions a guarded tool or secret, so a + part the guard cannot read is denied rather than allowed. + stdin: here-doc bodies and here-strings the command reads. + """ + + def __init__(self, guarded=True, stdin=(), ps=False): + self.guarded = guarded + self.stdin = stdin + self.ps = ps + + +class Analyzer: + def __init__(self): + self.depth = 0 + self.unwraps = 0 + + def text(self, command, ps=False, guarded=False): + """Verdict for a whole command line.""" + if len(command) > MAX_COMMAND: + return deny("The command is longer than %d KB, too long for the guard " + "to read; split it up." % (MAX_COMMAND // 1024)) + if self.depth > 8: + return deny("Command nesting too deep for the guard to read; simplify it.") + self.depth += 1 + try: + try: + sh = Shell(command, ps).parse() + except (TooComplex, RecursionError): + return deny("The command is too long or nested too deep for the guard " + "to read (over %d words in one command, %d commands, or %d " + "levels); simplify it." % (MAX_WORDS, MAX_COMMANDS, MAX_NESTING)) + return self.tree(sh, guarded or bool(GUARDED.search(command))) + finally: + self.depth -= 1 + + def tree(self, sh, guarded): + verdict = OK + if not sh.arith: + for cmd in sh.commands: + verdict = verdict.merge(self.simple(cmd, Ctx(guarded, cmd.stdin, sh.ps))) + if verdict.decision == DENY: + return verdict + for sub in sh.nested: + verdict = verdict.merge(self.tree(sub, guarded)) + if verdict.decision == DENY: + return verdict + return verdict + + def simple(self, cmd, ctx): + if any(w.brace for w in cmd.words) and GUARDED.search(" ".join(cmd.words)): + return deny("Brace expansion hides what this command runs; write it " + "out literally.") + verdict = redirect_verdict(cmd.redirects) + if verdict.decision == DENY: + return verdict + return verdict.merge(self.program(cmd.words, ctx)) + + def assignment(self, word, ctx): + name, value = word.split("=", 1) + name = name.rstrip("+") + low = value.lower() + if name == "SKIP": + return deny("SKIP= skips pre-commit hooks; " + HOOK_BYPASS) + if name in ("HUSKY", "LEFTHOOK") and value in ("0", "false"): + return deny("%s=0 skips the repo's git hooks; %s" % (name, HOOK_BYPASS)) + if "hookspath" in low or (name.startswith("GIT_CONFIG") and "no-verify" in low): + return deny("Overriding core.hooksPath skips the repo's git hooks; " + HOOK_BYPASS) + if name in COMMAND_VARS: + return self.text(value, guarded=ctx.guarded) + if is_secret_path(value): + return deny("'%s' is secret material; agents never read it." % value) + return OK + + def program(self, words, ctx): + if len(words) > MAX_WORDS: + return deny("The command has more than %d words, too many for the guard " + "to read; split it up." % MAX_WORDS) + if self.unwraps >= MAX_UNWRAP: + return deny("Too many wrappers inside one another for the guard to read; " + "simplify the command.") + self.unwraps += 1 + try: + return self._program(words, ctx) + finally: + self.unwraps -= 1 + + def _program(self, words, ctx): + verdict = OK + # Walk past assignments and keywords by index: slicing at each step + # is quadratic on a long run of `! ! ! …`. + i, n = 0, len(words) + while i < n: + if ASSIGNMENT.match(words[i]): + verdict = verdict.merge(self.assignment(words[i], ctx)) + i += 1 + continue + head = prog_name(words[i], ctx.ps) + if head == "function" and i + 1 < n: + i += 2 # function NAME { ... + continue + if head not in KEYWORDS: + break + i += 1 + if head == "command" and i < n and words[i] in ("-v", "-V"): + return verdict + if head == "coproc" and i + 1 < n and words[i + 1] == "{": + i += 1 + while i < n and words[i].startswith("-") and len(words[i]) > 1: + opt = words[i] + i += 1 + if opt == "--": + break + if (head, opt) in KEYWORD_VALUE_OPTS: + i += 1 + if verdict.decision == DENY: + return verdict + words = words[i:] + if not words or verdict.decision == DENY: + return verdict + prog_word = words[0] + if prog_word.dynamic: + # The program name is only known at run time. Fail safe when the + # line mentions a guarded tool at all. + if ctx.guarded: + return deny("The program name is built at run time ('%s'), so the guard " + "cannot classify this command. Write the command out literally." + % prog_word) + return verdict + if GLOB_CHARS & set(prog_word): + return deny("The program name '%s' is a glob; write it out literally." % prog_word) + prog = prog_name(prog_word, ctx.ps) + args = words[1:] + + if prog in ("export", "declare", "typeset", "local", "readonly"): + for a in args: + if ASSIGNMENT.match(a): + verdict = verdict.merge(self.assignment(a, ctx)) + return verdict + if prog in SHELLS: + return verdict.merge(self.shell(args, ctx)) + if prog in PWSH: + return verdict.merge(self.powershell(args, ctx)) + if prog == "cmd": + for idx, a in enumerate(args): + if a.lower() in ("/c", "/k", "/r"): + return verdict.merge(self.text(" ".join(args[idx + 1:]), + guarded=ctx.guarded)) + return verdict + if prog in EVALS: + if any(a.dynamic for a in args) and ctx.guarded: + return deny("'%s' runs a string built at run time; write the command " + "out literally." % prog) + return verdict.merge(self.text(" ".join(args), ctx.ps, ctx.guarded)) + if prog in ("source", "."): + if any(a.dynamic for a in args) and ctx.guarded: + return deny("'%s' runs a script built at run time; run the command " + "directly." % prog) + if prog == "trap": + rest = [a for a in args if not a.startswith("-")] + return verdict.merge(self.text(rest[0], guarded=ctx.guarded) if rest else OK) + if prog in WRAPPERS: + return verdict.merge(self.wrapper(prog, args, ctx)) + if prog in BUNDLES and args: + return verdict.merge(self.program(args, ctx)) + if prog == "find": + verdict = verdict.merge(self.find_exec(args)) + if verdict.decision == DENY: + return verdict + if prog == "rtk": + return verdict.merge(self.rtk(args, ctx)) + if prog in RUNNERS: + return verdict.merge(self.runner(prog, args, ctx)) + if prog in ("nix-shell", "nix", "tmux"): + return verdict.merge(self.launcher(prog, args, ctx)) + + verdict = verdict.merge(secret_words(prog_word, prog, args)) + verdict = verdict.merge(hook_writes(prog, args)) + rule = RULES.get(prog) + if rule: + verdict = verdict.merge(rule(args, self)) + return verdict + + def stdin_script(self, ctx, who): + """A program that reads its commands from stdin.""" + if ctx.stdin: + verdict = OK + for doc in ctx.stdin: + verdict = verdict.merge(self.text(doc, guarded=ctx.guarded)) + return verdict + if ctx.guarded: + return deny("%s reading commands from stdin hides what it runs; run the " + "command directly." % who) + return OK + + def shell(self, args, ctx): + # Options come first. In a cluster (`-euo pipefail`), a last letter + # that takes a value consumes the next word. With -c, the command + # string is the first word after the options. + idx = 0 + from_stdin = has_c = False + while idx < len(args): + a = args[idx] + if a in SHELL_VALUE_OPTS: + idx += 2 + continue + if a == "--": + idx += 1 + break + if a.startswith("--"): + idx += 1 + continue + if a[:1] in "-+" and len(a) > 1: + has_c = has_c or "c" in a[1:] + from_stdin = from_stdin or "s" in a[1:] + idx += 2 if a[-1] in "oO" else 1 + continue + break + rest = args[idx:] + if has_c: + if not rest: + return OK + if rest[0].dynamic and ctx.guarded: + return deny("The shell runs a string built at run time; write " + "the command out literally.") + return self.text(rest[0], guarded=ctx.guarded) + if from_stdin or not rest or rest[0] == "-": + return self.stdin_script(ctx, "A shell") + if rest[0].dynamic and ctx.guarded: + return deny("The shell runs a script built at run time; run the command " + "directly.") + if is_secret_path(rest[0]): + return deny("'%s' is secret material; agents never run or read it." % rest[0]) + return OK + + def powershell(self, args, ctx): + idx = 0 + while idx < len(args): + a = args[idx].lower() + if a in PWSH_VALUE_OPTS: + idx += 2 + continue + if a in ("-e", "-ec") or (len(a) > 2 and "-encodedcommand".startswith(a)): + return deny("An encoded PowerShell command hides what it runs; write " + "it out literally.") + if a == "-c" or (len(a) > 3 and "-command".startswith(a)): + idx += 1 + break + if a.startswith("-"): + idx += 1 + continue + break + rest = args[idx:] + if not rest or rest == ["-"]: + return self.stdin_script(ctx, "PowerShell") + return self.text(" ".join(rest), ps=True, guarded=ctx.guarded) + + def rtk(self, words, ctx): + # rtk args passes through to ; rtk run is sh -c; proxy, + # err, test and summary run the rest as a command. + while words and words[0].startswith("-"): + words = words[1:] + if not words: + return OK + sub = words[0] + if sub == "run": + return self.text(" ".join(words[1:]), guarded=ctx.guarded) + if sub in ("proxy", "err", "test", "summary"): + return self.program(words[1:], ctx) + return self.program(words, ctx) + + def runner(self, prog, words, ctx): + subs = RUNNERS[prog] + start = 0 + if subs is not None: + while start < len(words) and words[start].startswith("-"): + start += 1 + if start >= len(words) or words[start] not in subs: + return OK + start += 1 + rest = words[start:] + # Runner options take values (`uv run --with x …`), so rather than + # model each runner's options, start at the first word that names a + # program the guard knows, or else after `--`. + for idx, w in enumerate(rest): + base = prog_name(w, ctx.ps) + if base in RULES or base in SHELLS or base in WRAPPERS or \ + base in EVALS or base in RUNNERS or base in BUNDLES or base == "rtk": + return self.program(rest[idx:], ctx) + if "--" in rest: + return self.program(rest[rest.index("--") + 1:], ctx) + return OK + + def launcher(self, prog, args, ctx): + if prog == "nix-shell": + for idx, a in enumerate(args): + if a in ("--run", "--command") and idx + 1 < len(args): + return self.text(args[idx + 1], guarded=ctx.guarded) + return OK + if prog == "nix": + for idx, a in enumerate(args): + if a in ("-c", "--command"): + return self.program(args[idx + 1:], ctx) + return OK + # tmux: the shell command is what follows a command-running subcommand + for idx, a in enumerate(args): + if a in TMUX_RUN: + rest = self._skip_opts(args[idx + 1:], TMUX_VALUE_OPTS) + return self.text(" ".join(rest), guarded=ctx.guarded) if rest else OK + return OK + + def find_exec(self, args): + verdict = OK + idx = 0 + while idx < len(args): + if args[idx] in ("-exec", "-execdir", "-ok", "-okdir"): + end = idx + 1 + while end < len(args) and args[end] not in (";", "+"): + end += 1 + verdict = verdict.merge(self.program(args[idx + 1:end], Ctx())) + idx = end + idx += 1 + return verdict + + def wrapper(self, prog, words, ctx): + takes_value = WRAPPERS[prog] + if prog in ("su", "script"): + # su -c / su -lc / script -qc carry a command string + for idx, w in enumerate(words): + is_c = w in ("-c", "--command") or ( + w.startswith("-") and not w.startswith("--") and "c" in w[1:]) + if is_c and idx + 1 < len(words): + return self.text(words[idx + 1], guarded=ctx.guarded) + if w.startswith("--command="): + return self.text(w.split("=", 1)[1], guarded=ctx.guarded) + return OK + if prog in ("watch", "parallel"): + # both join their command words and hand them to a shell + rest = self._skip_opts(words, takes_value) + cmd = [] + for w in rest: + if w in (":::", "::::", ":::+", "::::+"): + break + cmd.append(w) + return self.text(" ".join(cmd), guarded=ctx.guarded) + if prog == "ssh": + rest = self._skip_opts(words, takes_value) + if len(rest) > 1: + return self.text(" ".join(rest[1:]), guarded=ctx.guarded) + if rest: # a host and no command: the remote shell reads stdin + return self.stdin_script(ctx, "ssh") + return OK # no host: git's GIT_SSH_COMMAND, which git completes + if prog == "xargs": + for idx, w in enumerate(words): + if w in ("-a", "--arg-file") and idx + 1 < len(words) and \ + is_secret_path(words[idx + 1]): + return deny("'%s' is secret material; agents never read it." + % words[idx + 1]) + if prog == "env": + idx = 0 + verdict = OK + while idx < len(words): + w = words[idx] + if w in ("-S", "--split-string") and idx + 1 < len(words): + return self.text(" ".join(words[idx + 1:]), guarded=ctx.guarded) + if w.startswith("--split-string="): + return self.text(" ".join([w.split("=", 1)[1]] + words[idx + 1:]), + guarded=ctx.guarded) + if _takes_value(w, takes_value): + idx += 2 + continue + if w.startswith("-"): + idx += 1 + continue + if ASSIGNMENT.match(w): + verdict = verdict.merge(self.assignment(w, ctx)) + idx += 1 + continue + break + return verdict.merge(self.program(words[idx:], ctx)) + rest = self._skip_opts(words, takes_value) + if prog in ("timeout", "taskset", "chrt", "chroot") and rest: + rest = rest[1:] # duration / mask / priority / new root + if prog == "flock" and rest: + rest = rest[1:] # lock file + if len(rest) >= 2 and rest[0] in ("-c", "--command"): + return self.text(rest[1], guarded=ctx.guarded) + return self.program(rest, ctx) + + @staticmethod + def _skip_opts(words, takes_value): + idx = 0 + while idx < len(words): + w = words[idx] + if w == "--": + idx += 1 + break + if _takes_value(w, takes_value): + idx += 2 + continue + if w.startswith("-") and len(w) > 1: + idx += 1 + continue + break + return words[idx:] + + +# -------------------------------------------------------------------------- +# Per-tool rules: rule(args, analyzer) -> Verdict +# -------------------------------------------------------------------------- + +def first_positional(args, takes_value): + """(index, word) of the first non-option argument, skipping option values.""" + idx = 0 + while idx < len(args): + a = args[idx] + if a == "--": + idx += 1 + break + if a in takes_value: + idx += 2 + continue + if a.startswith("-") and len(a) > 1: + idx += 1 + continue + return idx, a + if idx < len(args): + return idx, args[idx] + return None, None + + +def wants_help(args): + return any(a in ("--help", "-h", "-help") for a in args) + + +def _flag(args, *names): + """True when an option in `names` is given, with or without a value.""" + return any(a.lstrip("-").split("=", 1)[0] in names for a in args + if a.startswith("-")) + + +KUBECTL_GLOBAL = {"-n", "--namespace", "--context", "--kubeconfig", "--cluster", + "--user", "-s", "--server", "--token", "--as", "--as-group", + "--as-uid", "--certificate-authority", "--client-certificate", + "--client-key", "--request-timeout", "--tls-server-name", + "--cache-dir", "-v", "--profile", "--profile-output", + "--username", "--password", "--kuberc", "--log-file", + "--log-dir", "--vmodule"} +KUBECTL_READ = {"get", "describe", "logs", "top", "explain", "api-resources", + "api-versions", "version", "cluster-info", "events", "kustomize", + "wait", "completion", "help", "options"} +SECRET_RESOURCES = {"secret", "secrets"} +SAFE_OUTPUTS = {"wide", "name"} + + +def kubectl(args, an): + idx, verb = first_positional(args, KUBECTL_GLOBAL) + if verb is None or wants_help(args): + return OK + rest = args[idx + 1:] + if verb in KUBECTL_READ: + if verb == "get": + for j, a in enumerate(rest): + raw = None + if a == "--raw" and j + 1 < len(rest): + raw = rest[j + 1] + elif a.startswith("--raw="): + raw = a.split("=", 1)[1] + if raw is not None and "secret" in raw.lower(): + return deny("'kubectl get --raw' on a Secrets path prints Secret " + "data; agents never read Secrets.") + if _names_secret(rest) and _secret_output(rest): + return deny("'kubectl get secret -o …' prints Secret data; agents never " + "read Secrets. Plain 'kubectl get secrets' lists names only.") + if _kustomize(rest) and _secret_output(rest): + return deny("'kubectl get -k … -o …' prints every object the " + "kustomization names, Secrets included.") + if _secret_manifest(rest) and _secret_output(rest): + return deny("'kubectl get -f -o …' prints the live " + "Secret's data; agents never read Secrets.") + return OK + if verb == "auth": + sub = rest[0] if rest else "" + if sub in ("can-i", "whoami"): + return OK + if verb == "rollout": + sub = rest[0] if rest else "" + if sub in ("status", "history"): + return OK + if verb == "create" and _dry_run(rest) == "client": + # renders a manifest locally (e.g. a Secret to pipe into kubeseal) + return OK + if verb == "config": + sub = rest[0] if rest else "" + if sub in ("view",) and not any(a in ("--raw", "--flatten") or + a.startswith(("--raw=", "--flatten=")) + for a in rest): + return OK + if sub in ("get-contexts", "current-context", "get-clusters", "get-users", + "use-context", "use"): + return OK + if sub == "view": + return deny("'kubectl config view --raw' prints cluster credentials.") + if verb == "diff": + return deny("Live 'kubectl diff' is a server-side dry run that needs write " + "RBAC and is not used; use the offline render (kustomize build / " + "flux build --dry-run).") + return deny("'kubectl %s' is not on the allowlist of subcommands that change no " + "cluster and print no secret. Direct cluster changes never happen " + "from an agent; every change applies by approved merge." % verb) + + +def _dry_run(rest): + """The effective --dry-run mode: the last one given wins.""" + mode = None + for j, a in enumerate(rest): + if a.startswith("--dry-run="): + mode = a.split("=", 1)[1] + elif a == "--dry-run": + mode = rest[j + 1] if j + 1 < len(rest) else "unknown" + return mode + + +def _kustomize(rest): + return any(a in ("-k", "--kustomize") or a.startswith(("--kustomize=", "-k=")) + for a in rest) + + +def _secret_manifest(rest): + """A -f file whose name says it holds a Secret. A SealedSecret is + encrypted, so it does not count.""" + for j in option_values(rest, {"-f", "--filename"}): + if j < len(rest): + name = os.path.basename(rest[j].split("=", 1)[-1]).lower() + if "secret" in name and "sealed" not in name: + return True + return False + + +def _names_secret(rest): + for a in rest: + if a.startswith("-"): + continue + for part in re.split(r"[,/]", a.lower()): + if part.split(".", 1)[0] in SECRET_RESOURCES: + return True + return False + + +def _secret_output(rest): + for idx, a in enumerate(rest): + val = None + if a in ("-o", "--output") and idx + 1 < len(rest): + val = rest[idx + 1] + elif a.startswith("--output="): + val = a.split("=", 1)[1] + elif a.startswith("-o") and len(a) > 2: + val = a[2:].lstrip("=") + elif a == "--template" or a.startswith("--template="): + return True + if val is not None and val.split("=", 1)[0] not in SAFE_OUTPUTS: + return True + return False + + +HELM_GLOBAL = {"-n", "--namespace", "--kube-context", "--kubeconfig", + "--kube-apiserver", "--kube-as-user", "--kube-as-group", + "--kube-token", "--kube-ca-file", "--registry-config", + "--repository-config", "--repository-cache", "--burst-limit", + "--qps", "--kube-tls-server-name"} +HELM_READ = {"template", "lint", "list", "ls", "status", "history", "show", + "inspect", "version", "env", "search", "dependency", "dep", "pull", + "fetch", "package", "verify", "create", "completion", "help", "repo"} + + +def helm(args, an): + idx, verb = first_positional(args, HELM_GLOBAL) + if verb is None or wants_help(args): + return OK + rest = args[idx + 1:] + if verb in HELM_READ: + if verb == "repo" and rest and rest[0] not in ("add", "update", "list", "ls", "index"): + return deny("'helm repo %s' is not in the guard's allowlist." % rest[0]) + return OK + if verb == "get": + sub = rest[0] if rest else "" + if sub in ("notes", "metadata"): + return OK + return deny("'helm get %s' prints release values, manifests or hooks, which " + "can hold secret material." % sub) + if verb == "plugin": + sub = rest[0] if rest else "" + if sub in ("list", "ls"): + return OK + if verb == "diff": # the helm-diff plugin: read-only, Secrets redacted + if _flag(rest, "show-secrets", "show-secrets-decoded"): + return deny("'helm diff --show-secrets' prints Secret data.") + if rest[:1] and rest[0] in HELM_DIFF_SUBS: + return OK + if verb == "secrets": # the helm-secrets plugin + return helm_secrets(rest, an) + return deny("'helm %s' changes a release or the cluster. Releases change only " + "by approved merge." % verb) + + +HELM_DIFF_SUBS = {"upgrade", "install", "revision", "rollback", "release", "version"} + + +def helm_secrets(args, an): + # every helm-secrets mode but encrypt decrypts, or deploys decrypted values + _, verb = first_positional(args, set()) + if verb in ("encrypt", "enc", "help", "version") or wants_help(args): + return OK + return deny("'helm secrets %s' decrypts secrets; agents never decrypt them. Only " + "'helm secrets encrypt' is allowed." % (verb or "")) + + +HELMFILE_GLOBAL = {"-f", "--file", "-e", "--environment", "-n", "--namespace", + "--kube-context", "-l", "--selector", "--state-values-set", + "--state-values-file", "-b", "--helm-binary", "--log-level", + "--chart", "-c"} +HELMFILE_READ = {"template", "lint", "build", "list", "deps", "repos", "version", + "help", "write-values", "show-dag", "completion"} + + +def helmfile(args, an): + idx, verb = first_positional(args, HELMFILE_GLOBAL) + if verb is None or wants_help(args) or verb in HELMFILE_READ: + return OK + return deny("'helmfile %s' is not on the allowlist of subcommands that change " + "no release and print no secret. Releases change only by approved " + "merge." % verb) + + +TOFU_READ = {"init", "validate", "fmt", "plan", "providers", "version", "graph", + "get", "metadata", "modules", "help"} + + +def tofu(args, an): + # -chdir=DIR and other leading -flags are single words + idx, verb = first_positional(args, set()) + if verb is None or wants_help(args): + return OK + rest = args[idx + 1:] + if verb in ("run-all", "run"): # terragrunt: run-all , run [--all] + return tofu(rest, an) + if verb == "init" and _flag(rest, "migrate-state", "force-copy"): + return deny("'tofu init -migrate-state/-force-copy' moves state between " + "backends.") + if verb in TOFU_READ: + return OK + if verb == "workspace": + sub = rest[0] if rest else "" + if sub in ("list", "show", "select"): + return OK + return deny("'tofu workspace %s' changes state." % sub) + if verb == "output": + if _flag(rest, "json", "raw"): + return deny("'tofu output -json/-raw' prints sensitive outputs in clear.") + return OK + if verb == "show": + if _flag(rest, "json"): + return deny("'tofu show -json' prints sensitive values in clear.") + files = [a for a in rest if not a.startswith("-")] + if not files: + return deny("'tofu show' with no plan file prints the current state, " + "which holds secret material.") + return OK + if verb == "state": + sub = rest[0] if rest else "" + if sub == "list": + return OK + return deny("'tofu state %s' reads or edits state directly." % sub) + if verb == "destroy": + return deny("'tofu destroy' is never run by an agent.") + if verb == "apply": + if _flag(rest, "destroy"): + return deny("'tofu apply -destroy' is a destroy; never run by an agent.") + return ask("'tofu apply' changes real infrastructure.") + if verb in ("import", "refresh", "test"): + return ask("'tofu %s' writes state or creates real resources." % verb) + if verb in ("taint", "untaint", "force-unlock", "console", "push"): + return deny("'tofu %s' edits or exposes state directly." % verb) + return deny("'tofu %s' is not in the guard's allowlist." % verb) + + +# terragrunt's own commands on top of tofu's; they only read or format HCL. +TERRAGRUNT_READ = {"hclfmt", "render-json", "render", "hclvalidate", + "validate-inputs", "graph-dependencies", "output-module-groups", + "info", "find", "list"} + + +def terragrunt(args, an): + idx, verb = first_positional(args, set()) + if verb in TERRAGRUNT_READ: + return OK + if verb == "hcl" and args[idx + 1:idx + 2] in (["fmt"], ["validate"], ["format"]): + return OK + return tofu(args, an) + + +ANSIBLE_READ_FLAGS = {"--check", "--syntax-check", "--list-tasks", "--list-hosts", + "--list-tags", "--version", "--help", "-h"} +ANSIBLE_VALUE_SHORT = set("ieftuMlkKbcTPBmaJ") # options whose value may follow + + +def _ansible_check_mode(args): + for a in args: + if a in ANSIBLE_READ_FLAGS: + return True + if a.startswith("--check="): + return True + if a.startswith("-") and not a.startswith("--") and len(a) > 1: + for ch in a[1:]: + if ch == "C": + return True + if ch in ANSIBLE_VALUE_SHORT: + break + return False + + +def ansible_playbook(args, an): + if _ansible_check_mode(args): + return OK + return ask("'ansible-playbook' without --check changes real hosts.") + + +def ansible_adhoc(args, an): + if _ansible_check_mode(args) or not args: + return OK + return ask("ad-hoc 'ansible' without --check runs modules on real hosts.") + + +def ansible_pull(args, an): + if _ansible_check_mode(args): + return OK + return ask("'ansible-pull' without --check changes real hosts.") + + +def ansible_console(args, an): + return ask("'ansible-console' runs modules on real hosts.") + + +def ansible_vault(args, an): + _, verb = first_positional(args, {"--vault-id", "--vault-password-file"}) + if verb in ("view", "decrypt", "edit", "rekey"): + return deny("'ansible-vault %s' decrypts vaulted secrets; agents never do." % verb) + return OK + + +def kubeseal(args, an): + for a in args: + if a.split("=", 1)[0] in ("--recovery-unseal", "--recovery-private-key"): + return deny("kubeseal recovery decrypts Sealed Secrets; agents never do.") + return OK + + +SOPS_SAFE = {"-e", "--encrypt", "encrypt", "updatekeys", "filestatus", + "--version", "-v", "--help", "-h", "help", "keyservice"} + + +def sops(args, an): + # A bare `sops ` opens it decrypted in $EDITOR, so only the + # encrypting and metadata modes are allowed. + if any(a in SOPS_SAFE for a in args): + if not any(a in ("-d", "--decrypt", "decrypt") for a in args): + return OK + return deny("sops would decrypt here; agents never decrypt secrets. Only " + "'sops --encrypt', 'updatekeys' and 'filestatus' are allowed.") + + +def gpg(args, an): + # gpg takes any unambiguous prefix of a long option + if any(a.startswith("--export-secret") for a in args): + return deny("'gpg --export-secret-keys' prints private keys.") + return OK + + +FLUX_GLOBAL = {"-n", "--namespace", "--context", "--kubeconfig", "--timeout", + "--cluster", "--user", "--token", "--as", "--as-group", "--server", + "-s", "--certificate-authority", "--client-certificate", "--client-key"} +FLUX_READ = {"get", "logs", "events", "tree", "trace", "stats", "check", + "version", "build", "completion", "help", "debug", "envsubst"} + + +def flux(args, an): + idx, verb = first_positional(args, FLUX_GLOBAL) + if verb is None or wants_help(args): + return OK + rest = args[idx + 1:] + if verb == "debug" and _flag(rest, "show-values", "show-vars"): + return deny("'flux debug --show-values/--show-vars' can print values pulled " + "from Secrets.") + if verb in FLUX_READ: + return OK + if verb == "export": + if _flag(rest, "with-credentials"): + return deny("'flux export --with-credentials' prints source credentials.") + return OK + if verb in ("create", "install") and "--export" in rest: + return OK + if verb == "reconcile": + return ask("'flux reconcile' makes the cluster act now.") + if verb == "diff": + return deny("Live 'flux diff' needs write RBAC and is not used; use " + "'flux build --dry-run' or the PR's offline render diff.") + return deny("'flux %s' changes the cluster. Cluster changes apply by approved " + "merge." % verb) + + +GIT_GLOBAL = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", + "--exec-path", "--config-env", "--super-prefix"} +# Subcommands that take a message with -m, and the short options whose value +# is the next word when they end a cluster (`-am msg`). +GIT_MESSAGE_SUBS = {"commit", "tag", "merge", "notes", "stash", "revert"} +GIT_VALUE_SHORT = {"commit": "mFcCt", "tag": "mFu", "merge": "mFsX", + "notes": "mFcC", "stash": "m", "revert": "mX", + "log": "SGn", "show": "SG", "whatchanged": "SG", + "rev-list": "SGn", "diff": "SG"} +GIT_VALUE_LONG = {"--message", "--file", "--reuse-message", "--reedit-message", + "--template", "--author", "--date", "--cleanup", "--fixup", + "--squash", "--trailer", "--grep", "--format", "--pretty", + "--committer"} + + +def _git_sub_index(args): + idx = 0 + while idx < len(args): + a = args[idx] + if a in GIT_GLOBAL: + idx += 2 + continue + if a.startswith("-"): + idx += 1 + continue + return idx + return None + + +def _git_value_indexes(sub, rest): + """Indexes of option values in a git subcommand's arguments.""" + letters = GIT_VALUE_SHORT.get(sub, "") + skip = set() + for j, a in enumerate(rest): + if j in skip: + continue + if a in GIT_VALUE_LONG: + skip.add(j + 1) + elif a.startswith("-") and not a.startswith("--"): + for pos, ch in enumerate(a[1:]): + if ch in letters: + if pos == len(a) - 2: + skip.add(j + 1) + break + return skip + + +def _git_message_indexes(rest): + """Indexes of the words that are a -m / --message value.""" + found = set() + for j, a in enumerate(rest): + if a in ("-m", "--message"): + found.add(j + 1) + elif a.startswith("--message="): + found.add(j) + elif a.startswith("-") and not a.startswith("--") and "m" in a: + found.add(j + 1 if a.endswith("m") and a.index("m") == len(a) - 1 else j) + return found + + +def _git_config_value(value, an): + low = value.lower() + if "hookspath" in low: + return deny("Overriding core.hooksPath skips the repo's git hooks; " + HOOK_BYPASS) + if "no-verif" in low: + return deny("A git alias carrying --no-verify skips the repo's git hooks; " + + HOOK_BYPASS) + key, _, val = value.partition("=") + key = key.lower() + if key == "core.sshcommand": + return an.text(val) + if key.startswith("alias.") and val.startswith("!"): + return an.text(val[1:]) + if is_secret_path(val): + return deny("'%s' is secret material; agents never read it." % val) + return OK + + +def git(args, an): + verdict = OK + idx = 0 + while idx < len(args): + a = args[idx] + if a in ("-c", "--config-env") and idx + 1 < len(args): + verdict = verdict.merge(_git_config_value(args[idx + 1], an)) + idx += 2 + continue + if a.startswith("--config-env="): + verdict = verdict.merge(_git_config_value(a.split("=", 1)[1], an)) + elif a.startswith("-c") and len(a) > 2: + verdict = verdict.merge(_git_config_value(a[2:].lstrip("="), an)) + if a in GIT_GLOBAL: + idx += 2 + continue + if a.startswith("-"): + idx += 1 + continue + break + if verdict.decision == DENY or idx >= len(args): + return verdict + sub = args[idx] + rest = args[idx + 1:] + values = _git_value_indexes(sub, rest) + opts = [a for j, a in enumerate(rest) if j not in values] + # git accepts any unambiguous prefix of a long option: --no-verif, --no-ve… + if sub != "grep" and any(len(a) >= 6 and "--no-verify".startswith(a) for a in opts): + return deny("'--no-verify' skips the repo's git hooks; " + HOOK_BYPASS) + if sub == "config": + setting = not any(x in ("--get", "--get-all", "-l", "--list", "--unset", + "--unset-all", "get", "list", "unset") for x in rest) + for j, a in enumerate(rest): + key = a.lower() + if j + 1 >= len(rest) or not setting: + break + if key == "core.hookspath": + return deny("Setting core.hooksPath skips the repo's git hooks; " + + HOOK_BYPASS) + if key.startswith("alias.") or key == "core.sshcommand": + verdict = verdict.merge(_git_config_value(a + "=" + rest[j + 1], an)) + if sub == "rebase": + for j, a in enumerate(rest): + if a in ("-x", "--exec") and j + 1 < len(rest): + verdict = verdict.merge(an.text(rest[j + 1])) + elif a.startswith("--exec="): + verdict = verdict.merge(an.text(a.split("=", 1)[1])) + if sub == "bisect" and rest[:1] == ["run"]: + verdict = verdict.merge(an.program(rest[1:], Ctx())) + if sub == "submodule" and "foreach" in rest: + cmd = [w for w in rest[rest.index("foreach") + 1:] if not w.startswith("--")] + verdict = verdict.merge(an.text(" ".join(cmd))) + if sub == "commit": + for j, a in enumerate(rest): + if j in values or not a.startswith("-") or a.startswith("--"): + continue + for ch in a[1:]: + if ch == "n": + return deny("'git commit -n' is --no-verify; it skips the " + "repo's git hooks.") + if ch in GIT_VALUE_SHORT["commit"]: + break + return verdict + + +def pre_commit(args, an): + _, verb = first_positional(args, {"-c", "--config"}) + if verb == "uninstall": + return deny("'pre-commit uninstall' turns the repo's gates off; " + HOOK_BYPASS) + return OK + + +RULES = { + "kubectl": kubectl, "kubecolor": kubectl, "microk8s.kubectl": kubectl, + "helm": helm, "helm3": helm, + "helmfile": helmfile, "helm-secrets": helm_secrets, + "tofu": tofu, "terraform": tofu, "terragrunt": terragrunt, + "ansible-playbook": ansible_playbook, + "ansible": ansible_adhoc, + "ansible-pull": ansible_pull, + "ansible-console": ansible_console, + "ansible-vault": ansible_vault, + "kubeseal": kubeseal, + "sops": sops, + "gpg": gpg, "gpg2": gpg, + "flux": flux, + "git": git, + "pre-commit": pre_commit, +} + +# -------------------------------------------------------------------------- +# Tool dispatch +# -------------------------------------------------------------------------- + +SHELL_TOOLS = {"bash", "shell", "powershell", "local_shell", "exec_command", + "unified_exec", "run_shell_command", "container.exec", "monitor", + "write_stdin", "write_bash"} +PS_TOOLS = {"powershell"} +COMMAND_KEYS = ("command", "cmd", "input", "chars") +PATH_KEYS = ("file_path", "path", "notebook_path", "filePath", "absolute_path") +WRITE_TOOLS = {"write", "edit", "multiedit", "notebookedit", "create", + "str_replace", "str_replace_editor", "insert"} +PATCH_TARGET = re.compile(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", re.M) + + +def analyse_tool(tool, tool_input): + if not isinstance(tool, str) or not tool: + raise ValueError("no tool name") + lname = tool.lower() + if lname in SHELL_TOOLS: + if not isinstance(tool_input, dict): + raise ValueError("tool input is not an object") + cmd = next((tool_input[k] for k in COMMAND_KEYS if k in tool_input), None) + if isinstance(cmd, list) and cmd and all(isinstance(c, str) for c in cmd): + cmd = " ".join(_quote(c) for c in cmd) + if not isinstance(cmd, str): + raise ValueError("no command string") + return Analyzer().text(cmd, ps=lname in PS_TOOLS) + if not isinstance(tool_input, dict): + tool_input = {} + if lname == "apply_patch": + cmd = str(tool_input.get("command", "") or tool_input.get("input", "")) + for m in PATCH_TARGET.finditer(cmd): + path = m.group(1).strip() + if is_secret_path(path): + return deny("'%s' is secret material; agents never touch it." % path) + if is_hooks_path(path): + return deny("Changing '%s' changes the repo's git hooks; %s" + % (path, HOOK_BYPASS)) + return OK + for key in PATH_KEYS: + val = tool_input.get(key) + if not isinstance(val, str): + continue + if is_secret_path(val): + return deny("'%s' is secret material (vault password, private key, " + "admin kubeconfig or tofu state); agents never read it." % val) + if lname in WRITE_TOOLS and is_hooks_path(val): + return deny("Changing '%s' changes the repo's git hooks; %s" % (val, HOOK_BYPASS)) + for key in ("glob", "include"): + val = tool_input.get(key) + if isinstance(val, str) and is_secret_path(val): + return deny("A search over '%s' reads secret material." % val) + return OK + + +def _quote(s): + if re.match(r"^[A-Za-z0-9_./=:@%+,-]+$", s): + return s + return "'" + s.replace("'", "'\\''") + "'" + + +def detect_runtime(): + here = os.path.abspath(__file__).replace("\\", "/") + if "/.claude/hooks/" in here: + return "claude" + if "/.github/hooks/" in here: + return "copilot" + if "/.codex/hooks/" in here: + return "codex" + return "unknown" + + +def read_payload(payload): + """(tool name, tool input) from either payload shape.""" + if "toolName" in payload: + args = payload.get("toolArgs") + if isinstance(args, str): + try: + args = json.loads(args) + except ValueError: + args = {"command": args} + if args is not None and not isinstance(args, dict): + raise ValueError("toolArgs is not an object") + return payload.get("toolName"), args + return payload.get("tool_name"), payload.get("tool_input") + + +def emit(runtime, event, verdict): + decision = verdict.decision + if decision == ASK and runtime not in ("claude", "copilot"): + decision = DENY + verdict = Verdict(DENY, verdict.reason + + " This runtime cannot ask, so the guard denies.") + if decision == ALLOW: + return 0 + if runtime == "copilot": + print(json.dumps({"permissionDecision": decision, + "permissionDecisionReason": verdict.reason})) + return 0 + if runtime == "claude": + print(json.dumps({"hookSpecificOutput": { + "hookEventName": event, + "permissionDecision": decision, + "permissionDecisionReason": verdict.reason}})) + return 0 + # Codex and unknown runtimes: exit 2 with the reason on stderr is the + # portable deny. + sys.stderr.write(verdict.reason + "\n") + return 2 + + +def main(): + runtime = detect_runtime() + event = "PreToolUse" + try: + payload = json.loads(sys.stdin.read()) + if not isinstance(payload, dict): + raise ValueError("payload is not an object") + if isinstance(payload.get("hook_event_name"), str): + event = payload["hook_event_name"] + verdict = analyse_tool(*read_payload(payload)) + except Exception as exc: # fail closed + verdict = Verdict(DENY, "delivery guard: could not read the tool call (%s); " + "denying to stay safe." % exc.__class__.__name__) + return emit(runtime, event, verdict) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/plugins/delivery/.apm/hooks/hooks.json b/plugins/delivery/.apm/hooks/hooks.json new file mode 100644 index 0000000..03304ba --- /dev/null +++ b/plugins/delivery/.apm/hooks/hooks.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "PreToolUse": [ + { + "hooks": [ + { + "command": "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/guard.py", + "onFailure": "block", + "timeout": 10, + "type": "command" + } + ] + } + ] + } +} diff --git a/plugins/delivery/apm.yml b/plugins/delivery/apm.yml index 929a347..d045e4a 100644 --- a/plugins/delivery/apm.yml +++ b/plugins/delivery/apm.yml @@ -1,5 +1,5 @@ name: delivery -version: 0.1.0 +version: 0.2.0 description: Agents and skills for taking a change from spec to a verified merge through tracker-gated stages. author: name: Mortis diff --git a/plugins/delivery/docs/guard-hook.md b/plugins/delivery/docs/guard-hook.md new file mode 100644 index 0000000..6fb3b64 --- /dev/null +++ b/plugins/delivery/docs/guard-hook.md @@ -0,0 +1,188 @@ +# Guard hook + +`delivery` ships one pre-tool-use hook, `.apm/hooks/guard.py`. It is ADR-0032's enforcement layer +2, a guardrail above the credential boundary and not the boundary itself. The decisions behind it are +in the `delivery guard hook` ticket (holocron#190) and ADR-0032's 2026-11-23 amendment. + +## What it decides + +| Tier | Examples | Claude Code | Copilot CLI | Codex / unknown | +|---|---|---|---|---| +| Never | `kubectl`/`kubecolor` subcommands outside the allowlist, `helm`/`helm3` install/upgrade/uninstall/rollback, `helm get values/manifest/hooks/all`, `helm diff --show-secrets`, `helm secrets` and `helm-secrets` except `encrypt`, `helmfile` subcommands outside the allowlist, `flux suspend/delete/…`, `flux debug --show-values/--show-vars`, `tofu`/`terraform`/`terragrunt destroy`, `tofu apply -destroy`, `tofu init -migrate-state/-force-copy`, `tofu state` (except `list`), `tofu show` without a plan file or with `-json`, `tofu output -json/-raw`, `git … --no-verify` (and its abbreviations), `git commit -n`, `SKIP=`/`SKIP+=`, `HUSKY=0`, `LEFTHOOK=0`, `core.hooksPath` overrides (`-c`, `--config-env`, `GIT_CONFIG_*`, `git config`), git aliases carrying `--no-verify` or a guarded `!` command (`-c alias.…` or `git config alias.…`), `pre-commit uninstall`, writing, moving, removing or `chmod`-ing anything under `.git/hooks/`, `ansible-vault view/decrypt/edit/rekey`, `kubeseal --recovery-*`, `sops` in any decrypting mode (including bare `sops `), `gpg --export-secret-keys/-subkeys`, `kubectl get secret -o …`/`--template`, `kubectl get -k … -o …`, `kubectl get -f -o …`, `kubectl get --raw …secrets…`, `kubectl config view --raw`, any mention of a secret path | deny | deny | deny | +| Odd job | `ansible-playbook` / ad-hoc `ansible` / `ansible-pull` without `--check`, `ansible-console`, `tofu apply/import/refresh/test`, `flux reconcile` | ask | ask | deny | +| Read / Propose | everything else | allow | allow | allow | + +`kubectl`, `helm`, `helmfile`, `flux` and `tofu` are **allowlists**: a subcommand the guard does not list as +allowed is denied. Widen the allowlist in `guard.py` and its test table together. The allowed sets +are "no cluster or state change and no secret printed", not strictly read-only. `helm pull`, +`package`, `create` and `repo add/update`, `tofu init`, `plan` and `get`, `helm diff upgrade/install/revision/rollback` (the read-only helm-diff plugin), `kubectl wait`, and +`kubectl create … --dry-run=client` (which renders a Secret to pipe into `kubeseal`) all write local +files or caches. When `--dry-run` is given twice, the last one counts. `helmfile` allows `template`, +`lint`, `build`, `list`, `deps`, `repos`, `version`, `help`, `write-values` and `show-dag`. +`terragrunt` follows the `tofu` rule and also allows its own HCL commands: `hclfmt`, `hcl fmt`, +`hcl validate`, `render-json` and `render`. `--help` is always allowed. + +Secret paths are basename globs: `.vault_pass*`, `vault_pass*`, `*vault_password*` (and the `-` +spellings), `*deploy_key*`, `*.tfstate`, `*.tfstate.*`, `id_rsa*`/`id_ed25519*`/`id_ecdsa*`/`id_dsa*`, +`*.key`, `key.pem`, `*-key.pem`, `*_key.pem`, `privkey*.pem`, `*private*.pem`, `*.p12`, `*.pfx` and +`.git-credentials*`. The undotted vault-password names and `*deploy_key*` also fit source and docs +about them, so a doc or data suffix (`.yml`, `.yaml`, `.md`, `.rst`, `.j2`, `.adoc`, `.html`) +exempts them. A code suffix (`.py`, `.sh`, …) exempts only a test file: `test_vault_password.py` +is fine, but `vault_pass.py` and `vault-pass.sh` are the usual names of an Ansible vault-password +script, which prints the password when run. `vault_password` and `.vault_pass.yml` are not exempt. git's `REV:path` form is checked by its path (`git show HEAD:.vault_pass`). Also covered: +- the admin kubeconfig `.kube/config` and its backups (`config.*`, `config~`). Other kubeconfigs in + `.kube`, such as `.kube/configs/stage-ro.yaml`, are fine. +- the `.kube` and `.ssh` directories as a whole, and any glob inside them (`~/.ssh/id*`, + `~/.kube/*`) +- `sops/age/keys.txt`, `/etc/rancher/k3s/k3s.yaml` and `/etc/kubernetes/admin.conf` + +Any other shell glob with at least three literal characters (`.vault_pa*`) counts if it could +expand to a secret name. Redirect targets are checked the same way for every program, so +`echo x > terraform.tfstate` and `grep < ~/.ssh/id_rsa .` are denied. + +An option name is never a path: only its `=value` is checked. So `--vault-password-file` itself +does not count, and `ansible-vault encrypt --vault-password-file ~/placeholder vars.yml` (the +placeholder-password stage workflow) is allowed, while `--vault-password-file .vault_pass` is not. + +Exemptions: +- `.pub` files. +- The values of `--vault-password-file`, `--vault-id`, `--private-key` and `--key-file`, for + `ansible-playbook`, `ansible` and `ansible-pull` only. Ansible reads those itself, and that run is + already an Odd job. Elsewhere, `ansible-inventory` and `ansible-vault` included, the value is + checked like any path. +- SSH keys handed to ssh: `ssh -i`, `scp -i`, `sftp -i`, `ssh-add`, and the command in + `GIT_SSH_COMMAND` or `core.sshCommand`, which the guard reads as a command. +- The search pattern of `grep`/`rg`/`ag`/`ack`/`git grep`, wherever the program sits after + unwrapping (so `rtk grep vault_pass ansible.cfg` is allowed). The exemption doesn't apply once + `-e` or `-f` makes the pattern explicit. +- The filter of `jq`, `gojq` and `yq` (`jq -r '.tls.key' x.json`), unless `-f` reads it from a + file. The files they read are still checked. +- The `-k`/`-m` test selector of `pytest` and `python -m pytest`. +- File-name patterns: the values of `--include`, `--exclude`, `--exclude-dir`, `--glob`/`-g` and + `--iglob` for the search tools, and of `find -name`/`-iname`/`-path`/`-ipath`/`-regex`. A + directory `find` searches is still checked, so `find ~/.ssh -name id_rsa` is denied. A `find` + that deletes or runs something (`-delete`, `-exec`, `-execdir`, `-ok`) loses this exemption, so + `find . -name '*.tfstate' -delete` is denied, and so is any such `find` naming `.git/hooks`. +- Prose: the `-m`/`--message` value of `git commit`, `tag`, `merge`, `notes`, `stash` and + `revert`, and the title, body and notes values of `gh` and `tea`. `git commit -m x --no-verify` + is still denied: only the secret-path check skips the message. The search values of + `git log -S`/`-G`/`--grep` are skipped by the `--no-verify` check. +- Programs that only print or stat their arguments: `echo`, `printf`, `ls`, `stat`, `test`. Their + redirect targets are still checked. +- `git rm`, `check-ignore`, `ls-files` and `status`. + +Pointing at the admin `~/.kube/config` is denied on purpose: stage sessions use the read-only +kubeconfig. File tools are checked too: Read, Grep, Edit and Write paths, Copilot's `view`, and +Codex's `apply_patch` targets, including `Move to`. Write and Edit under `.git/hooks/` are denied; +reading there is fine. + +## How it reads a command + +The script tokenises the shell line itself. It handles: +- quoting and escapes, including backslash-newline and `$'…'` with escaped quotes +- `;`, `&&`, `||`, `|`, newlines, subshells, braces, `function NAME { … }` and `((…))` +- redirections, which never become words of the command. The fd number in `2>&1` is dropped, and + the target is checked for secret paths and `.git/hooks/`. +- here-documents. A body is data, so commit messages and PR bodies may name any command. Two + exceptions: an unquoted delimiter's body (`<(…)` with the same rules as the rest of the line, so a +quote or bracket in a here-document inside `$(…)` cannot hide what follows. Backtick bodies are +parsed too. It also unwraps: +- shells: `bash`/`sh`/… `-c` (including clusters such as `-lc`, `-o opt -c` and + `-euo pipefail -c`), here-strings, + here-documents, and a shell reading a pipe, which is denied when the line mentions a guarded tool. + `bash <(…)`, `source <(…)`, `. <(…)` and a `-c` string holding a `$(…)` are built at run time, + so they are denied when the line mentions a guarded tool. +- `eval` (the same run-time rule), `trap 'cmd' SIG`, and leading `NAME=value` / `NAME+=value` + assignments +- `env` (including `-S`), `sudo`, `doas`, `su -c`, `script -c`, `flock`, `strace`, `systemd-run`, + `chroot`, `busybox`, `k3s`, `microk8s` +- `nohup`, `setsid`, `time`, `command` and `exec` (by basename, with their options) +- `timeout`, `nice`, `xargs`, `parallel`, `watch`, `find -exec`, `ssh host ` +- `nix-shell --run`, `nix shell/develop -c`, `tmux new-session/new-window/split-window` +- git's own shell-outs: `rebase --exec`, `bisect run`, `submodule foreach` and `!` aliases +- `rtk` (`rtk `, `rtk run`, `rtk proxy`) +- project runners: `uv`/`poetry`/`pipenv`/`pdm`/`hatch`/`pipx run`, `uv tool run`, `uvx`, + `direnv exec`, `mise exec`, `devbox run`, and secret injectors `aws-vault exec`, `op run` and + `doppler run` + +In an option cluster, a last letter that takes a value consumes the next word, for shells and for +every wrapper: `sudo -iu root kubectl …` runs `kubectl`, not `root`. + +It takes the program's basename and drops a `.exe` suffix, so `/usr/bin/kubectl`, `\kubectl` and +`kubectl.exe` are all `kubectl`. It denies, rather than guesses, when a program name is built at run +time (`$k apply`) and the line mentions a guarded tool, when the program name is a glob, or when an +unquoted brace expansion hides a guarded command. A guarded tool counts only as a whole name, so +`.pre-commit-config.yaml` is not `pre-commit`. + +The PowerShell tool gets a PowerShell mode of the same tokenizer, not a full PowerShell parser. The +backtick is the escape and line-continuation character, backslash is a plain path separator, `''` +escapes a single quote, and `@'…'@` here-strings are read. Program names are matched without case. +It unwraps `iex`/`Invoke-Expression`, `cmd /c` and `pwsh`/`powershell -Command`, and denies +`-EncodedCommand`. + +Copilot lets a timed-out hook's call through, so the guard refuses input it cannot read well inside +the 10-second budget. It denies outright a command longer than 256 KB, a simple command of more than +2,000 words, a line of more than 5,000 commands, substitutions nested more than 40 deep, and more +than 32 wrappers inside one another (`sudo sudo …`, `find -exec find -exec …`). Each of these +finishes well under a second. + +**Known gaps, by construction:** +- a script the agent writes and then runs +- `python -c` or `node -e` subprocesses +- MCP tools, which carry no shell command +- secret files at an unusual path +- `cd ~/.kube && cat config`, because the guard does not track the working directory +- file names produced at run time, such as `ls ~/.ssh/id_* | xargs cat`: `xargs` reads its + arguments from the pipe, which the guard cannot see +- a shell reading a pipe when the line mentions no guarded tool, such as `curl … | bash` +- what an allowed command prints at run time, such as `ansible -C -m debug` of a vaulted variable + +The credential boundary covers all of these: the read-only kubeconfig, no vault password and no +apply credentials in stage sessions. + +## Runtimes + +The script tells runtimes apart by where apm deployed it: + +| Deployed under | Runtime | Notes | +|---|---|---| +| `.claude/hooks/` | Claude Code | Output is `hookSpecificOutput.permissionDecision`. `onFailure: block` makes a crash or timeout block the call (Claude Code ≥ 2.1.295). Verified live on 2.1.326. | +| `.github/hooks/scripts/` | Copilot CLI | Output is top-level `permissionDecision` plus a reason. A non-zero exit denies, but a **timeout lets the call through**. The TUI auto-approves `ask` (ADR-0032 accepted risk). apm writes the entry in Claude's nested shape with `command`/`timeout`, and Copilot's docs accept both keys but don't document the nested group, so it is **unverified** until a Copilot account exists. | +| `.codex/hooks/` | Codex | `ask` is unsupported, so the guard denies with exit 2 and the reason on stderr. apm deploys only if `.codex/` already exists, and Codex skips project hooks until a human trusts them. Codex resolves the relative command from the session cwd, so a session started in a subdirectory may not find the script. | +| anywhere else | unknown | Treated like Codex: odd jobs are denied, with exit 2. The payload's shape (`toolName` or `tool_name`) picks only how the payload is read, never the runtime. | + +## What a consuming repo needs + +- `python3` on PATH. The script uses the standard library only. Without python3 the hook cannot + start, which blocks every tool call on Claude Code and Copilot. That's deliberate. +- An `executables.allow` grant for the package in the repo's `apm.yml`, when that repo turns on apm's + executable-trust gate: + + ```yaml + executables: + allow: + delivery: + hooks: true + ``` + + apm 0.28.0 prints "parked pending approval" even when the grant matches (holocron#208). Check that + the hook actually deployed by looking for `guard.py` under `.claude/hooks/delivery/` and the + `PreToolUse` entry in `.claude/settings.json`. Don't rely on the install exit code. +- Host hardening is documented, not shipped (ADR-0032 layer 3). Examples are Claude permission + deny rules, sandbox `denyRead` on the vault password file, and managed settings with + `allowManagedHooksOnly` so the guard cannot be switched off. + +## Tests + +`tests/test-delivery-guard-hook.sh` copies the script to each runtime's deploy path and drives it +with Claude, Copilot and Codex payloads. It covers the deny, ask and allow tables, bypass attempts +(quoting, `bash -c`, `env`, `sudo`, `xargs`, `find -exec`, substitution, `eval`, dynamic program +names), PowerShell, the per-runtime output shape, and fail-closed handling of malformed payloads. +A malformed payload is denied: not JSON or not an object, no tool name, a shell tool whose input is +not an object or carries no command string (read from `command`, `cmd`, `input` or `chars`), and +Copilot `toolArgs` that is not an object. It also covers the time the guard takes on pathological +input and the `hooks.json` invariants. diff --git a/scripts/check-executables-allow-sync.sh b/scripts/check-executables-allow-sync.sh index 86457ca..7971590 100755 --- a/scripts/check-executables-allow-sync.sh +++ b/scripts/check-executables-allow-sync.sh @@ -1,23 +1,29 @@ #!/usr/bin/env bash set -euo pipefail -# Fails the push when root apm.yml's executables.allow key stops naming -# kyberforge's actual version. The grant itself is version-blind — apm matches -# the version-less name alongside '#' (exec_gate.py builds -# the candidate list, _map_grants matches it) — so a stale key keeps granting -# kyberforge's hooks/ and bin/ and deployment does not break. What this gate -# buys is repo-level, not apm-level: a version bump without the matching key -# edit fails this repo's own pre-push, so the key stays an accurate record of -# what was approved. See ADR-0019's 2026-09-19 correction and docs/spec/gates.md, +# Fails the push when root apm.yml's executables.allow stops naming the actual +# version of every plugin that ships executables. A plugin ships executables +# when plugins//.apm/hooks/ or plugins//bin/ exists; each one needs +# a '#' key, where and come from its own +# apm.yml (and must equal the directory name, since keys use the +# package name). Every failing package is reported in one run. +# +# The grant itself is version-blind — apm matches the version-less name +# alongside '#' (exec_gate.py builds the candidate list, +# _map_grants matches it) — so a stale key keeps granting the package's hooks/ +# and bin/ and deployment does not break. What this gate buys is repo-level, +# not apm-level: a version bump without the matching key edit fails this +# repo's own pre-push, so each key stays an accurate record of what was +# approved. See ADR-0019's 2026-09-19 correction and docs/spec/gates.md, # "check-executables-allow-sync"; nothing else in the pre-push gate compares -# these two files. +# these files. # # Run from repo root or pass REPO_ROOT as arg. REPO_ROOT="${1:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}" # A nonexistent REPO_ROOT fails loudly rather than falling through to the -# "no kyberforge plugin here" no-op below: that no-op is for a repo that -# legitimately does not ship the plugin, not for a typo'd or stale path, and +# "no executable-shipping plugin here" no-op below: that no-op is for a repo +# that legitimately ships no executables, not for a typo'd or stale path, and # exit 0 would read as "checked, in sync" when nothing was compared at all. if [[ ! -d "$REPO_ROOT" ]]; then echo "FAIL: executables-allow sync check: REPO_ROOT '$REPO_ROOT' is not a directory." >&2 @@ -26,28 +32,69 @@ if [[ ! -d "$REPO_ROOT" ]]; then fi REPO_ROOT="$(cd "$REPO_ROOT" && pwd)" -PLUGIN_DIR="$REPO_ROOT/plugins/kyberforge" -PLUGIN_MANIFEST="$PLUGIN_DIR/apm.yml" ROOT_MANIFEST="$REPO_ROOT/apm.yml" -# Only a repo with no kyberforge plugin at all is a legitimate no-op — there is -# no version to pin and no hook to deploy. -if [[ ! -d "$PLUGIN_DIR" ]]; then +# --------------------------------------------------------------------------- +# Discovery +# --------------------------------------------------------------------------- +# PLUGINS: directory names of every plugin that ships executables. READABLE +# (below) is the subset whose apm.yml exists; only those reach the readers. +PLUGINS=() +shopt -s nullglob +for plugin_dir in "$REPO_ROOT"/plugins/*/; do + plugin_dir="${plugin_dir%/}" + if [[ -d "$plugin_dir/.apm/hooks" || -d "$plugin_dir/bin" ]]; then + PLUGINS+=("${plugin_dir##*/}") + fi +done +shopt -u nullglob + +# Only a repo with no executable-shipping plugin at all is a legitimate no-op — +# there is no version to pin and no hook to deploy. +if [[ ${#PLUGINS[@]} -eq 0 ]]; then exit 0 fi -if [[ ! -f "$PLUGIN_MANIFEST" ]]; then - echo "FAIL: plugins/kyberforge/ exists but has no apm.yml, so its version cannot be read." >&2 +FAILED=0 + +# "hooks/ and bin/", "hooks/" or "bin/" — what the plugin actually ships, so a +# message never claims a package has a bin/ it does not. +ships() { + local dir="$REPO_ROOT/plugins/$1" + if [[ -d "$dir/.apm/hooks" && -d "$dir/bin" ]]; then + printf 'hooks/ and bin/' + elif [[ -d "$dir/.apm/hooks" ]]; then + printf 'hooks/' + else + printf 'bin/' + fi +} + +# "hooks: true, bin: true" etc. — the allow entry body the plugin needs. +grants() { + local dir="$REPO_ROOT/plugins/$1" out="" + if [[ -d "$dir/.apm/hooks" ]]; then out="hooks: true"; fi + if [[ -d "$dir/bin" ]]; then out+="${out:+, }bin: true"; fi + printf '%s' "$out" +} + +READABLE=() +for plugin in ${PLUGINS[@]+"${PLUGINS[@]}"}; do + if [[ -f "$REPO_ROOT/plugins/$plugin/apm.yml" ]]; then + READABLE+=("$plugin") + continue + fi + echo "FAIL: plugins/$plugin/ ships $(ships "$plugin") but has no apm.yml, so its version cannot be read." >&2 echo " Why: this gate compares that version against root apm.yml's executables.allow key;" >&2 echo " without the manifest it would exit 0 having compared nothing." >&2 - echo " Fix: restore plugins/kyberforge/apm.yml, or remove plugins/kyberforge/ entirely." >&2 - exit 1 -fi + echo " Fix: restore plugins/$plugin/apm.yml, or remove plugins/$plugin/ entirely." >&2 + FAILED=1 +done if [[ ! -f "$ROOT_MANIFEST" ]]; then - echo "FAIL: root apm.yml is missing, so kyberforge's executables allow key cannot be verified." >&2 + echo "FAIL: root apm.yml is missing, so no executables allow key can be verified (${PLUGINS[*]})." >&2 echo " Why: apm reads executables.allow from the consuming package's manifest; with no root" >&2 - echo " manifest nothing grants kyberforge's hooks/ and bin/ permission to deploy." >&2 + echo " manifest nothing grants these packages' hooks/ and bin/ permission to deploy." >&2 echo " Fix: restore apm.yml at the repo root." >&2 exit 1 fi @@ -58,16 +105,30 @@ fi # Both readers emit the same line protocol, so the rest of the script does not # care which ran: # -# v exactly once -# apresent|absent exactly once — is executables.allow a mapping? -# k zero or more +# v once per readable plugin (version may be empty) +# n once per readable plugin (name may be empty) +# e zero or more — the plugin's facts are unusable +# apresent|absent exactly once — is executables.allow a mapping? +# k zero or more # # python3 + PyYAML is preferred where importable; the fallback below is not a -# YAML parser, it recognises only the two shapes these manifests use. PyYAML -# stays optional so a missing pip package can't block every push (ADR-0019). +# YAML parser, it recognises only the shapes these manifests use. PyYAML stays +# optional so a missing pip package can't block every push (ADR-0019). + +reader_args() { + local plugin + printf '%s\0' "$ROOT_MANIFEST" + for plugin in ${READABLE[@]+"${READABLE[@]}"}; do + printf '%s\0%s\0' "$plugin" "$REPO_ROOT/plugins/$plugin/apm.yml" + done +} read_facts_python() { - python3 - "$ROOT_MANIFEST" "$PLUGIN_MANIFEST" << 'PY' + local args=() arg + while IFS= read -r -d '' arg; do + args+=("$arg") + done < <(reader_args) + python3 - ${args[@]+"${args[@]}"} << 'PY' import sys import yaml @@ -78,19 +139,25 @@ def load(path): return data if isinstance(data, dict) else {} -root, plugin = load(sys.argv[1]), load(sys.argv[2]) +root = load(sys.argv[1]) +pairs = sys.argv[2:] -version = plugin.get("version") -# A 2-component version parses as a YAML float and would render back as e.g. -# "1.5" from 1.50 — a mismatch invented by the reader rather than found in the -# files. Refuse instead of guessing; semver keys here are always strings. -if version is not None and not isinstance(version, str): - sys.stderr.write( - "kyberforge's version: is not a string (%r) — quote it so the " - "executables.allow key can be compared verbatim.\n" % (version,) - ) - raise SystemExit(2) -print("v\t%s" % ("" if version is None else version)) +for plugin_dir, path in zip(pairs[::2], pairs[1::2]): + plugin = load(path) + version = plugin.get("version") + # A 2-component version parses as a YAML float and would render back as + # e.g. "1.5" from 1.50 — a mismatch invented by the reader rather than + # found in the files. Refuse instead of guessing; semver keys here are + # always strings. + if version is not None and not isinstance(version, str): + print( + "e\t%s\tversion: is not a string (%r) — quote it so the " + "executables.allow key can be compared verbatim." % (plugin_dir, version) + ) + continue + name = plugin.get("name") + print("v\t%s\t%s" % (plugin_dir, "" if version is None else version)) + print("n\t%s\t%s" % (plugin_dir, "" if name is None else name)) executables = root.get("executables") allow = executables.get("allow") if isinstance(executables, dict) else None @@ -114,14 +181,24 @@ unquote() { printf '%s\n' "$value" } -read_facts_bash() { - local line version="" allow_state="absent" in_executables=0 in_allow=0 key - +# top_level_scalar — the first column-0 ':' value, unquoted. +top_level_scalar() { + local line while IFS= read -r line || [[ -n "$line" ]]; do - [[ "$line" == version:* ]] || continue - version="$(unquote "${line#version:}")" - break - done < "$PLUGIN_MANIFEST" + [[ "$line" == "$2:"* ]] || continue + unquote "${line#"$2":}" + return + done < "$1" +} + +read_facts_bash() { + local line allow_state="absent" in_executables=0 in_allow=0 key plugin manifest + + for plugin in ${READABLE[@]+"${READABLE[@]}"}; do + manifest="$REPO_ROOT/plugins/$plugin/apm.yml" + printf 'v\t%s\t%s\n' "$plugin" "$(top_level_scalar "$manifest" version)" + printf 'n\t%s\t%s\n' "$plugin" "$(top_level_scalar "$manifest" name)" + done while IFS= read -r line || [[ -n "$line" ]]; do # Blank and full-line comments carry no structure at any depth. @@ -160,17 +237,17 @@ read_facts_bash() { fi done < "$ROOT_MANIFEST" - printf 'v\t%s\n' "$version" printf 'a\t%s\n' "$allow_state" } if command -v python3 > /dev/null 2>&1 && python3 -c 'import yaml' > /dev/null 2>&1; then READER="python3 + PyYAML" if ! FACTS="$(read_facts_python)"; then - echo "FAIL: could not read apm.yml / plugins/kyberforge/apm.yml (see the parser error above)." >&2 - echo " Why: this gate compares kyberforge's version against root apm.yml's executables.allow" >&2 - echo " key; an unreadable manifest means the comparison did not happen." >&2 - echo " Fix: make both manifests valid YAML, then re-run." >&2 + echo "FAIL: could not read apm.yml or a plugin's apm.yml (see the parser error above)." >&2 + echo " Why: this gate compares each executable-shipping plugin's version against root" >&2 + echo " apm.yml's executables.allow keys; an unreadable manifest means the comparison" >&2 + echo " did not happen." >&2 + echo " Fix: make the manifests valid YAML, then re-run." >&2 exit 1 fi else @@ -178,49 +255,104 @@ else FACTS="$(read_facts_bash)" fi -VERSION="$(printf '%s\n' "$FACTS" | sed -n 's/^v\t//p')" +# fact — the third field of that plugin's line. +fact() { + awk -F'\t' -v t="$1" -v d="$2" '$1 == t && $2 == d { sub(/^[^\t]*\t[^\t]*\t/, ""); print; exit }' <<< "$FACTS" +} + ALLOW_STATE="$(printf '%s\n' "$FACTS" | sed -n 's/^a\t//p')" ALLOW_KEYS="$(printf '%s\n' "$FACTS" | sed -n 's/^k\t//p')" -if [[ -z "$VERSION" ]]; then - echo "FAIL: plugins/kyberforge/apm.yml declares no version:, so no allow key can be checked against it." >&2 - echo " Why: apm's executables.allow lookup is keyed on '#' exactly; with no" >&2 - echo " version there is nothing for root apm.yml's key to stay in sync with." >&2 - echo " Fix: give plugins/kyberforge/apm.yml a top-level version: (read by $READER)." >&2 - exit 1 -fi +# --------------------------------------------------------------------------- +# Per-package checks +# --------------------------------------------------------------------------- +# EXPECTED: plugin dir names whose manifest is usable; the key each needs is +# '#' because a usable manifest's name: equals its dir name. +EXPECTED=() +for plugin in ${READABLE[@]+"${READABLE[@]}"}; do + error="$(fact e "$plugin")" + if [[ -n "$error" ]]; then + echo "FAIL: plugins/$plugin/apm.yml: $error" >&2 + echo " Why: a non-string version would be compared in a form the reader invented rather" >&2 + echo " than the one written in the file." >&2 + echo " Fix: quote the version, e.g. version: \"1.5\" (read by $READER)." >&2 + FAILED=1 + continue + fi -EXPECTED_KEY="kyberforge#$VERSION" + version="$(fact v "$plugin")" + name="$(fact n "$plugin")" -if [[ "$ALLOW_STATE" != "present" ]]; then - echo "FAIL: root apm.yml has no executables.allow mapping, but plugins/kyberforge is version $VERSION." >&2 - echo " Why: without an allow entry apm refuses to deploy kyberforge's hooks/ and bin/, so the" >&2 - echo " SessionStart hook that keeps this install level with the remote never runs and the" >&2 - echo " deployed skills go stale silently (ADR-0019)." >&2 + if [[ "$name" != "$plugin" ]]; then + echo "FAIL: plugins/$plugin/apm.yml declares name: '${name}', which does not match its directory '$plugin'." >&2 + echo " Why: executables.allow keys use the package name; with the two disagreeing this gate" >&2 + echo " cannot tell which '#' key root apm.yml should carry." >&2 + echo " Fix: make plugins/$plugin/apm.yml's name: equal '$plugin', or rename the directory (read by $READER)." >&2 + FAILED=1 + continue + fi + + if [[ -z "$version" ]]; then + echo "FAIL: plugins/$plugin/apm.yml declares no version:, so no allow key can be checked against it." >&2 + echo " Why: the executables.allow key is '#'; with no version there is" >&2 + echo " nothing for root apm.yml's key to stay in sync with." >&2 + echo " Fix: give plugins/$plugin/apm.yml a top-level version: (read by $READER)." >&2 + FAILED=1 + continue + fi + + EXPECTED+=("$plugin") +done + +if [[ ${#EXPECTED[@]} -gt 0 && "$ALLOW_STATE" != "present" ]]; then + summary="" + for plugin in ${EXPECTED[@]+"${EXPECTED[@]}"}; do + summary+="${summary:+, }$plugin#$(fact v "$plugin")" + done + echo "FAIL: root apm.yml has no executables.allow mapping, but these packages ship executables: $summary." >&2 + echo " Why: without an allow entry apm refuses to deploy a package's hooks/ and bin/ — for" >&2 + echo " kyberforge that means the SessionStart hook that keeps this install level with the" >&2 + echo " remote never runs and the deployed skills go stale silently (ADR-0019)." >&2 echo " Fix: add to root apm.yml:" >&2 echo " executables:" >&2 echo " allow:" >&2 - echo " $EXPECTED_KEY:" >&2 - echo " hooks: true" >&2 - echo " bin: true" >&2 + for plugin in ${EXPECTED[@]+"${EXPECTED[@]}"}; do + echo " $plugin#$(fact v "$plugin"):" >&2 + if [[ -d "$REPO_ROOT/plugins/$plugin/.apm/hooks" ]]; then echo " hooks: true" >&2; fi + if [[ -d "$REPO_ROOT/plugins/$plugin/bin" ]]; then echo " bin: true" >&2; fi + done exit 1 fi -if grep -qxF "$EXPECTED_KEY" <<< "$ALLOW_KEYS"; then - exit 0 -fi +for plugin in ${EXPECTED[@]+"${EXPECTED[@]}"}; do + expected_key="$plugin#$(fact v "$plugin")" + if grep -qxF -- "$expected_key" <<< "$ALLOW_KEYS"; then + continue + fi -STALE_KEYS="$(printf '%s\n' "$ALLOW_KEYS" | grep '^kyberforge#' || true)" + stale_keys=() + while IFS= read -r key; do + if [[ -n "$key" && "$key" == "$plugin#"* ]]; then stale_keys+=("$key"); fi + done <<< "$ALLOW_KEYS" -echo "FAIL: root apm.yml's executables.allow has no '$EXPECTED_KEY' key, but that is kyberforge's version." >&2 -if [[ -n "$STALE_KEYS" ]]; then - echo " Found instead:" >&2 - printf '%s\n' "$STALE_KEYS" | sed 's/^/ /' >&2 -fi -echo " Why: nothing is broken right now — apm's grant is version-blind, so a key naming another" >&2 -echo " version still grants kyberforge's hooks/ and bin/. This gate is a repo-level record" >&2 -echo " check: a version bump without the matching key edit fails here, which is what keeps" >&2 -echo " the key an accurate record of what was approved (ADR-0019, 2026-09-19 correction)." >&2 -echo " Fix: bump the key in root apm.yml to '$EXPECTED_KEY:' — the version bump in" >&2 -echo " plugins/kyberforge/apm.yml is not complete without it." >&2 -exit 1 + echo "FAIL: root apm.yml's executables.allow has no '$expected_key' key, but that is $plugin's version." >&2 + if [[ ${#stale_keys[@]} -gt 0 ]]; then + echo " Found instead:" >&2 + printf ' %s\n' ${stale_keys[@]+"${stale_keys[@]}"} >&2 + echo " Why: nothing is broken right now — apm's grant is version-blind, so a key naming another" >&2 + echo " version still grants $plugin's $(ships "$plugin"). This gate is a repo-level record" >&2 + echo " check: a version bump without the matching key edit fails here, which is what keeps" >&2 + echo " the key an accurate record of what was approved (ADR-0019, 2026-09-19 correction)." >&2 + echo " Fix: bump the key in root apm.yml to '$expected_key:' — the version bump in" >&2 + echo " plugins/$plugin/apm.yml is not complete without it." >&2 + else + echo " Why: $plugin ships $(ships "$plugin") and no key grants them, so apm refuses to deploy" >&2 + echo " them; this gate also keeps each key an accurate record of what was approved" >&2 + echo " (ADR-0019, 2026-09-19 correction)." >&2 + echo " Fix: add '$expected_key:' under executables.allow in root apm.yml, granting" >&2 + echo " $(grants "$plugin")." >&2 + fi + FAILED=1 +done + +exit "$FAILED" diff --git a/tests/test-check-executables-allow-sync.sh b/tests/test-check-executables-allow-sync.sh index 6dd7c3a..c3b46b5 100644 --- a/tests/test-check-executables-allow-sync.sh +++ b/tests/test-check-executables-allow-sync.sh @@ -1,11 +1,12 @@ #!/usr/bin/env bash # Tests for scripts/check-executables-allow-sync.sh — the pre-push gate that -# keeps root apm.yml's executables.allow key level with kyberforge's version. +# keeps root apm.yml's executables.allow keys level with the version of every +# plugin that ships executables (plugins//.apm/hooks/ or bin/). # -# Fixtures are two-file skeletons (root apm.yml + plugins/kyberforge/apm.yml) -# rather than copies of the real repo: the gate reads exactly those two files, -# and a hand-built fixture is the only way to construct the drift it exists to -# catch without editing the real manifests. +# Fixtures are skeletons (root apm.yml + plugins//apm.yml + an empty +# hooks/ or bin/ dir) rather than copies of the real repo: the gate reads +# exactly those files, and a hand-built fixture is the only way to construct +# the drift it exists to catch without editing the real manifests. set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -36,7 +37,8 @@ make_fixture() { local version_line="$1" executables_block="$2" dir dir="$(mktemp -d)" FIXTURES+=("$dir") - mkdir -p "$dir/plugins/kyberforge" + # kyberforge ships both hooks and bin, which is what makes the gate check it. + mkdir -p "$dir/plugins/kyberforge/.apm/hooks" "$dir/plugins/kyberforge/bin" { echo "name: kyberforge" @@ -61,6 +63,17 @@ make_fixture() { printf '%s\n' "$dir" } +# add_plugin [] — a second plugin that +# ships hooks only (like delivery). defaults to . +add_plugin() { + local dir="$1/plugins/$2" + mkdir -p "$dir/.apm/hooks" + { + echo "name: ${4:-$2}" + echo "$3" + } > "$dir/apm.yml" +} + MATCHING_BLOCK='executables: allow: kyberforge#1.5.0: @@ -73,6 +86,23 @@ STALE_BLOCK='executables: hooks: true bin: true' +TWO_MATCHING_BLOCK='executables: + allow: + kyberforge#1.5.0: + hooks: true + bin: true + # delivery ships a guard hook; an indented comment must not read as a key. + delivery#0.1.0: + hooks: true' + +TWO_STALE_BLOCK='executables: + allow: + kyberforge#1.4.0: + hooks: true + bin: true + delivery#0.0.9: + hooks: true' + OTHER_PACKAGE_BLOCK='executables: allow: git#1.0.0: @@ -165,17 +195,23 @@ run_gate "$REPO_ROOT/definitely-not-a-directory" [[ $GATE_RC -ne 0 ]] && pass "fails on a nonexistent REPO_ROOT" \ || fail "a bad path must not exit 0 — that reads as 'checked, in sync'" -# No kyberforge plugin at all is the one legitimate no-op: nothing to pin. +# No executable-shipping plugin at all is the one legitimate no-op: nothing to pin. NO_PLUGIN="$(mktemp -d)"; FIXTURES+=("$NO_PLUGIN") echo "name: someone-else" > "$NO_PLUGIN/apm.yml" run_gate "$NO_PLUGIN" -[[ $GATE_RC -eq 0 ]] && pass "no-ops in a repo with no kyberforge plugin" \ - || fail "a repo without plugins/kyberforge/ has nothing to check" +[[ $GATE_RC -eq 0 ]] && pass "no-ops in a repo with no executable-shipping plugin" \ + || fail "a repo without any plugins/*/.apm/hooks or bin has nothing to check" -# ...but a kyberforge directory with no manifest is drift, not a no-op. +# A plugin dir that ships nothing executable is not this gate's business. mkdir -p "$NO_PLUGIN/plugins/kyberforge" run_gate "$NO_PLUGIN" -[[ $GATE_RC -ne 0 ]] && pass "fails when plugins/kyberforge/ has no apm.yml" \ +[[ $GATE_RC -eq 0 ]] && pass "no-ops when plugins/kyberforge/ ships no hooks/ or bin/" \ + || fail "a plugin dir without hooks/ or bin/ has nothing to check" + +# ...but one that ships executables with no manifest is drift, not a no-op. +mkdir -p "$NO_PLUGIN/plugins/kyberforge/.apm/hooks" +run_gate "$NO_PLUGIN" +[[ $GATE_RC -ne 0 ]] && pass "fails when plugins/kyberforge/ ships hooks but has no apm.yml" \ || fail "a plugin dir with no manifest must not silently pass" F="$(make_fixture "description: no version here" "$MATCHING_BLOCK")" @@ -183,6 +219,68 @@ run_gate "$F" [[ $GATE_RC -ne 0 ]] && pass "fails when the plugin manifest declares no version" \ || fail "no version means nothing to compare — must fail, not pass" +# --------------------------------------------------------------------------- +echo "" +echo "--- several executable-shipping plugins ---" +# --------------------------------------------------------------------------- + +F="$(make_fixture "version: 1.5.0" "$TWO_MATCHING_BLOCK")" +add_plugin "$F" delivery "version: 0.1.0" +run_gate "$F" +[[ $GATE_RC -eq 0 ]] && pass "exits 0 when both shipping plugins have matching keys" \ + || fail "two in-sync packages should pass, got rc=$GATE_RC" + +F="$(make_fixture "version: 1.5.0" "$MATCHING_BLOCK")" +add_plugin "$F" delivery "version: 0.1.0" +run_gate "$F" +[[ $GATE_RC -ne 0 ]] && pass "fails when the second package's key is missing" \ + || fail "a shipping plugin with no allow key must fail" +OUT="$(bash "$SCRIPT" "$F" 2>&1 || true)" +grep -q "delivery#0.1.0" <<< "$OUT" && pass "names the second package's expected key" \ + || fail "the failure must state delivery#0.1.0" +grep -q "kyberforge#" <<< "$OUT" && fail "an in-sync kyberforge must not be reported" \ + || pass "does not report the package that is in sync" + +F="$(make_fixture "version: 1.5.0" "$TWO_STALE_BLOCK")" +add_plugin "$F" delivery "version: 0.1.0" +OUT="$(bash "$SCRIPT" "$F" 2>&1 || true)" +grep -q "kyberforge#1.5.0" <<< "$OUT" && grep -q "delivery#0.1.0" <<< "$OUT" \ + && pass "reports every failing package in one run" \ + || fail "both stale packages must be named, got: $OUT" +grep -q "kyberforge#1.4.0" <<< "$OUT" && grep -q "delivery#0.0.9" <<< "$OUT" \ + && pass "quotes back each package's stale key" || fail "each stale key must be quoted back" + +F="$(make_fixture "version: 1.5.0" "")" +add_plugin "$F" delivery "version: 0.1.0" +OUT="$(bash "$SCRIPT" "$F" 2>&1 || true)" +grep -q "kyberforge#1.5.0" <<< "$OUT" && grep -q "delivery#0.1.0" <<< "$OUT" \ + && pass "missing executables.allow lists every package's key to add" \ + || fail "the add-this block must name every shipping package" + +# A plugin with no hooks/ or bin/ needs no key, whatever its version. +F="$(make_fixture "version: 1.5.0" "$MATCHING_BLOCK")" +mkdir -p "$F/plugins/docs-only/.apm/skills" +printf 'name: docs-only\nversion: 9.9.9\n' > "$F/plugins/docs-only/apm.yml" +run_gate "$F" +[[ $GATE_RC -eq 0 ]] && pass "ignores a plugin that ships no hooks/ or bin/" \ + || fail "a plugin without executables must not need an allow key" + +# Keys use the package name, so the dir name and name: must agree. +F="$(make_fixture "version: 1.5.0" "$TWO_MATCHING_BLOCK")" +add_plugin "$F" delivery "version: 0.1.0" "delivery-renamed" +run_gate "$F" +[[ $GATE_RC -ne 0 ]] && pass "fails when a plugin's name: differs from its directory" \ + || fail "a dir/name mismatch must fail" +OUT="$(bash "$SCRIPT" "$F" 2>&1 || true)" +grep -q "delivery-renamed" <<< "$OUT" && pass "names the mismatched name:" \ + || fail "the failure must quote the mismatched name:" + +# A 2-component version is a YAML float; the PyYAML reader refuses to guess. +F="$(make_fixture "version: 1.5" "$MATCHING_BLOCK")" +run_gate "$F" +[[ $GATE_RC -ne 0 ]] && pass "refuses an unquoted 2-component version" \ + || fail "a float version must fail rather than be compared in reader-invented form" + # --------------------------------------------------------------------------- echo "" echo "--- the fallback reader agrees with the PyYAML reader ---" @@ -221,6 +319,22 @@ F="$(make_fixture "version: 1.5.0" "$OTHER_PACKAGE_BLOCK")" run_fallback "$F" [[ $GATE_RC -ne 0 ]] && pass "fallback fails when no kyberforge key is present" || fail "fallback missed an absent key" +F="$(make_fixture "version: 1.5.0" "$TWO_MATCHING_BLOCK")" +add_plugin "$F" delivery "version: 0.1.0" +run_fallback "$F" +[[ $GATE_RC -eq 0 ]] && pass "fallback passes two in-sync packages" || fail "fallback should pass two in-sync packages" + +F="$(make_fixture "version: 1.5.0" "$TWO_STALE_BLOCK")" +add_plugin "$F" delivery "version: 0.1.0" +OUT="$(PATH="$NO_YAML_BIN:$PATH" bash "$SCRIPT" "$F" 2>&1 || true)" +grep -q "kyberforge#1.5.0" <<< "$OUT" && grep -q "delivery#0.1.0" <<< "$OUT" \ + && pass "fallback reports both stale packages" || fail "fallback must name both stale packages" + +F="$(make_fixture "version: 1.5.0" "$TWO_MATCHING_BLOCK")" +add_plugin "$F" delivery "version: 0.1.0" "delivery-renamed" +run_fallback "$F" +[[ $GATE_RC -ne 0 ]] && pass "fallback fails a dir/name mismatch" || fail "fallback missed a dir/name mismatch" + run_fallback "$REPO_ROOT" [[ $GATE_RC -eq 0 ]] && pass "fallback passes the real repo" || fail "fallback disagrees with PyYAML on the real repo" diff --git a/tests/test-delivery-guard-hook.sh b/tests/test-delivery-guard-hook.sh new file mode 100755 index 0000000..579db6d --- /dev/null +++ b/tests/test-delivery-guard-hook.sh @@ -0,0 +1,761 @@ +#!/usr/bin/env bash +# Tests for plugins/delivery/.apm/hooks/guard.py, the delivery guard hook +# (ADR-0032 enforcement layer 2): deny the Never tier everywhere, ask before +# Odd jobs where the runtime honours ask, allow the rest. +# +# The hook tells runtimes apart by where apm deployed it, so each runtime is +# exercised by copying the script to that runtime's deploy path. +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SRC="$REPO_ROOT/plugins/delivery/.apm/hooks/guard.py" +HOOKS_JSON="$REPO_ROOT/plugins/delivery/.apm/hooks/hooks.json" +PASS=0 +FAIL=0 + +pass() { PASS=$((PASS + 1)); } +fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); } + +command -v python3 > /dev/null 2>&1 || { echo "python3 required"; exit 77; } + +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT +for d in .claude/hooks/delivery/.apm/hooks .github/hooks/scripts/delivery/.apm/hooks \ + .codex/hooks/delivery/.apm/hooks elsewhere; do + mkdir -p "$WORK/$d" + cp "$SRC" "$WORK/$d/guard.py" +done +CLAUDE="$WORK/.claude/hooks/delivery/.apm/hooks/guard.py" +COPILOT="$WORK/.github/hooks/scripts/delivery/.apm/hooks/guard.py" +CODEX="$WORK/.codex/hooks/delivery/.apm/hooks/guard.py" +UNKNOWN="$WORK/elsewhere/guard.py" + +# decision