diff --git a/plugins/guardrails/.claude-plugin/plugin.json b/plugins/guardrails/.claude-plugin/plugin.json index bc3ba8a2597..9dc5f98ca0b 100644 --- a/plugins/guardrails/.claude-plugin/plugin.json +++ b/plugins/guardrails/.claude-plugin/plugin.json @@ -147,5 +147,5 @@ "min": 1 } }, - "version": "0.32.14" + "version": "0.32.16" } diff --git a/plugins/guardrails/CHANGELOG.md b/plugins/guardrails/CHANGELOG.md index d35d73bd746..5f37920b6b7 100644 --- a/plugins/guardrails/CHANGELOG.md +++ b/plugins/guardrails/CHANGELOG.md @@ -3,6 +3,72 @@ All notable changes to the `guardrails` plugin are documented here. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this plugin uses semantic versioning. +## [0.32.16] + +### Fixed + +- **A guard that could not run now says so (#3528).** Every hook in the set + declared `set -uo pipefail` and, with one exception, installed no trap, so a + hook that died between its first line and its own final `exit` (an unbound + variable, a helper that no longer existed, a `source hook-utils.sh` that + failed) ended with whatever status the last command had, usually 1, and + wrote nothing of its own. Claude Code treats any status other than 0 and 2 + as a non-blocking error: the tool call proceeds, and the transcript records + "exit 1, stderr: (none)". For a PreToolUse blocking guard that is + enforcement silently skipped, which is what `claude-ops`' unsurfaced-failure + detector recorded for `block-windows-drive-tmp` and `cli-flag-verify`. + New `hooks/abort-boundary.sh` is the shared boundary the report asked for, + lifted from the handler `block-hook-bypass` already carried (#3130 F5): + `guard::abort_boundary ...` + installs an EXIT trap that passes the chosen statuses through untouched and + turns any other into one stderr line naming the hook and the status plus a + `systemMessage` / `additionalContext` document, then exits with the declared + posture. The handler clears its own trap first, uses builtins only, and + depends on nothing from `hook-utils.sh`, so it still reports the case where + that library failed to load (each hook's `source hook-utils.sh` now exits 70 + on failure instead of falling through into undefined `hook::` calls). + Per-hook postures, each written beside its install line: **fail-open** for + all fourteen registered hooks and the dispatcher. The blocking guards + (`block-convention-violation`, `block-dangerous-git`, + `block-exported-msys-pathconv`, `block-hook-bypass`, `block-no-verify`, + `block-noncanonical-commit`, `block-windows-drive-tmp`, + `hardcoded-path-check`, `secret-pattern-detection`) choose 0 and 2; the + advisory hooks (`cli-flag-verify`, `flag-commit-pr-skill-bypass`, + `skill-reference-verify`, `stale-path-verify`, `workflow-resilience-check`) + choose 0 only. Fail-open is the status quo enforcement on abort for every + one of them, so nothing any guard permits or denies changes; the notice is + the only delta, and flipping a guard to fail-closed is one word on its + install line. `run-guards.sh` installs the same boundary around its own + prologue and merge (an abort there skipped every guard of the event), primes + `.hook_event_name` in its existing jq call so its notice names the event + (looked up by name among the primed filters, never by position, so a filter + added ahead of it cannot move the event), and releases the trap before its + deliberate aggregated exit, so a non-block + status a guard returns still surfaces as before. `block-hook-bypass`'s + bespoke handler is replaced by the shared one; its crash test passes + against it unchanged in expectation. New `hooks/abort-boundary.test.sh` + reads the registered set from `hooks.json`, forces a `set -u` abort in every + registered hook on a copy of the plugin and asserts exit 0 plus a notice + naming the hook, the status, and an event it is registered for; forces the + abort mid-hook through a failing shared helper on one blocking hook (on a + payload the shipped guard still denies) and one advisory hook; checks the + dispatched path keeps a sibling's deny beside an aborting guard and merges + two notices into one document; checks chosen statuses pass through with no + output; checks no registered hook or sourced library installs an EXIT trap + of its own (bash keeps one per shell, so a second would replace the boundary + and restore the silent abort); and checks the handler ends the process once + when its own body + fails. A/B against a pristine `origin/main` export: every guardrails contract + suite produces the same assertion lines on both trees (the injected-crash + fixture aside), and the same 71 payloads through the dispatcher and the + standalone guards agree on exit code, stdout, and stderr. Kernel census + (`strace -f -e trace=clone,clone3,fork,vfork,execve`) of the whole Bash + dispatcher on a benign `git status --short`, three repeats each side: + creations **23 -> 23**, execve **2 -> 2**; the boundary adds no process. + Wall clock on the Linux CI host moved about 2 to 5 ms at p50 (n=20), which + is the eight isolation subshells each opening the boundary file and + returning on its include guard. Not measured on a Windows host. + ## [0.32.14] ### Changed diff --git a/plugins/guardrails/README.md b/plugins/guardrails/README.md index f17b8d37636..d381093bb7a 100644 --- a/plugins/guardrails/README.md +++ b/plugins/guardrails/README.md @@ -172,9 +172,28 @@ out of scope until such a signal exists. repository where guardrails is enabled. Those levers are printed on stderr (Claude Code surfaces an exit-2 stderr reason; `systemMessage` is an exit-0 field and is discarded on a block). -- **`block-hook-bypass` fails open on its own crash.** An internal script error - exits 0 so a defect on this hottest-path hook cannot freeze the session, and - emits a dual-channel "guard did not run" notice so the allow is not silent. +- **Every hook says so when it could not run.** A hook has three outcomes, + not two: allow (exit 0), block (exit 2), and could-not-run. Every registered + hook and the dispatcher install the shared abort boundary + (`hooks/abort-boundary.sh`, #3528) right after their first line. It passes + the statuses the hook chooses through untouched and turns any other exit (an + unbound variable under `set -u`, a helper that stopped existing, a + `hook-utils.sh` that failed to load) into a one-line "guard did not run" + notice naming the hook and the status, on stderr and as a + `systemMessage` / `additionalContext` document, then exits with the posture + the hook declares beside its install. Every hook currently declares + **fail-open**: the tool call proceeds exactly as it did before this boundary + existed, and the notice is the only change. Before it, such an abort exited + with a bare status, usually 1, which Claude Code treats as a non-blocking + error with nothing to show; a blocking guard enforced nothing and nobody was + told. Flipping a hook to fail-closed (deny the call when the guard could not + check it) is the one word `closed` on its install line; the contract test + reads the registered set from `hooks.json`, so a hook added without the + boundary fails it. +- **`block-hook-bypass` fails open on its own crash.** The boundary above is + the generalization of the handler this guard carried first (#3130 F5): an + internal script error exits 0 so a defect on this hottest-path hook cannot + freeze the session, with the dual-channel notice so the allow is not silent. Stdin timeout and a NUL payload still fail closed. The 60s `hooks.json` `timeout` on this handler is a harness-level fail-open the plugin does not override: if the process is killed at that bound, the tool call proceeds. @@ -379,6 +398,20 @@ out of scope until such a signal exists. ### Hook budget accounting +**0.32.16, the abort boundary.** 2026-09-07, Linux CI host. A correctness +change, not a perf one, recorded here because it touches every registered +hook's prologue: each now sources `hooks/abort-boundary.sh` and installs an +EXIT trap (#3528). Kernel census with +`strace -f -e trace=clone,clone3,fork,vfork,execve` of the whole Bash +dispatcher (eight guards) on a benign `git status --short`, three repeats each +side against `origin/main`: creations **23 -> 23**, execve **2 -> 2**. The +boundary adds no process: the trap is a builtin, the handler is builtins only, +and under the dispatcher each isolation subshell inherits the loaded library +and returns on its include guard. Wall clock, p50/p95 of 20 samples after 2 +warmup, interleaved, two rounds: 59.9/65.1 and 61.7/63.3 ms before, +67.0/92.1 and 63.8/68.5 ms after, so about 2 to 5 ms at p50 on this host from +eight extra file opens. Not measured on a Windows host. + **0.32.14, leftover helper-capture forks on verifiers and PreToolUse telemetry.** 2026-09-06, Linux CI host characterised measurable by `spawn_probe`. The 0.32.13 tokenizer table is unchanged: this drop is diff --git a/plugins/guardrails/hooks/abort-boundary.sh b/plugins/guardrails/hooks/abort-boundary.sh new file mode 100644 index 00000000000..17779e9cd55 --- /dev/null +++ b/plugins/guardrails/hooks/abort-boundary.sh @@ -0,0 +1,141 @@ +# shellcheck shell=bash +# Abort boundary for the guardrails hooks (#3528). Sourced by every registered +# hook and by the dispatcher; never executed on its own. +# +# A hook has three outcomes, not two: allow (exit 0), block (exit 2, reason on +# stderr), and could-not-run. Before this file the third had no signal. A hook +# that died between its first line and its own final `exit` (an unbound +# variable under `set -u`, a helper that no longer exists, a `source` that +# failed) ended with whatever status the last command had, usually 1, and wrote +# nothing of its own. Claude Code treats any status other than 0 and 2 as a +# NON-BLOCKING error: the tool call proceeds, bash's one-line error goes to the +# debug log, and the transcript records "exit 1, stderr: (none)". A blocking +# guard enforced nothing and nobody was told. The boundary makes that outcome a +# deliberate one: +# +# source "$_HOOK_SELF/abort-boundary.sh" +# guard::abort_boundary ... +# +# installs an EXIT trap that passes every CHOSEN status through untouched (the +# hook's own `exit 0` / `exit 2`, including the ones the shared helpers make on +# its behalf: hook::check_enabled, hook::require_jq, hook::require_jq_blocking) +# and treats any other status as "the guard did not run". For those it writes +# one line naming the hook and the status to stderr, and then applies the +# hook's declared posture: +# +# open exit 0, after emitting the same text as a hook JSON document on +# stdout: `systemMessage` for the operator and `additionalContext` +# for the agent, the two channels Claude Code reads when a hook exits +# 0 (stderr on exit 0 reaches only the debug log, see +# docs/conventions/hook-observability/). The tool call proceeds, as +# it did before, and the notice says it was not checked. +# closed exit 2 with the notice on stderr, the channel a blocking exit feeds +# back to the agent. The tool call is denied. +# +# is the event the hook is registered for (PreToolUse, +# PostToolUse); it names the `hookSpecificOutput` block. Pass an empty string +# when the event is not known at install time (the dispatcher serves both), and +# the notice carries `systemMessage` only. +# +# Why a trap and not `set -e`: errexit across the hook set would change +# behavior on every non-zero status a guard tests on purpose. The trap sees +# only the status the process actually terminates with. +# +# Handler discipline. `trap - EXIT` is the handler's first action so nothing it +# does can re-enter it. It uses builtins only, every variable it reads is set +# at install time, and it calls nothing from hook-utils.sh, because a failed +# `source hook-utils.sh` is one of the aborts it exists to report. A failure +# inside the handler ends the process once, with that failure's status, after +# the stderr line is already written. +# +# One EXIT trap per shell. Bash holds a single EXIT trap, so a hook that runs +# its own `trap ... EXIT` (or `trap - EXIT`) after the install line REPLACES +# this boundary and is back to the silent abort it exists to remove, with +# nothing at run time to say so. abort-boundary.test.sh fails on any `trap` +# naming EXIT in a registered hook or in a library it sources; this file is the +# only one allowed to touch it. No hook needs exit-time work today (each is +# builtins plus one jq read, nothing to clean up). The supported way for one +# that does is to chain through this library, not around it: add a chain slot +# here that guard::_abort_on_exit calls before it decides (the chained +# function under the same handler discipline: builtins only, never exits, +# never touches the trap), with a suite case beside the others, in the same +# change. A release on purpose goes through guard::abort_boundary_release. +# +# Under run-guards.sh each guard is sourced inside its own command-substitution +# subshell. The trap a guard installs there runs at that subshell's exit; its +# stderr passes straight through and its stdout document is merged with the +# other guards' output like any notice. A subshell does not inherit the +# dispatcher's own EXIT trap (Bash Reference Manual, Command Execution +# Environment), so the two boundaries never fire for the same exit. + +[[ -n "${_GUARDRAILS_ABORT_BOUNDARY_LOADED:-}" ]] && return 0 +readonly _GUARDRAILS_ABORT_BOUNDARY_LOADED=1 + +_GAB_NAME="" +_GAB_EVENT="" +_GAB_POSTURE="open" +_GAB_CHOSEN=" " + +# guard::abort_boundary ... +guard::abort_boundary() { + _GAB_NAME="$1" + _GAB_EVENT="$2" + case "$3" in + open | closed) _GAB_POSTURE="$3" ;; + *) + # A posture that is neither word is a defect in the hook's own prologue. + # Say so and keep the status quo enforcement (fail-open) rather than + # inventing a block the hook never declared. + printf 'guardrails %s: abort boundary posture %q is not open or closed; using open\n' "$1" "$3" >&2 + _GAB_POSTURE="open" + ;; + esac + shift 3 + _GAB_CHOSEN=" $* " + trap guard::_abort_on_exit EXIT +} + +# guard::abort_boundary_release: uninstall the trap. For a process whose final +# status is computed rather than written as a literal (the dispatcher's +# aggregated exit): release right before that deliberate `exit`, so a status +# reached on purpose is never reported as an abort. +guard::abort_boundary_release() { + trap - EXIT +} + +# JSON-escape $2 into the variable named by $1: backslash, double quote, and the +# three line-structure control bytes. The notice text is built from install-time +# literals and a status number, so nothing else can occur in it; the escape is +# here so a hook name or event containing a quote cannot break the document. +guard::_abort_json_escape_to() { + local __gab_s="$2" + __gab_s="${__gab_s//\\/\\\\}" + __gab_s="${__gab_s//\"/\\\"}" + __gab_s="${__gab_s//$'\n'/\\n}" + __gab_s="${__gab_s//$'\r'/\\r}" + __gab_s="${__gab_s//$'\t'/\\t}" + printf -v "$1" '%s' "$__gab_s" +} + +guard::_abort_on_exit() { + local rc=$? + trap - EXIT + [[ "$_GAB_CHOSEN" == *" $rc "* ]] && return 0 + local msg + if [[ "$_GAB_POSTURE" == closed ]]; then + msg="guardrails ${_GAB_NAME}: guard did not run (internal error, rc=${rc}); fail-closed: this tool call is denied because the guard could not check it. The failing line is on the hook's stderr." + printf '%s\n' "$msg" >&2 + exit 2 + fi + msg="guardrails ${_GAB_NAME}: guard did not run (internal error, rc=${rc}); fail-open: this tool call was not checked by this guard. The failing line is on the hook's stderr (claude --debug)." + printf '%s\n' "$msg" >&2 + local esc ev + guard::_abort_json_escape_to esc "$msg" + if [[ -n "$_GAB_EVENT" ]]; then + guard::_abort_json_escape_to ev "$_GAB_EVENT" + printf '{"hookSpecificOutput":{"hookEventName":"%s","additionalContext":"%s"},"systemMessage":"%s"}\n' "$ev" "$esc" "$esc" + else + printf '{"systemMessage":"%s"}\n' "$esc" + fi + exit 0 +} diff --git a/plugins/guardrails/hooks/abort-boundary.test.sh b/plugins/guardrails/hooks/abort-boundary.test.sh new file mode 100755 index 00000000000..b85ae160d11 --- /dev/null +++ b/plugins/guardrails/hooks/abort-boundary.test.sh @@ -0,0 +1,481 @@ +#!/usr/bin/env bash +# Contract test for hooks/abort-boundary.sh (guardrails plugin, #3528). +# +# Black-box where it matters: every registered hook is run as a subprocess on +# a COPY of the plugin with an abort injected, and the assertions are on exit +# code, stderr, and the stdout document. The registered set is read from +# hooks.json, never enumerated here, so a hook added without the boundary +# fails this suite. Self-contained; no host-repo assertion library. + +set -uo pipefail + +HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PLUGIN_DIR="$(cd "$HOOK_DIR/.." && pwd)" +TEST_TMPDIR="$(mktemp -d)" +trap 'rm -rf "$TEST_TMPDIR"' EXIT + +# shellcheck source=guardrails-test-helpers.sh +source "$HOOK_DIR/guardrails-test-helpers.sh" + +if ! command -v jq >/dev/null 2>&1; then + echo "FAIL: jq is required for these tests" >&2 + exit 1 +fi + +MARKER='GUARDRAILS_TEST_FORCED_ABORT' +NOTICE='guard did not run (internal error, rc=' +# run_hook assigns these through printf -v; declared so ShellCheck sees them. +OUT="" +ERR="" +RC=0 + +# Insert after the first line of matching . awk plus a +# rename rather than `sed -i`, whose in-place flag differs between GNU and BSD. +# Fails the suite when the anchor is absent: an injection that silently did +# nothing would make every assertion below vacuous. +inject_after() { + local file="$1" regex="$2" line="$3" hits + hits=$(awk -v re="$regex" '$0 ~ re { n++ } END { print n + 0 }' "$file") + if [[ "$hits" != "1" ]]; then + bad "inject_after: expected exactly one anchor /$regex/ in ${file##*/}, found $hits" + return 1 + fi + awk -v re="$regex" -v ins="$line" '{ print } $0 ~ re && !done { print ins; done = 1 }' \ + "$file" >"$file.injected" && mv "$file.injected" "$file" +} + +# pipe_run : the payload on the command's stdin through a +# pipe (never a here-string; see lib/hook-utils.sh on the 64 KiB deadlock). +pipe_run() { + local payload="$1" + shift + printf '%s' "$payload" | "$@" +} + +# run_hook -- : fills OUT, ERR, RC. A fixed benign +# environment: no project dir, telemetry sink unset, both opt-in advisory +# hooks switched on (each exits 0 at its own top line otherwise, before the +# boundary is installed, which is a chosen status and not what this tests). +run_hook() { + local -a envs=() + while (($#)) && [[ "$1" != "--" ]]; do + envs+=("$1") + shift + done + shift + local rc=0 + # A subshell with exports rather than `env`, which execs a program and so + # cannot run the pipe_run function. + ( + unset HOOK_TELEMETRY_SINK + export CLAUDE_PROJECT_DIR='' \ + CLAUDE_PLUGIN_OPTION_FLAG_COMMIT_PR_SKILL_BYPASS_ENABLED=true \ + CLAUDE_PLUGIN_OPTION_WORKFLOW_RESILIENCE_CHECK_ENABLED=true + ((${#envs[@]})) && export "${envs[@]}" + "$@" + ) >"$TEST_TMPDIR/out" 2>"$TEST_TMPDIR/err" || rc=$? + OUT=$(cat "$TEST_TMPDIR/out") + ERR=$(cat "$TEST_TMPDIR/err") + RC=$rc +} + +count_notices() { # -> number of lines carrying the notice + local n=0 line + while IFS= read -r line; do + [[ "$line" == *"$NOTICE"* ]] && n=$((n + 1)) + done < <(printf '%s\n' "$1") + echo "$n" +} + +json_field() { # + printf '%s' "$1" | jq -r "$2 // empty" 2>/dev/null +} + +BASH_BENIGN=$(jq -nc '{hook_event_name:"PreToolUse",tool_name:"Bash",cwd:"/x",tool_input:{command:"git status --short"}}') +BASH_NO_VERIFY=$(jq -nc '{hook_event_name:"PreToolUse",tool_name:"Bash",cwd:"/x",tool_input:{command:"git commit --no-verify -m x"}}') +BASH_FORCE_PUSH=$(jq -nc '{hook_event_name:"PreToolUse",tool_name:"Bash",cwd:"/x",tool_input:{command:"git push --force origin main"}}') + +# --- The registered hook set, read from hooks.json -------------------------- +# Every command is tokenised; `--lib ` pairs are dropped (a library, not +# a hook); every remaining *.sh token is a registered script, the dispatcher +# included. EVENTS records the event(s) each script is registered under, which +# the forced-abort assertions below compare against the notice's hookEventName. +declare -A EVENTS=() +REGISTERED=() +# Libraries a registered hook sources at run time, plugin-relative: +# hook-utils.sh in every hook, the `--lib` paths in the dispatcher. A trap in +# one of these replaces the boundary as surely as one in the hook itself. +SOURCED_LIBS=("hooks/hook-utils.sh") +set -f +while IFS=$'\t' read -r ev cmd; do + # shellcheck disable=SC2206 # the split IS the point; globbing is off + toks=($cmd) + skip=0 + for tok in "${toks[@]}"; do + if ((skip)); then + skip=0 + [[ " ${SOURCED_LIBS[*]} " == *" $tok "* ]] || SOURCED_LIBS+=("$tok") + continue + fi + if [[ "$tok" == "--lib" ]]; then + skip=1 + continue + fi + [[ "$tok" == *.sh ]] || continue + name="${tok##*/}" + if [[ -z "${EVENTS[$name]:-}" ]]; then + REGISTERED+=("$name") + EVENTS[$name]=" $ev " + elif [[ "${EVENTS[$name]}" != *" $ev "* ]]; then + EVENTS[$name]+="$ev " + fi + done +done < <(jq -r '.hooks | to_entries[] | .key as $ev | .value[] | .hooks[] | "\($ev)\t\(.command)"' "$HOOK_DIR/hooks.json") +set +f + +# A parse that quietly found nothing would make the whole suite pass on an +# empty loop. The set is fourteen guards plus the dispatcher today; the floor +# is loose on purpose so removing a guard is not a failure here. +if ((${#REGISTERED[@]} >= 10)); then + ok "hooks.json yields a registered set of ${#REGISTERED[@]} scripts" +else + bad "hooks.json yielded only ${#REGISTERED[@]} scripts: ${REGISTERED[*]}" +fi +for name in "${REGISTERED[@]}"; do + [[ -f "$HOOK_DIR/$name" ]] || bad "registered script missing from hooks/: $name" +done + +# exit_trap_hits : lines that install an EXIT trap (or signal 0). First +# stage finds a `trap` statement; second stage requires the EXIT/0 token to be +# bounded on the right by whitespace, end-of-line, or a statement terminator +# (`;`, `&`, `|`, `)`). The terminator class is required: a one-liner such as +# `if cond; then trap cleanup EXIT; fi` has EXIT immediately followed by `;`, +# and a trailing-space-or-EOL-only boundary would drop that line from hits. +# Comment lines are skipped; a `trap` naming only other signals is not a hit. +exit_trap_hits() { + grep -nE '^[^#]*(^|[;&|{(]|then|do|else)[[:space:]]*trap[[:space:]]' "$1" | + grep -E '(^|[[:space:]])(EXIT|0)([[:space:];&|)]|$)' || true +} + +# assert_no_exit_trap