feat(delivery): add the guard hook (ADR-0032 layer 2)

Ship one pre-tool-use hook in the delivery package. It denies the Never
tier on every runtime and asks before Odd jobs on Claude Code and Copilot
CLI (denying them on Codex and unknown runtimes):

- guard.py: stdlib-only Python; tokenises the shell line, unwraps
  bash -c / env / sudo / eval / xargs / find -exec / rtk / uv run and
  friends, checks file-tool paths for secret material, and uses read-verb
  allowlists for kubectl, helm, flux and tofu
- hooks.json: no matcher, onFailure: block, 10s timeout
- tests/test-delivery-guard-hook.sh: 281 cases incl. bypass attempts and
  per-runtime output shape
- root apm.yml: executables.allow delivery#0.1.0
- check-executables-allow-sync now covers every plugin shipping hooks/bin
- ADR-0032 amended: Copilot ask kept as an accepted risk, file tools and
  allowlists recorded

Refs #190

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012CqgnwEGtmfsjcoG9QwByN
This commit is contained in:
Defame1297andClaude Opus 5.5 committed 2026-11-23 08:15:14 +00:00
1 parent 6edd66432c
commit a6ff1c14d4
11 files changed
+2244 -110

No files matched your search

+5
View File
@@ -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
+2 -2
View File
@@ -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 "<package>#<version>" 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 "<name>#<version>" key matching the apm.yml version of every plugin that ships executables (plugins/<name>/.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]
+4
View File
@@ -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
@@ -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;
+21 -11
View File
@@ -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 `<name>#<version>` 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 `<package>#<version>`, 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#<version>` 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/<name>/.apm/hooks/` or
`plugins/<name>/bin/` exists — kyberforge ships both, delivery ships a guard hook. For each one it
reads `name:` and `version:` from `plugins/<name>/apm.yml` and asserts root `apm.yml` carries the
`<name>#<version>` 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 `<name>#<other-version>` 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`
+1275
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
{
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"command": "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/guard.py",
"onFailure": "block",
"timeout": 10,
"type": "command"
}
]
}
]
}
}
+120
View File
@@ -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 <file>`), `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 <cmd>`
- git's own shell-outs: `rebase --exec`, `bisect run`, `submodule foreach` and `!` aliases
- `rtk` (`rtk <tool>`, `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.
+218 -86
View File
@@ -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 '<package>#<version>' (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/<name>/.apm/hooks/ or plugins/<name>/bin/ exists; each one needs
# a '<name>#<version>' key, where <name> and <version> come from its own
# apm.yml (and <name> 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 '<package>#<version>' (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<TAB><kyberforge version> exactly once
# a<TAB>present|absent exactly once — is executables.allow a mapping?
# k<TAB><allow key> zero or more
# v<TAB><plugin dir><TAB><version> once per readable plugin (version may be empty)
# n<TAB><plugin dir><TAB><name> once per readable plugin (name may be empty)
# e<TAB><plugin dir><TAB><message> zero or more — the plugin's facts are unusable
# a<TAB>present|absent exactly once — is executables.allow a mapping?
# k<TAB><allow key> 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 <file> <key> — the first column-0 '<key>:' 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 <tag> <plugin dir> — the third field of that plugin's <tag> 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 '<package>#<version>' 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
# '<dir>#<version>' 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 '<name>#<version>' 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 '<package>#<version>'; 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"
+125 -11
View File
@@ -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/<name>/.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/<name>/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 <fixture> <dir> <version-line> [<name>] — a second plugin that
# ships hooks only (like delivery). <name> defaults to <dir>.
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"
+448
View File
@@ -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 <script> <payload-json> -> prints allow|ask|deny
decision() {
local script="$1" payload="$2" out rc
set +e
out="$(printf '%s' "$payload" | python3 "$script" 2> /dev/null)"
rc=$?
set -e
if [[ $rc -eq 2 ]]; then
echo deny
return
fi
if [[ $rc -ne 0 ]]; then
echo "error($rc)"
return
fi
if [[ -z "$out" ]]; then
echo allow
return
fi
python3 -c '
import json, sys
d = json.loads(sys.argv[1])
print(d.get("permissionDecision") or d["hookSpecificOutput"]["permissionDecision"])
' "$out"
}
claude_bash() {
python3 -c 'import json,sys; print(json.dumps({"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":sys.argv[1]}}))' "$1"
}
expect_claude() {
local want="$1" cmd="$2" got
got="$(decision "$CLAUDE" "$(claude_bash "$cmd")")"
if [[ "$got" == "$want" ]]; then pass; else fail "claude: want $want, got $got: $cmd"; fi
}
echo "== Shell commands on Claude Code"
# Each line: expected<TAB>command
while IFS=$'\t' read -r want cmd; do
[[ -z "$want" || "$want" == \#* ]] && continue
expect_claude "$want" "$cmd"
done << 'CASES'
# --- Read tier: allowed
allow ls -la
allow git status && git diff --stat
allow kubectl get pods -A
allow kubectl -n flux-system get kustomizations
allow kubectl describe secret db-creds
allow kubectl get secrets
allow kubectl get secrets -o name
allow kubectl logs deploy/app -c main --tail=50
allow kubectl config view
allow kubectl auth can-i get pods
allow kubectl rollout status deploy/app
allow kubectl kustomize clusters/home
allow helm template charts/app
allow helm list -A
allow helm get notes app
allow flux get kustomizations -A
allow flux build kustomization apps --path ./clusters/home --dry-run
allow flux create source git x --url=https://example.com --export
allow tofu plan -out=plan.tfplan
allow tofu -chdir=infra validate
allow tofu state list
allow tofu show plan.tfplan
allow tofu output
allow ansible-playbook site.yml --check --diff
allow ansible-playbook -C site.yml
allow ansible-playbook -vC site.yml
allow ansible-playbook site.yml --syntax-check
allow ansible-playbook site.yml --list-tasks
allow ansible-lint playbooks/
allow ansible-inventory --graph
allow ansible-vault encrypt_string --stdin-name x
allow kubeseal --cert pub-cert.pem -o yaml < secret.yaml
allow git commit -m "fix: rename id_rsa handling"
allow git commit -am "msg"
allow git commit -m "-n is fine inside a message"
allow git push -n origin feat/x
allow git push origin feat/x
allow grep -rn vault_password_file ansible.cfg
allow echo "do not run kubectl apply here"
allow ssh-keygen -y -f /dev/null; cat id_rsa.pub
allow molecule test
allow command -v kubectl
allow pre-commit run --all-files
allow "$PYTHON" script.py && git log
# --- Never tier: direct cluster mutation
deny kubectl apply -f deploy.yaml
deny kubectl -n prod delete pod x
deny kubectl edit deploy/app
deny kubectl patch deploy app -p '{}'
deny kubectl scale deploy/app --replicas=0
deny kubectl rollout restart deploy/app
deny kubectl label node n1 a=b
deny kubectl exec -it pod -- sh
deny kubectl create secret generic x --from-literal=a=b
deny kubectl diff -f deploy.yaml
deny helm install app charts/app
deny helm upgrade --install app charts/app
deny helm uninstall app
deny helm rollback app 1
deny helm get values app
deny flux suspend kustomization apps
deny flux delete source git x
deny flux export source git --all --with-credentials
# --- Never tier: tofu
deny tofu destroy
deny terraform destroy -auto-approve
deny tofu apply -destroy
deny tofu state rm aws_instance.x
deny tofu state mv a b
deny tofu state pull
deny tofu state show aws_instance.x
deny tofu show
deny tofu output -json
deny tofu taint aws_instance.x
# --- Never tier: hook bypass
deny git commit --no-verify -m x
deny git commit -n -m x
deny git commit -nm x
deny git push --no-verify
deny SKIP=ansible-lint git commit -m x
deny export SKIP=all
deny git -c core.hooksPath=/dev/null commit -m x
deny git config core.hooksPath /tmp/none
# --- Never tier: secrets
deny ansible-vault view group_vars/all/vault.yml
deny ansible-vault decrypt group_vars/all/vault.yml
deny ansible-vault edit group_vars/all/vault.yml
deny ansible-vault rekey vault.yml
deny kubeseal --recovery-unseal --recovery-private-key key.pem < s.yaml
deny sops -d secrets.enc.yaml
deny kubectl get secret db-creds -o yaml
deny kubectl get secrets -n kube-system -ojsonpath='{.items}'
deny kubectl get secret/db-creds --output=json
deny kubectl config view --raw
deny cat .vault_pass
deny cat ~/.ansible/vault_password.txt
deny head -1 /root/.ssh/id_ed25519
deny less terraform.tfstate
deny cp terraform.tfstate.backup /tmp/x
deny cat ~/.kube/config
deny base64 < .vault_pass
deny git add .vault_pass
deny cat tls.key
# --- Odd jobs: ask
ask ansible-playbook site.yml
ask ansible-playbook -i inventory/prod site.yml --limit web
ask ansible-playbook site.yml --vault-password-file .vault_pass
ask ansible-playbook site.yml --private-key ~/.ssh/id_ed25519
ask ansible all -m shell -a uptime
ask tofu apply plan.tfplan
ask terraform apply -auto-approve
ask flux reconcile kustomization apps --with-source
# --- Bypass attempts
deny bash -c "kubectl apply -f x.yaml"
deny sh -lc 'kubectl delete ns prod'
deny bash -c "bash -c 'helm uninstall app'"
deny env kubectl apply -f x
deny env -i PATH=/usr/bin kubectl apply -f x
deny env -S "kubectl apply -f x"
deny FOO=1 kubectl apply -f x
deny /usr/local/bin/kubectl apply -f x
deny \kubectl apply -f x
deny "kubectl" apply -f x
deny k'ube'ctl apply -f x
deny ku\bectl apply -f x
deny sudo -u root kubectl apply -f x
deny sudo -E helm upgrade app charts/app
deny nohup kubectl delete pod x &
deny timeout 30 kubectl apply -f x
deny nice -n 10 tofu destroy
deny command kubectl apply -f x
deny exec kubectl apply -f x
deny echo x | xargs kubectl delete pod
deny find . -name '*.yaml' -exec kubectl apply -f {} \;
deny true && kubectl apply -f x
deny false || kubectl apply -f x
deny ls; kubectl apply -f x
deny ls | kubectl apply -f -
deny (kubectl apply -f x)
deny { kubectl apply -f x; }
deny if true; then kubectl apply -f x; fi
deny echo $(kubectl delete pod x)
deny echo "$(ansible-vault view v.yml)"
deny echo `kubectl apply -f x`
deny diff <(kubectl get secret x -o yaml) a.yaml
deny eval "kubectl apply -f x"
deny eval kubectl delete pod x
deny k=kubectl; $k apply -f x
deny "$(which kubectl)" apply -f x
deny watch -n 5 kubectl delete pod x
deny kubectl --context prod apply -f x
deny kubectl --kubeconfig=/tmp/k apply -f x
deny helm -n prod upgrade app charts/app
deny git -C /repo commit --no-verify -m x
deny env SKIP=ansible-lint git commit -m x
deny cat .vault_pass | base64
deny cat .vault""_pass
deny $'kubectl' apply -f x
ask bash -c 'ansible-playbook site.yml'
ask sudo ansible-playbook site.yml
# --- Runners: rtk (mandated in some repos) and project-venv runners
allow rtk git status
allow rtk kubectl get pods
deny rtk kubectl apply -f x
deny rtk git commit --no-verify -m x
deny rtk run "kubectl delete pod x"
deny rtk proxy helm upgrade app charts/app
deny rtk read .vault_pass
allow uv run ansible-playbook site.yml --check
ask uv run ansible-playbook site.yml
ask poetry run ansible-playbook site.yml
deny uv run --with x ansible-vault view v.yml
ask direnv exec . ansible-playbook site.yml
allow uv sync
# --- Regressions from the factory-audit review: bypasses that got allow
deny git commit --no-verif -m x
deny git commit --no-ve -m x
deny git --config-env=core.hooksPath=HP commit -m x
deny GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.hooksPath GIT_CONFIG_VALUE_0=/dev/null git commit -m x
deny git -c alias.c='commit --no-verify' c -m x
deny git -c alias.k='!kubectl delete pod x' k
deny SKIP+=lint git commit -m x
deny grep .vault_pass -e ''
deny rg .vault_pass -e ''
deny grep -f .vault_pass ansible.cfg
deny cat .vault_pa*
deny cat ~/.kube/conf*
deny cat ~/.kube/config.bak
deny cp -r ~/.kube /tmp/k
deny kubectl get --raw /api/v1/namespaces/default/secrets/db
deny kubectl get secret db --template={{.data}}
deny kubectl get secrets.v1. db -o yaml
deny kubectl --username get delete pod x
deny kubectl --password p delete pod x
deny bash -o pipefail -c 'kubectl delete pod x'
deny bash -O extglob -c 'kubectl delete pod x'
deny echo 'kubectl delete pod x' | bash
deny bash <<< 'kubectl delete pod x'
deny script -qc 'kubectl delete pod x' /dev/null
deny su -lc 'kubectl delete pod x'
deny /usr/bin/time kubectl delete pod x
deny /usr/bin/time -f %e kubectl delete pod x
deny /usr/bin/nohup kubectl delete pod x
deny setsid -f kubectl delete pod x
deny nohup -- kubectl delete pod x
deny {kubectl,delete,pod,x}
deny git commit {--no-verify,-m,x}
deny /usr/bin/kube?tl delete pod x
deny coproc X { kubectl delete pod y; }
deny kubecolor delete pod x
deny helm3 uninstall rel
deny terragrunt destroy
deny terragrunt run-all destroy
deny parallel kubectl delete pod ::: x
deny ssh host kubectl delete pod x
deny git rebase --exec 'kubectl delete pod x' HEAD~1
deny git rebase -x 'kubectl delete pod x' HEAD~1
deny git bisect run kubectl delete pod x
deny git submodule foreach 'kubectl delete pod x'
ask uvx --from ansible-core ansible-playbook site.yml
ask uv tool run ansible-playbook site.yml
deny EDITOR=cat sops secrets.enc.yaml
deny flux debug hr app --show-values
deny tofu show -json plan.out
deny pre-commit uninstall
deny xargs -a .vault_pass echo
# --- Regressions from the review: read work that was wrongly denied
allow rtk grep vault_pass ansible.cfg
allow git grep vault_pass
allow git grep -n -- --no-verify
allow echo '*.tfstate' >> .gitignore
allow git rm --cached .vault_pass
allow ls -la .vault_pass
allow git config core.hooksPath
allow git config --get core.hooksPath
allow kubectl apply --help
allow cat monkey.pem
allow kubectl create configmap x --from-file=a.txt --dry-run=client -o yaml
allow kubectl create secret generic x --from-literal=a=b --dry-run=client -o yaml
allow ssh -i ~/.ssh/id_ed25519 host uptime
allow grep -A 3 vault_pass ansible.cfg
allow sops --encrypt secrets.yaml
allow sops updatekeys secrets.enc.yaml
allow wc -l *
allow flux debug hr app
# --- Kept on purpose: the admin kubeconfig is not the stage session's
deny export KUBECONFIG=~/.kube/config
deny kubectl --kubeconfig ~/.kube/config get pods
CASES
# Multi-line commands do not survive the line-per-case table above; test them
# directly.
expect_claude deny $'ls\nkubectl apply -f x'
expect_claude deny $'cat <<EOF | sh\nkubectl apply -f x\nEOF'
expect_claude deny $'ls \\\n && kubectl apply -f x'
expect_claude deny $'bash <<EOF\nkubectl delete pod x\nEOF'
expect_claude deny $'kube\\\nctl delete pod x'
# Here-doc bodies are data: commit messages and PR bodies may name commands.
expect_claude allow $'git commit -F- <<\'EOF\'\nkubectl apply is denied by the guard\nEOF'
expect_claude allow $'gh pr create --title t --body "$(cat <<\'EOF\'\nhelm uninstall foo is blocked; don\'t worry\nEOF\n)"'
expect_claude allow $'cat > notes.md <<\'EOF\'\nhelm uninstall foo\nEOF'
expect_claude allow $'cat <<-EOF > x\n\tkubectl delete pod x\n\tEOF\nls'
# ...but the command after the here-doc is still checked.
expect_claude deny $'cat > notes.md <<EOF\nhello\nEOF\nkubectl apply -f x'
echo "== File tools"
file_case() {
local want="$1" script="$2" payload="$3" got
got="$(decision "$script" "$payload")"
if [[ "$got" == "$want" ]]; then pass; else fail "file tool: want $want, got $got: $payload"; fi
}
file_case deny "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/repo/.vault_pass"}}'
file_case deny "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/root/.ssh/id_ed25519"}}'
file_case deny "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/repo/infra/terraform.tfstate"}}'
file_case deny "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/root/.kube/config"}}'
file_case deny "$CLAUDE" '{"tool_name":"Grep","tool_input":{"pattern":".","path":"/repo/.vault_pass"}}'
file_case deny "$CLAUDE" '{"tool_name":"Grep","tool_input":{"pattern":".","path":"/repo","glob":"*.tfstate"}}'
file_case deny "$CLAUDE" '{"tool_name":"Edit","tool_input":{"file_path":"/repo/terraform.tfstate","old_string":"a","new_string":"b"}}'
file_case allow "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/repo/ansible.cfg"}}'
file_case allow "$CLAUDE" '{"tool_name":"Read","tool_input":{"file_path":"/root/.ssh/id_ed25519.pub"}}'
file_case allow "$CLAUDE" '{"tool_name":"Glob","tool_input":{"pattern":"**/*.yml"}}'
file_case allow "$CLAUDE" '{"tool_name":"mcp__gitea__issue_read","tool_input":{"method":"get"}}'
file_case deny "$COPILOT" '{"toolName":"view","toolArgs":"{\"path\":\"/repo/.vault_pass\"}"}'
file_case allow "$COPILOT" '{"toolName":"view","toolArgs":"{\"path\":\"/repo/README.md\"}"}'
file_case deny "$CODEX" '{"tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch\n*** Update File: infra/terraform.tfstate\n*** End Patch"}}'
file_case allow "$CODEX" '{"tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch\n*** Update File: README.md\n*** End Patch"}}'
echo "== Per-runtime output"
runtime_case() {
local label="$1" want="$2" script="$3" payload="$4" got
got="$(decision "$script" "$payload")"
if [[ "$got" == "$want" ]]; then pass; else fail "$label: want $want, got $got"; fi
}
ODD_CLAUDE="$(claude_bash 'ansible-playbook site.yml')"
NEVER_CLAUDE="$(claude_bash 'kubectl apply -f x')"
ODD_COPILOT='{"toolName":"bash","toolArgs":"{\"command\":\"ansible-playbook site.yml\"}"}'
NEVER_COPILOT='{"toolName":"bash","toolArgs":"{\"command\":\"kubectl apply -f x\"}"}'
OK_COPILOT='{"toolName":"bash","toolArgs":"{\"command\":\"kubectl get pods\"}"}'
runtime_case "claude odd job asks" ask "$CLAUDE" "$ODD_CLAUDE"
runtime_case "copilot odd job asks" ask "$COPILOT" "$ODD_COPILOT"
runtime_case "copilot never denies" deny "$COPILOT" "$NEVER_COPILOT"
runtime_case "copilot read allows" allow "$COPILOT" "$OK_COPILOT"
runtime_case "codex odd job denies (no ask)" deny "$CODEX" "$ODD_CLAUDE"
runtime_case "codex never denies" deny "$CODEX" "$NEVER_CLAUDE"
runtime_case "unknown runtime odd job denies" deny "$UNKNOWN" "$ODD_CLAUDE"
runtime_case "camelCase payload outside a deploy path is Copilot" ask "$UNKNOWN" "$ODD_COPILOT"
# Shape checks: Claude needs hookSpecificOutput with hookEventName; Copilot
# needs a reason with every deny; Codex needs exit 2 with the reason on stderr.
out="$(claude_bash 'kubectl apply -f x' | python3 "$CLAUDE")"
if python3 -c '
import json, sys
h = json.loads(sys.argv[1])["hookSpecificOutput"]
assert h["hookEventName"] == "PreToolUse" and h["permissionDecision"] == "deny"
assert "ADR-0032" in h["permissionDecisionReason"]
' "$out"; then pass; else fail "claude deny output shape: $out"; fi
out="$(printf '%s' "$NEVER_COPILOT" | python3 "$COPILOT")"
if python3 -c '
import json, sys
d = json.loads(sys.argv[1])
assert d["permissionDecision"] == "deny" and d["permissionDecisionReason"]
' "$out"; then pass; else fail "copilot deny output shape: $out"; fi
set +e
err="$(claude_bash 'kubectl apply -f x' | python3 "$CODEX" 2>&1 > /dev/null)"
rc=$?
set -e
if [[ $rc -eq 2 && "$err" == *ADR-0032* ]]; then pass; else fail "codex deny: rc=$rc stderr=$err"; fi
echo "== Fail closed"
runtime_case "malformed payload denies on claude" deny "$CLAUDE" '{not json'
runtime_case "malformed payload denies on copilot" deny "$COPILOT" '{not json'
runtime_case "malformed payload denies on codex" deny "$CODEX" '{not json'
echo "== Hook definition"
if python3 - "$HOOKS_JSON" << 'PY'
import json, sys
doc = json.load(open(sys.argv[1]))
groups = doc["hooks"]["PreToolUse"]
assert len(groups) == 1, groups
# No matcher: the script dispatches on tool name itself, because matchers are
# written verbatim to every target and the shell tool is named differently on
# each runtime.
assert "matcher" not in groups[0], groups[0]
(h,) = groups[0]["hooks"]
# The .apm/ path is the one that resolves after install (kyberforge docs/hooks.md).
assert h["command"] == "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/guard.py", h
# Claude Code fails open on a hook error unless told otherwise.
assert h["onFailure"] == "block", h
# Copilot lets a timed-out hook's call through; keep the budget short but sane.
assert 1 <= h["timeout"] <= 30, h
PY
then pass; else fail "hooks.json shape"; fi
if [[ -x "$SRC" ]]; then pass; else fail "guard.py is not executable"; fi
if head -1 "$SRC" | grep -qx '#!/usr/bin/env python3'; then pass; else fail "guard.py shebang"; fi
# Standard library only: a missing dependency would stop every tool call.
if python3 - "$SRC" << 'PY'
import ast, sys
tree = ast.parse(open(sys.argv[1]).read())
mods = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
mods.update(a.name.split(".")[0] for a in node.names)
elif isinstance(node, ast.ImportFrom):
mods.add(node.module.split(".")[0])
extra = mods - {"fnmatch", "json", "os", "re", "sys"}
assert not extra, extra
PY
then pass; else fail "guard.py imports outside the allowed stdlib set"; fi
echo
echo "delivery guard hook: $PASS passed, $FAIL failed"
[[ $FAIL -eq 0 ]]