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..6e816f7 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.1.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..8de2d6b 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,16 @@ 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, Copilot's `view`, Codex's `apply_patch`) against the secret-path globs, not only shell + commands. `kubectl`, `helm`, `flux` and `tofu` are allowlists of read verbs: anything not on + the list is denied, so an unlisted mutating verb 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..6acf914 --- /dev/null +++ b/plugins/delivery/.apm/hooks/guard.py @@ -0,0 +1,1275 @@ +#!/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 +A camelCase payload (`toolName`) is also taken as Copilot. +""" + +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." + +# -------------------------------------------------------------------------- +# Secret material: paths an agent never reads +# -------------------------------------------------------------------------- + +SECRET_BASENAME_GLOBS = ( + ".vault_pass*", ".vault-pass*", "vault_pass*", "vault-pass*", + "*vault_password*", "*vault-password*", + "*.tfstate", "*.tfstate.*", + "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "id_ecdsa_sk", "id_ed25519_sk", + "*.key", "key.pem", "*-key.pem", "*_key.pem", "*.key.pem", "privkey*.pem", + "*private*.pem", "*.p12", "*.pfx", +) +# 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", +) +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:]) + for cand in candidates: + cand = cand.strip().rstrip("/") + if not cand: + continue + norm = cand.replace("\\", "/") + # the admin kubeconfig, its backups, and the directory holding them + if norm == ".kube" or norm.endswith("/.kube") or "/.kube/config" in "/" + norm: + return True + base = os.path.basename(norm).lower() + if base.endswith(".pub"): + continue + if any(fnmatch.fnmatchcase(base, g) for g in SECRET_BASENAME_GLOBS): + return True + if GLOB_CHARS & set(base) and _literal_count(base) >= 3: + if any(fnmatch.fnmatchcase(s, base) for s in SECRET_SAMPLES): + return True + parent = os.path.basename(os.path.dirname(norm)) + if parent == ".kube" and fnmatch.fnmatchcase("config", base): + return True + return False + + +# -------------------------------------------------------------------------- +# Shell tokenising +# -------------------------------------------------------------------------- + +OPERATORS = ("&&", "||", ";;", "|&", ";", "|", "&", "\n", "(", ")") +REDIRECTS = ("<<<", "<<-", "<<", ">>", "&>", ">&", "<&", "<>", ">|", "<", ">") + + +class Shell: + """Splits a command line into simple commands (lists of unquoted words). + + Not a full shell parser. It understands quoting, escapes, the control + operators, redirections, here-documents (whose bodies are data, not + commands), and command / process substitution, whose inner text is + analysed as further commands. A word that still holds a parameter + expansion after unquoting is marked dynamic, because its value is unknown. + """ + + def __init__(self, text): + self.text = text + self.i = 0 + self.commands = [] # list of list of (word, dynamic) + self.nested = [] # inner texts of $(...), `...`, <(...), >(...) + self.pending = [] # (delimiter, strip_tabs) of here-docs to skip + + def parse(self): + current = [] + n = len(self.text) + while self.i < n: + c = self.text[self.i] + if c in " \t": + self.i += 1 + continue + if self.text.startswith("\\\n", self.i): + self.i += 2 + continue + if c == "#" and self._at_word_start(): + while self.i < n and self.text[self.i] != "\n": + self.i += 1 + continue + op = self._match(OPERATORS) + if op: + self.i += len(op) + if op == "\n" and self.pending: + self._skip_heredocs() + if current: + self.commands.append(current) + current = [] + continue + if self.text.startswith(("<(", ">("), self.i): + self.i += 1 + self.nested.append(self._balanced("(", ")")) + continue + red = self._match(REDIRECTS) + if red: + self.i += len(red) + if red in ("<<", "<<-"): + while self.i < n and self.text[self.i] in " \t": + self.i += 1 + delim, _ = self._word() + self.pending.append((delim, red == "<<-")) + # any other redirect target stays a word of this command, so a + # `< .vault_pass` is caught by the secret-path check + continue + word, dynamic = self._word() + current.append((word, dynamic)) + if current: + self.commands.append(current) + return self + + def _skip_heredocs(self): + n = len(self.text) + for delim, strip_tabs in self.pending: + while self.i < n: + end = self.text.find("\n", self.i) + end = n if end == -1 else end + line = self.text[self.i:end] + self.i = min(end + 1, n) + if (line.lstrip("\t") if strip_tabs else line) == delim: + break + self.pending = [] + + def _at_word_start(self): + return self.i == 0 or self.text[self.i - 1] in " \t\n;&|()" + + def _match(self, ops): + for op in ops: + if self.text.startswith(op, self.i): + return op + return None + + def _balanced(self, open_c, close_c): + # self.i is at open_c + depth, start = 0, self.i + 1 + n = len(self.text) + quote = None + while self.i < n: + c = self.text[self.i] + if quote: + if c == "\\" and quote == '"': + self.i += 2 + continue + if c == quote: + quote = None + elif c in "'\"": + quote = c + elif c == "\\": + self.i += 2 + continue + elif c == open_c: + depth += 1 + elif c == close_c: + depth -= 1 + if depth == 0: + inner = self.text[start:self.i] + self.i += 1 + return inner + self.i += 1 + return self.text[start:] + + def _backtick(self): + start = self.i + 1 + self.i += 1 + n = len(self.text) + while self.i < n and self.text[self.i] != "`": + if self.text[self.i] == "\\": + self.i += 1 + self.i += 1 + inner = self.text[start:self.i] + self.i += 1 + return inner + + def _word(self): + out = [] + dynamic = False + n = len(self.text) + while self.i < n: + c = self.text[self.i] + if c in " \t\n;&|()<>": + break + if c == "\\": + if self.i + 1 < n and self.text[self.i + 1] != "\n": + out.append(self.text[self.i + 1]) + self.i += 2 # a backslash-newline is a line continuation + elif c == "'": + end = self.text.find("'", self.i + 1) + end = n if end == -1 else end + out.append(self.text[self.i + 1:end]) + self.i = end + 1 + elif c == '"': + self.i += 1 + while self.i < n and self.text[self.i] != '"': + d = self.text[self.i] + if d == "\\" and self.i + 1 < n and self.text[self.i + 1] in '"\\$`\n': + if self.text[self.i + 1] != "\n": + out.append(self.text[self.i + 1]) + self.i += 2 + elif d == "$" and self.text.startswith("$(", self.i): + self.i += 1 + self.nested.append(self._balanced("(", ")")) + dynamic = True + elif d == "`": + self.nested.append(self._backtick()) + dynamic = True + elif d == "$" and self.i + 1 < n and re.match(r"[A-Za-z_{0-9@*#?!$-]", self.text[self.i + 1]): + out.append(d) + dynamic = True + self.i += 1 + else: + out.append(d) + self.i += 1 + self.i += 1 + elif c == "$" and self.text.startswith("$'", self.i): + self.i += 1 + end = self.text.find("'", self.i + 1) + end = n if end == -1 else end + raw = self.text[self.i + 1:end] + try: + raw = raw.encode("latin-1", "backslashreplace").decode("unicode_escape") + except Exception: + pass + out.append(raw) + self.i = end + 1 + elif c == "$" and self.text.startswith("$(", self.i): + self.i += 1 + self.nested.append(self._balanced("(", ")")) + dynamic = True + elif c == "`": + self.nested.append(self._backtick()) + dynamic = True + elif c == "$" and self.i + 1 < n and re.match(r"[A-Za-z_{0-9@*#?!$-]", self.text[self.i + 1]): + out.append(c) + dynamic = True + self.i += 1 + else: + out.append(c) + self.i += 1 + return "".join(out), dynamic + + +# -------------------------------------------------------------------------- +# 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"} +# Words that only prefix the real command. Matched on the basename, so +# /usr/bin/time and /usr/bin/nohup count. +KEYWORDS = {"!", "{", "}", "then", "do", "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"}, +} +ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=") +GUARDED = re.compile( + r"\b(kubectl|kubecolor|helm|helm3|tofu|terraform|terragrunt|ansible-playbook|" + r"ansible-vault|ansible|ansible-pull|ansible-console|kubeseal|flux|sops|" + r"pre-commit)\b" + r"|--no-verif|hookspath|\bSKIP\+?=|vault.pass|\.tfstate|id_rsa|id_ed25519|\.kube", + re.I, +) +BRACE = re.compile(r"\{[^{}]*,[^{}]*\}") +# Options whose value a tool reads itself on the agent's behalf, as Ansible +# does with the vault password file and the SSH key. Such a run is an Odd job. +SECRET_ARG_EXEMPT = ("--vault-password-file", "--vault-pass-file", "--vault-id", + "--private-key", "--key-file") +SEARCHERS = {"grep", "egrep", "fgrep", "rg", "ag", "ack"} +SEARCH_VALUE_OPTS = {"-A", "-B", "-C", "-m", "-d", "-D", "-g", "-t", "-T", + "--include", "--exclude", "--exclude-dir", "--glob", + "--type", "--max-count", "--context", "--after-context", + "--before-context"} +# Programs that only print their arguments or look at file metadata. +NEUTRAL = {"echo", "printf", "ls", "stat", "test", "[", "[[", "true", ":"} +# Tool runners: args. Ansible repos commonly +# run their tools through a project venv this way. +RUNNERS = { + "uv": {"run", "tool"}, "poetry": {"run"}, "pipenv": {"run"}, "pdm": {"run"}, + "hatch": {"run"}, "pipx": {"run"}, "direnv": {"exec"}, "mise": {"exec", "x"}, + "devbox": {"run"}, "uvx": None, +} + + +def assignment_verdict(word): + name, value = word.split("=", 1) + name = name.rstrip("+") + low = value.lower() + if name == "SKIP": + return deny("SKIP= skips pre-commit hooks; " + 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 is_secret_path(value): + return deny("'%s' is secret material; agents never read it." % value) + return OK + + +def search_pattern_indexes(args): + """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 SEARCH_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 secret_words(prog_word, prog, args): + if prog in NEUTRAL: + return OK + if prog == "git": + sub_idx = _git_sub_index(args) + sub = args[sub_idx] if sub_idx is not None else "" + if sub in ("rm", "check-ignore", "ls-files", "status"): + return OK + skip = set() + if prog in SEARCHERS: + skip = search_pattern_indexes(args) + elif prog == "git" and sub == "grep": + skip = {i + sub_idx + 1 for i in search_pattern_indexes(args[sub_idx + 1:])} + if is_secret_path(prog_word): + return deny("'%s' is secret material; agents never run or read it." % prog_word) + skip_next = False + for idx, w in enumerate(args): + if skip_next: + skip_next = False + continue + if idx in skip: + continue + if w in SECRET_ARG_EXEMPT: + skip_next = True + continue + if w.startswith(tuple(e + "=" for e in SECRET_ARG_EXEMPT)): + continue + 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 + + +class Analyzer: + def __init__(self): + self.depth = 0 + + def text(self, command): + """Verdict for a whole command line.""" + if self.depth > 8: + return deny("Command nesting too deep for the guard to read; simplify it.") + self.depth += 1 + try: + sh = Shell(command).parse() + verdict = OK + for words in sh.commands: + verdict = verdict.merge(self.simple(words, command)) + for inner in sh.nested: + verdict = verdict.merge(self.text(inner)) + return verdict + finally: + self.depth -= 1 + + def simple(self, words, whole): + joined = " ".join(w for w, _ in words) + if any(BRACE.search(w) for w, _ in words) and GUARDED.search(joined): + return deny("Brace expansion hides what this command runs; write it " + "out literally.") + return self.program(list(words), whole) + + def program(self, words, whole): + verdict = OK + # leading assignments: NAME=value cmd ... + while words and ASSIGNMENT.match(words[0][0]): + verdict = verdict.merge(assignment_verdict(words[0][0])) + words = words[1:] + while words and os.path.basename(words[0][0]) in KEYWORDS: + head = os.path.basename(words[0][0]) + words = words[1:] + if head == "command" and words and words[0][0] in ("-v", "-V"): + return verdict + if head == "coproc" and len(words) >= 2 and words[1][0] == "{": + words = words[1:] + while words and words[0][0].startswith("-") and len(words[0][0]) > 1: + opt = words[0][0] + words = words[1:] + if opt == "--": + break + if (head, opt) in KEYWORD_VALUE_OPTS: + words = words[1:] + while words and ASSIGNMENT.match(words[0][0]): + verdict = verdict.merge(assignment_verdict(words[0][0])) + words = words[1:] + if not words or verdict.decision == DENY: + return verdict + prog_word, prog_dynamic = words[0] + if prog_dynamic: + # The program name is only known at run time. Fail safe when the + # line mentions a guarded tool at all. + if GUARDED.search(whole): + 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 = os.path.basename(prog_word) + args = [w for w, _ in words[1:]] + + if prog in ("export", "declare", "typeset", "local", "readonly"): + for a in args: + if ASSIGNMENT.match(a): + verdict = verdict.merge(assignment_verdict(a)) + return verdict + if prog in SHELLS: + return verdict.merge(self.shell(args, whole)) + if prog == "eval": + return verdict.merge(self.text(" ".join(args))) + if prog in WRAPPERS: + return verdict.merge(self.wrapper(prog, words[1:], whole)) + if prog == "busybox" and args: + return verdict.merge(self.program(words[1:], whole)) + if prog == "find": + verdict = verdict.merge(self.find_exec(args)) + if prog == "rtk": + return verdict.merge(self.rtk(words[1:], whole)) + if prog in RUNNERS: + return verdict.merge(self.runner(prog, words[1:], whole)) + + verdict = verdict.merge(secret_words(prog_word, prog, args)) + rule = RULES.get(prog) + if rule: + verdict = verdict.merge(rule(args, self)) + return verdict + + def shell(self, args, whole): + idx = 0 + 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: + if "c" in a[1:]: + j = idx + 1 + while j < len(args) and args[j] in SHELL_VALUE_OPTS: + j += 2 + return self.text(args[j]) if j < len(args) else OK + idx += 1 + continue + break + rest = args[idx:] + if not rest: + # The shell reads its commands from stdin: a pipe or here-doc the + # guard cannot follow. + if GUARDED.search(whole): + return deny("A shell reading commands from stdin hides what it runs; " + "run the command directly.") + return OK + # bash script.sh, or a here-string (`bash <<< 'cmd'`), whose word lands here + verdict = OK + for r in rest: + verdict = verdict.merge(self.text(r)) + return verdict + + def rtk(self, words, whole): + # 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][0].startswith("-"): + words = words[1:] + if not words: + return OK + sub = words[0][0] + if sub == "run": + return self.text(" ".join(w for w, _ in words[1:])) + if sub in ("proxy", "err", "test", "summary"): + return self.program(words[1:], whole) + return self.program(words, whole) + + def runner(self, prog, words, whole): + subs = RUNNERS[prog] + start = 0 + if subs is not None: + while start < len(words) and words[start][0].startswith("-"): + start += 1 + if start >= len(words) or words[start][0] not in subs: + return OK + start += 1 + # 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. + for idx in range(start, len(words)): + base = os.path.basename(words[idx][0]) + if base in RULES or base in SHELLS or base in WRAPPERS or \ + base in ("eval", "rtk") or base in RUNNERS: + return self.program(words[idx:], whole) + 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 + inner = [(w, False) for w in args[idx + 1:end]] + verdict = verdict.merge(self.program(inner, " ".join(args))) + idx = end + idx += 1 + return verdict + + def wrapper(self, prog, words, whole): + 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][0]) + if w.startswith("--command="): + return self.text(w.split("=", 1)[1]) + return OK + if prog == "watch": + rest = self._skip_opts(words, takes_value) + return self.text(" ".join(w for w, _ in rest)) + if prog == "ssh": + rest = self._skip_opts(words, takes_value) + if len(rest) > 1: + return self.text(" ".join(w for w, _ in rest[1:])) + return OK + if prog == "parallel": + rest = self._skip_opts(words, takes_value) + cmd = [] + for w in rest: + if w[0] in (":::", "::::", ":::+", "::::+"): + break + cmd.append(w) + return self.program(cmd, whole) + 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][0]): + return deny("'%s' is secret material; agents never read it." + % words[idx + 1][0]) + if prog == "env": + idx = 0 + verdict = OK + while idx < len(words): + w = words[idx][0] + if w in ("-S", "--split-string") and idx + 1 < len(words): + return self.text(words[idx + 1][0] + " " + + " ".join(x for x, _ in words[idx + 2:])) + if w.startswith("--split-string="): + return self.text(w.split("=", 1)[1] + " " + + " ".join(x for x, _ in words[idx + 1:])) + if w in takes_value: + idx += 2 + continue + if w.startswith("-"): + idx += 1 + continue + if ASSIGNMENT.match(w): + verdict = verdict.merge(assignment_verdict(w)) + idx += 1 + continue + break + return verdict.merge(self.program(words[idx:], whole)) + rest = self._skip_opts(words, takes_value) + if prog == "timeout" and rest: + rest = rest[1:] # DURATION + if prog in ("taskset", "chrt") and rest: + rest = rest[1:] # mask / priority + if prog == "flock" and rest: + rest = rest[1:] # lock file + if len(rest) >= 2 and rest[0][0] in ("-c", "--command"): + return self.text(rest[1][0]) + return self.program(rest, whole) + + @staticmethod + def _skip_opts(words, takes_value): + idx = 0 + while idx < len(words): + w = words[idx][0] + if w == "--": + idx += 1 + break + if w in 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) + + +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=None): + 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.") + 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 any(a == "--dry-run=client" for a in rest) or \ + verb == "create" and any(a == "--dry-run" and j + 1 < len(rest) and + rest[j + 1] == "client" for j, a in enumerate(rest)): + # 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 a read verb. Direct cluster changes never happen " + "from an agent; every change applies by approved merge." % verb) + + +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=None): + 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", "hooks"): + return OK + return deny("'helm get %s' prints release values or manifests, which can " + "hold secret material." % (sub or "")) + if verb == "plugin": + sub = rest[0] if rest else "" + if sub in ("list", "ls"): + return OK + return deny("'helm %s' changes a release or the cluster. Releases change only " + "by approved merge." % verb) + + +TOFU_READ = {"init", "validate", "fmt", "plan", "providers", "version", "graph", + "get", "metadata", "modules", "help"} + + +def tofu(args, an=None): + # -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 == "run-all": # terragrunt + return tofu(rest, an) + 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 any(a.lstrip("-").split("=")[0] in ("json", "raw") for a in rest): + return deny("'tofu output -json/-raw' prints sensitive outputs in clear.") + return OK + if verb == "show": + if any(a.lstrip("-").split("=")[0] == "json" for a in rest): + 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 any(a.lstrip("-").split("=")[0] == "destroy" for a in rest): + 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) + + +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=None): + if _ansible_check_mode(args): + return OK + return ask("'ansible-playbook' without --check changes real hosts.") + + +def ansible_adhoc(args, an=None): + 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=None): + if _ansible_check_mode(args): + return OK + return ask("'ansible-pull' without --check changes real hosts.") + + +def ansible_console(args, an=None): + return ask("'ansible-console' runs modules on real hosts.") + + +def ansible_vault(args, an=None): + idx, 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=None): + 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=None): + # 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.") + + +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=None): + 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 any(a.split("=", 1)[0] == "--show-values" for a in rest): + return deny("'flux debug --show-values' can print values pulled from Secrets.") + if verb in FLUX_READ: + return OK + if verb == "export": + if any(a.split("=", 1)[0] == "--with-credentials" for a in rest): + 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"} +GIT_COMMIT_VALUE_SHORT = set("mFcCt") + + +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_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) + if "=" in value: + key, val = value.split("=", 1) + if key.lower().startswith("alias.") and val.startswith("!") and an: + return an.text(val[1:]) + return OK + + +def git(args, an=None): + 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:] + # 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 rest): + return deny("'--no-verify' skips the repo's git hooks; " + HOOK_BYPASS) + if sub == "config": + for j, a in enumerate(rest): + if a.lower() == "core.hookspath" and j + 1 < len(rest) and \ + not any(x in ("--get", "--get-all", "-l", "--list", "--unset", + "--unset-all") for x in rest): + return deny("Setting core.hooksPath skips the repo's git hooks; " + + HOOK_BYPASS) + if sub == "rebase" and an: + 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 an and rest[:1] == ["run"]: + verdict = verdict.merge(an.program([(w, False) for w in rest[1:]], " ".join(rest))) + if sub == "submodule" and an 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": + skip = False + for a in rest: + if skip: + skip = False + continue + if a in ("--message", "--file", "--reuse-message", "--reedit-message", + "--template", "--author", "--date", "--cleanup", "--fixup", + "--squash", "--trailer"): + skip = True + continue + if a.startswith("-") and not a.startswith("--") and len(a) > 1: + letters = a[1:] + for pos, ch in enumerate(letters): + if ch == "n": + return deny("'git commit -n' is --no-verify; it skips the " + "repo's git hooks.") + if ch in GIT_COMMIT_VALUE_SHORT: + if pos == len(letters) - 1: + skip = True + break + return verdict + + +def pre_commit(args, an=None): + idx, 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, "kubectl.exe": kubectl, "kubecolor": kubectl, + "helm": helm, "helm3": helm, + "tofu": tofu, "terraform": tofu, "terragrunt": tofu, + "ansible-playbook": ansible_playbook, + "ansible": ansible_adhoc, + "ansible-pull": ansible_pull, + "ansible-console": ansible_console, + "ansible-vault": ansible_vault, + "kubeseal": kubeseal, + "sops": sops, + "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"} +PATH_KEYS = ("file_path", "path", "notebook_path", "filePath", "absolute_path") + + +def analyse_tool(tool, tool_input): + if not isinstance(tool_input, dict): + tool_input = {} + lname = (tool or "").lower() + if lname in SHELL_TOOLS: + cmd = tool_input.get("command", "") + if isinstance(cmd, list): + cmd = " ".join(_quote(c) for c in cmd) + return Analyzer().text(str(cmd)) + if lname == "apply_patch": + cmd = str(tool_input.get("command", "") or tool_input.get("input", "")) + for m in re.finditer(r"^\*\*\* (?:Add|Update|Delete) File: (.+)$", cmd, re.M): + if is_secret_path(m.group(1).strip()): + return deny("'%s' is secret material; agents never touch it." % m.group(1).strip()) + return OK + for key in PATH_KEYS: + val = tool_input.get(key) + if isinstance(val, str) and is_secret_path(val): + return deny("'%s' is secret material (vault password, private key, " + "admin kubeconfig or tofu state); agents never read it." % val) + 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): + s = str(s) + if re.match(r"^[A-Za-z0-9_./=:@%+,-]+$", s): + return s + return "'" + s.replace("'", "'\\''") + "'" + + +def detect_runtime(payload=None): + 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" + if isinstance(payload, dict) and "toolName" in payload: + return "copilot" + return "unknown" + + +def read_payload(raw): + payload = json.loads(raw) if raw.strip() else {} + if not isinstance(payload, dict): + raise ValueError("payload is not an object") + if "toolName" in payload: + tool = payload.get("toolName") + args = payload.get("toolArgs") + if isinstance(args, str): + try: + args = json.loads(args) + except ValueError: + args = {"command": args} + return tool, 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 or "PreToolUse", + "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(): + raw = sys.stdin.read() + runtime = detect_runtime() + event = "PreToolUse" + try: + payload = json.loads(raw) if raw.strip() else {} + if isinstance(payload, dict): + runtime = detect_runtime(payload) + event = payload.get("hook_event_name") or event + tool, tool_input = read_payload(raw) + verdict = analyse_tool(tool, tool_input) + 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.dont_write_bytecode = True + 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/docs/guard-hook.md b/plugins/delivery/docs/guard-hook.md new file mode 100644 index 0000000..4c65148 --- /dev/null +++ b/plugins/delivery/docs/guard-hook.md @@ -0,0 +1,120 @@ +# 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` verbs outside the read allowlist, `helm`/`helm3` install/upgrade/uninstall/rollback, `helm get values/manifest/all`, `flux suspend/delete/…`, `flux debug --show-values`, `tofu`/`terraform`/`terragrunt destroy`, `tofu apply -destroy`, `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+=`, `core.hooksPath` overrides (`-c`, `--config-env`, `GIT_CONFIG_*`, `git config`), git aliases carrying `--no-verify`, `pre-commit uninstall`, `ansible-vault view/decrypt/edit/rekey`, `kubeseal --recovery-*`, `sops` in any decrypting mode (including bare `sops `), `kubectl get secret -o …`/`--template`, `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`, `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`, `kubectl wait`, and +`kubectl create … --dry-run=client` (which renders a Secret to pipe into `kubeseal`) all write local +files or caches. `--help` is always allowed. + +Secret paths are basename globs: `.vault_pass*`, `vault_pass*`, `*vault_password*` (and the `-` +spellings), `*.tfstate`, `*.tfstate.*`, `id_rsa`/`id_ed25519`/`id_ecdsa`/`id_dsa`, `*.key`, +`key.pem`, `*-key.pem`, `*_key.pem`, `privkey*.pem`, `*private*.pem`, `*.p12` and `*.pfx`. Also +covered: anything under `.kube/config` (backups included) and the `.kube` directory itself. A shell +glob with at least three literal characters (`.vault_pa*`) counts if it could expand to one of +these. + +Exemptions: +- `.pub` files. +- The values of `--vault-password-file`, `--vault-id`, `--private-key` and `--key-file`. Ansible + reads those itself, and that run is already an Odd job. +- `ssh -i`, for the same reason. +- 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. +- Programs that only print or stat their arguments: `echo`, `printf`, `ls`, `stat`, `test`. +- `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. + +## How it reads a command + +The script tokenises the shell line itself. It handles: +- quoting and escapes, including backslash-newline +- `;`, `&&`, `||`, `|`, newlines, subshells and braces +- here-documents, whose bodies are treated as data, not commands, so commit messages and PR bodies + may name any command + +It analyses the inner text of `$(…)`, backticks, `<(…)` and `>(…)` as further commands. It also +unwraps: +- shells: `bash`/`sh`/… `-c` (including clusters such as `-lc` and `-o opt -c`), here-strings, and + a shell reading stdin, which is denied when the line mentions a guarded tool +- `eval`, and leading `NAME=value` / `NAME+=value` assignments +- `env` (including `-S`), `sudo`, `doas`, `su -c`, `script -c`, `flock`, `strace`, `systemd-run`, + `busybox` +- `nohup`, `setsid`, `time`, `command` and `exec` (by basename, with their options) +- `timeout`, `nice`, `xargs`, `parallel`, `watch`, `find -exec`, `ssh host ` +- 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` + +It takes the program's basename, so `/usr/bin/kubectl` and `\kubectl` are both `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 brace expansion hides a guarded +command. + +**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 +- 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. | + +## 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), the per-runtime output shape, fail-closed handling of malformed payloads, 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..e909310 --- /dev/null +++ b/tests/test-delivery-guard-hook.sh @@ -0,0 +1,448 @@ +#!/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