From 99caae76158cf55f972b4af235201705fc11dcfd Mon Sep 17 00:00:00 2001 From: Timothy Date: Wed, 26 Aug 2026 20:37:38 +0200 Subject: [PATCH] fix(788): gate the vocabulary on a sentinel, not on a skippable `if` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cold adversarial review found a fail-open in the first commit, reproduced here before fixing: with `.*` in the positive list and the negative list written as a scalar, `check-review-verdict.sh` classified an explicit `BLOCKED @ ` as `positive`, exit 0. The merge-consent hook auto-grants on exactly that, and it discards the classifier's stderr, so the only signal was invisible. Root cause, measured rather than reasoned: * `${#arr[@]}` is nounset-safe only for a DECLARED-EMPTY array. On an unset name or a scalar it is a fatal unbound-variable error. * Under `set -u` that error inside a FUNCTION aborts the function, not the script — and in the `if ! validate; then exit 2; fi` form NEITHER branch is then taken, so the gate is skipped and execution continues. * `check-review-verdict.sh` deliberately runs without `set -e`, so the words reached the regex unvalidated. The write side has `set -e` and did die, so the asymmetry left the hole on precisely the side that authorizes merges. The single-fault case needed no metacharacter and is the realistic wrong edit: writing the list as a string degraded every negative verdict from `negative` to `unknown` — DENY silently downgraded to ASK — with no non-zero exit anywhere. A control-flow gate can be skipped by an abort; a value that was never assigned cannot be read. So enforcement is now a DATA dependency: validation sets `ETV_VERDICT_VOCABULARY_OK=1` as the last statement of its successful path, and `etv_verdict_class`/`etv_verdict_alternation`/`etv_verdict_words_display` refuse without it. The sentinel is reset to 0 at load time, so an inherited environment variable cannot forge it. Array-ness is asserted with `declare -p` BEFORE any `${#arr[@]}`, so the abort cannot occur in the first place — kept alongside the sentinel for the accurate message, not as a second gate. Separately, a top-level `exit` in a sourced library terminates the sourcing script at the `source` line, so no check written after it can run: the reader returned exit 0 with EMPTY stdout, breaking its "exactly one classification word" contract. Both consumers now probe-source the library in a subshell and require an end-of-file marker before sourcing it for real; that also catches a syntax error and a truncated file. All six failure modes now fail closed (reader exit 2, writer exit 1 having posted nothing), and the shipped words classify exactly as before. Four of the six new tests were witnessed RED against the unfixed predecessor 2d389a5bf; the other two (unset array, truncated library) pin behaviour that already held and are labelled as such rather than presented as fixes. Also from the review: prose in the decision record, `docs/ci-cd.md` and two in-script comments claimed validation was "run above, fatal" — the false premise that shipped the hole. Corrected to name the sentinel as what enforces it. The unresolved-symlink location dependency is recorded as a known limitation (fail-closed today). De-flaked the unreadable-file test for a root runner, and fixed a stale `check-review-verdict.sh:212` line reference plus a comment still describing #788 as future work. Not done, deliberately: no third guard on the both-patterns-match case. The validator rejects a word in both lists, and test_check_review_verdict.py already pins the dangerous direction; a third overlapping guard is the shape where deleting any one leaves the suite green. Verification: 987 passed / 2 skipped, ruff clean, shellcheck clean, catalog regenerated, decisions-validate OK. Refs: #788 Decisions-Edit: yes Co-authored-by: Timothy --- docs/ci-cd.md | 19 ++- docs/decisions/README.md | 2 +- .../release/verdict-vocabulary-shared.md | 42 +++++- scripts/check-review-verdict.sh | 34 ++++- scripts/lib/review-verdict-vocabulary.sh | 73 +++++++++- scripts/post-review-verdict.sh | 9 ++ scripts/tests/test_check_review_verdict.py | 6 +- .../tests/test_review_verdict_vocabulary.py | 126 ++++++++++++++++++ 8 files changed, 288 insertions(+), 23 deletions(-) diff --git a/docs/ci-cd.md b/docs/ci-cd.md index a805f611b..66155d615 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -1249,11 +1249,20 @@ in `check-review-verdict.sh`, where every #629 false-open actually lived. Run Two things follow that are easy to get wrong. **Do not reintroduce a parity test** that compares the two scripts' sources: #774 shipped one and withdrew it after six review rounds, each finding another shell construction that escaped the extractor or reddened it on a correct tree. And a vocabulary -that is missing, unreadable or invalid is **fatal on both sides** — the reader exits 2 (which -callers treat as an unreadable input and fail closed on), the writer exits 1 having posted nothing. -That is deliberate: words are interpolated into a regex, so a `.*` slipping into the positive list -would classify an explicit `BLOCKED` as `positive`. Validation restricts every word to -`[a-z][a-z-]*`, which is why it is a hard exit rather than a warning. +that cannot be loaded or does not validate yields **no words on either side** — the reader exits 2 +(which callers treat as an unreadable input and fail closed on), the writer exits 1 having posted +nothing. Words are interpolated into a regex, so a `.*` in the positive list would classify an +explicit `BLOCKED` as `positive`; validation restricts every word to `[a-z][a-z-]*`. + +**What enforces that is a data dependency, not the `if` around the validator** — worth knowing +before editing either script, because the obvious reading is wrong and the first version of #788 +shipped the hole. Under `set -u`, an unbound-variable error inside a function aborts the function +but not the script, and in an `if ! validate` form neither branch runs, so the `exit 2` is skipped. +The reader has no `set -e`, so unvalidated words reached the regex and an explicit `BLOCKED @ head` +classified `positive`, exit 0. Validation now sets a sentinel on its last line and the derived views +refuse without it. Likewise a top-level `exit` in a sourced library terminates the sourcing script +where it stands, so both consumers probe-source the library in a subshell and require an +end-of-file marker before trusting it. The status description also records the base branch — `Review-verdict: MERGEABLE @ abc1234 (base: main)` — and the merge-consent hook denies when that no longer matches the PR's live `base.ref` diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 2021f3851..51ae1a9ed 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -141,7 +141,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera | `release.promotion-floating-prod` | Prod tracks the floating `:prod` image reference; a tag build's immutable `:` image is scanned first, then promotion happens via a separate manual `DeployStack`, with daily auto-update only as a fallback — tag with enough runway before 03:00 to avoid an unscanned promotion. | 2026-07-13 | [link](records/release/promotion-floating-prod.md) | | `release.review-verdict-gate` | A PR may not merge until a `Review-verdict: @ ` comment references the PR's current head sha (short-sha prefix match against the verdict's OWN `@ ` field, marker at COLUMN 0 (no indent, so indented code blocks cannot self-approve), whole-word verdict token, fenced code blocks stripped with markdown fence-length semantics, negative wins over positive on the same head); folds into the H6 merge-consent hook as condition (c). The grammar lives in ONE tested place, `scripts/check-review-verdict.sh` — #629 found three false-opens that survived because it was implemented inline and untested while this record described stricter behaviour than the code had. | 2026-07-12 | [link](records/release/review-verdict-gate.md) | | `release.verdict-status-check` | The H10 review verdict is written as a `review-verdict/h10` Gitea **commit status** on the exact reviewed sha by `scripts/post-review-verdict.sh`, and that context is a REQUIRED status check on `main`. Because a status belongs to one sha, a later commit cannot inherit it, so Gitea's own `merge_when_checks_succeed` refuses to merge a head no one reviewed. The PreToolUse hook additionally refuses to SCHEDULE an auto-merge unless that status is already green on head. A `pull_request_target` workflow auto-passes the two exempt classes (Renovate-authored, docs-only) unless the PR touches a protected path (`.claude/`, `.codex/`, `.gitea/`, `.husky/`, `scripts/`, `docker/ci/`). This extends — does not supersede — `release.review-verdict-gate` (#303 H10), whose comment convention remains the human-readable artifact and the hook's condition (c). | 2026-07-25 | [link](records/release/verdict-status-check.md) | -| `release.verdict-vocabulary-shared` | The H10 verdict words live in exactly one place, `scripts/lib/review-verdict-vocabulary.sh`, as two arrays. `scripts/post-review-verdict.sh` (write: word to commit-status state) classifies through `etv_verdict_class`; `scripts/check-review-verdict.sh` (read: comment to classification) builds `POS_RE`/`NEG_RE` from `etv_verdict_alternation`. Neither script may restate a word, and neither may enumerate the vocabulary in a usage banner or an error string. Every word is validated to `[a-z][a-z-]*` before it reaches a regex, and a vocabulary that is missing, unreadable or invalid is FATAL on both sides — exit 1 for the writer, exit 2 for the reader. Do NOT reintroduce a text-comparison parity test alongside this. | 2026-08-26 | [link](records/release/verdict-vocabulary-shared.md) | +| `release.verdict-vocabulary-shared` | The H10 verdict words live in exactly one place, `scripts/lib/review-verdict-vocabulary.sh`, as two arrays. `scripts/post-review-verdict.sh` (write: word to commit-status state) classifies through `etv_verdict_class`; `scripts/check-review-verdict.sh` (read: comment to classification) builds `POS_RE`/`NEG_RE` from `etv_verdict_alternation`. Neither script may restate a word, and neither may enumerate the vocabulary in a usage banner or an error string. Every word is validated to `[a-z][a-z-]*` before it reaches a regex. Validation is enforced by a DATA dependency, not a control-flow check: `etv_verdict_vocabulary_validate` sets `ETV_VERDICT_VOCABULARY_OK=1` on its final line, and the derived views refuse to hand out words without it. A vocabulary that is missing, unreadable, truncated, exits at top level, is declared as a scalar, or fails validation yields NO words on either side — exit 1 for the writer (nothing posted), exit 2 for the reader (callers fail closed). Do NOT reintroduce a text-comparison parity test alongside this. | 2026-08-26 | [link](records/release/verdict-vocabulary-shared.md) | | `release.verdict-writes-status-before-comment` | `scripts/post-review-verdict.sh` writes the sha-bound `review-verdict/h10` commit status FIRST and the human-readable `Review-verdict:` comment SECOND. Every refusal path still refuses (fail-closed, unchanged) and exits non-zero, and none of them may leave a verdict comment behind. An orphaned comment is therefore PREVENTED rather than tolerated. If the comment write fails after the status was written, that is an error too, but it degrades to an `ask` at the merge gate rather than to an apparent grant. | 2026-08-22 | [link](records/release/verdict-writes-status-before-comment.md) | | `rulebuilder.relative-date-macros` | The visual rule builder's `inLast`/`notInLast` date operators compile to/parse from the pre-existing `CustomMultiFieldQueryParser` macros `released_inthelast`/`released_notinthelast` and `added_inthelast`/`added_notinthelast`, value form `" day\|week\|month\|year"`; there is no backend change. | 2026-07-23 | [link](records/rulebuilder/relative-date-macros.md) | | `scan.collections-scan-status` | `GET /api/v1/media-sources/collections-scan-status` reports a family-global (not per-source), boolean-only active-scan set read from `IEntityLocker`; the SPA reconciles authoritatively against it (with a grace-tick helper) instead of a fixed client-side timeout. | 2026-07-12 | [link](records/scan/collections-scan-status.md) | diff --git a/docs/decisions/records/release/verdict-vocabulary-shared.md b/docs/decisions/records/release/verdict-vocabulary-shared.md index e13e50836..3d56f3474 100644 --- a/docs/decisions/records/release/verdict-vocabulary-shared.md +++ b/docs/decisions/records/release/verdict-vocabulary-shared.md @@ -5,7 +5,7 @@ status: active since: '2026-08-26' supersedes: none superseded-by: none -rule: 'The H10 verdict words live in exactly one place, `scripts/lib/review-verdict-vocabulary.sh`, as two arrays. `scripts/post-review-verdict.sh` (write: word to commit-status state) classifies through `etv_verdict_class`; `scripts/check-review-verdict.sh` (read: comment to classification) builds `POS_RE`/`NEG_RE` from `etv_verdict_alternation`. Neither script may restate a word, and neither may enumerate the vocabulary in a usage banner or an error string. Every word is validated to `[a-z][a-z-]*` before it reaches a regex, and a vocabulary that is missing, unreadable or invalid is FATAL on both sides — exit 1 for the writer, exit 2 for the reader. Do NOT reintroduce a text-comparison parity test alongside this.' +rule: 'The H10 verdict words live in exactly one place, `scripts/lib/review-verdict-vocabulary.sh`, as two arrays. `scripts/post-review-verdict.sh` (write: word to commit-status state) classifies through `etv_verdict_class`; `scripts/check-review-verdict.sh` (read: comment to classification) builds `POS_RE`/`NEG_RE` from `etv_verdict_alternation`. Neither script may restate a word, and neither may enumerate the vocabulary in a usage banner or an error string. Every word is validated to `[a-z][a-z-]*` before it reaches a regex. Validation is enforced by a DATA dependency, not a control-flow check: `etv_verdict_vocabulary_validate` sets `ETV_VERDICT_VOCABULARY_OK=1` on its final line, and the derived views refuse to hand out words without it. A vocabulary that is missing, unreadable, truncated, exits at top level, is declared as a scalar, or fails validation yields NO words on either side — exit 1 for the writer (nothing posted), exit 2 for the reader (callers fail closed). Do NOT reintroduce a text-comparison parity test alongside this.' signals: 'verdict vocabulary drift, POS_RE NEG_RE, two shell copies, parity test withdrawn, add a verdict word, shared vocabulary, MERGEABLE not recognised, unexplained merge-gate deny · paths: `scripts/lib/review-verdict-vocabulary.sh`, `scripts/post-review-verdict.sh`, `scripts/check-review-verdict.sh`, `scripts/tests/test_review_verdict_vocabulary.py` · issues: #788, #774, #629, #622' mechanics: '`scripts/tests/test_review_verdict_vocabulary.py::test_a_word_added_to_the_shared_source_reaches_BOTH_sides` (and the NEGATIVE-list twin), graded MUTATION in `docs/guard-inventory.md` with its clause declared in `scripts/tests/mutation_manifest.py` — the harness restores the pre-#788 hardcoded `POS_RE` on every run and requires that proof to go red' --- @@ -37,12 +37,34 @@ whole-word boundary, the anchored `@ ` field (#629) — and none of that be **Validation is not hygiene, it is the security property.** The list is interpolated into an extended regular expression, so it is an injection surface, and the failure direction is the -dangerous one: a `.*` in the positive list would make `POS_RE` match every verdict-shaped line, so -an explicit `BLOCKED` would classify `positive` and the gate would grant consent nobody gave. -Restricting words to `[a-z][a-z-]*` makes that unreachable as a property of the character class -rather than of anyone remembering to escape. A word appearing in both lists, an empty list and an -empty word are refused for the same reason: each would make the classification of some real verdict -depend on which arm ran first. +dangerous one: a `.*` in the positive list makes `POS_RE` match every verdict-shaped line, so an +explicit `BLOCKED` classifies `positive` and the gate grants consent nobody gave. A word appearing +in both lists, an empty list and an empty word are refused for the same reason: each would make the +classification of some real verdict depend on which arm ran first. + +**A control-flow gate was not enough, and the first version of this change shipped the hole.** The +validator was called as `if ! etv_verdict_vocabulary_validate; then exit 2; fi`. Under `set -u` an +unbound-variable error inside a FUNCTION aborts the function but not the script, and in that form +NEITHER branch is then taken — execution continues straight past the gate. `${#arr[@]}` triggers +exactly that abort: it is nounset-safe only on a *declared-empty* array, and fatal on an unset name +or a scalar. Since the reader deliberately runs without `set -e`, the words reached the regex +unvalidated. Measured, with `.*` in the positive list and the negative list written as a scalar: an +explicit `BLOCKED @ ` classified **`positive`, exit 0**, with the only signal on a stderr the +calling hook discards. Cold review found it; it was not caught by the suite. + +So enforcement is now a DATA dependency. Validation sets `ETV_VERDICT_VOCABULARY_OK=1` as the last +statement of its successful path, and `etv_verdict_class` / `etv_verdict_alternation` refuse without +it. A control-flow gate can be skipped by an abort; a value that was never assigned cannot be read. +The sentinel is reset to 0 at load time so an inherited environment variable cannot forge it, and +array-ness is asserted with `declare -p` *before* any `${#arr[@]}` so the abort cannot happen in the +first place. Both are kept deliberately — the second gives an accurate message, the first is what +holds. + +**A sourced library that `exit`s cannot be caught after the fact**, because the `exit` terminates +the sourcing script at the `source` line — the reader returned exit 0 with empty stdout, breaking +its "exactly one classification word" contract. Both consumers therefore probe-source the library in +a SUBSHELL and require an end-of-file marker on stdout before sourcing it for real. That also covers +a syntax error and a truncated file, neither of which reaches the marker. **The arrays are arrays, not whitespace-separated strings.** A string list has to be split by an UNQUOTED expansion, and an unquoted expansion also performs PATHNAME EXPANSION. That is not @@ -51,6 +73,12 @@ repo root. It makes validation depend on the working directory, and it fails OPE matters, since a `*` entry expands to the filenames beside it and any matching `[a-z][a-z-]*` (`scripts`, `docs`) would validate cleanly and enter the vocabulary as a real verdict word. +**Known limitation, stated rather than implied.** The library is located relative to +`${BASH_SOURCE[0]}` without resolving symlinks, so a script reached through a symlink looks for its +vocabulary beside the *link*. Every normal invocation is unaffected (absolute path, relative, via +`PATH`, a path containing spaces — all measured), and the case fails CLOSED when no library sits +there. It is recorded because this repo does symlink files across repositories. + **What is deliberately NOT shared.** `.claude/hooks/pretooluse-merge-consent.sh` names the words in one operator-facing message string. It performs no classification of its own — it delegates to `check-review-verdict.sh` — so it is a prose copy, not a second implementation, and sourcing a shell diff --git a/scripts/check-review-verdict.sh b/scripts/check-review-verdict.sh index bc062fad3..459994ebd 100755 --- a/scripts/check-review-verdict.sh +++ b/scripts/check-review-verdict.sh @@ -83,16 +83,37 @@ esac # closed on it (see the header). A classifier that cannot load its vocabulary does not know what a # verdict word is; the one thing it must never do is fall through to `absent`, which the hook reads # as "convention not adopted" and downgrades into an `ask`. +# +# THE GATE IS THE SENTINEL, NOT THIS `if`. Stated because the obvious reading is wrong: under +# `set -u` an unbound-variable error inside a function aborts the function and NOT the script, and +# in an `if ! validate` form neither branch is then taken, so the `exit 2` is skipped and execution +# continues. That is a measured fail-open, not a hypothetical — see the sentinel comment in the +# library. `etv_verdict_alternation` refusing without the sentinel is what actually holds. _here=$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) || { printf 'check-review-verdict: could not resolve this script own directory to locate the shared verdict vocabulary\n' >&2; exit 2; } VOCABULARY_LIB="$_here/lib/review-verdict-vocabulary.sh" if [ ! -r "$VOCABULARY_LIB" ]; then printf 'check-review-verdict: the shared verdict vocabulary is missing or unreadable at %s\n' "$VOCABULARY_LIB" >&2; exit 2 fi +# PROBE-SOURCE IN A SUBSHELL FIRST, and require the library's end-of-file marker on stdout. A +# top-level `exit` in a sourced file terminates THIS script where the `source` stands, so no check +# written after it can run: the reader returned exit 0 with empty stdout, which violates its +# "exactly one classification word" contract and would read as success to any caller that checks +# only the exit code. The probe moves that failure into a subshell, where it is observable. It also +# covers a syntax error and a truncated file, since neither reaches the marker. +# shellcheck source=lib/review-verdict-vocabulary.sh +vocabulary_probe=$( . "$VOCABULARY_LIB" >/dev/null 2>&1 && etv_verdict_vocabulary_loaded 2>/dev/null ) || vocabulary_probe='' +if [ "$vocabulary_probe" != 'etv-verdict-vocabulary-loaded' ]; then + printf 'check-review-verdict: the shared verdict vocabulary at %s did not load to completion (syntax error, truncated, or it exits at top level)\n' "$VOCABULARY_LIB" >&2; exit 2 +fi # shellcheck source=lib/review-verdict-vocabulary.sh if ! . "$VOCABULARY_LIB"; then printf 'check-review-verdict: the shared verdict vocabulary at %s could not be sourced\n' "$VOCABULARY_LIB" >&2; exit 2 fi +# The return code is checked, but it is NOT what makes this safe — a `set -u` abort inside the +# function would skip both branches of this `if` and carry straight on. What makes it safe is that +# validation sets a sentinel on its last line and `etv_verdict_alternation` refuses without it, so a +# skipped validation cannot yield a pattern. Both are kept: this gives the accurate diagnostic. if ! etv_verdict_vocabulary_validate; then printf 'check-review-verdict: the shared verdict vocabulary at %s did not validate (see above)\n' "$VOCABULARY_LIB" >&2; exit 2 fi @@ -219,10 +240,15 @@ FIELD_RE='^review-verdict:[[:space:]]*[A-Za-z][A-Za-z-]*[[:space:]]*@[[:space:]] # list. `etv_verdict_alternation` emits only the alternation BODY (`word|word|word`), and the # `([[:space:]@]|$)` boundary below are unchanged. # -# Interpolating into an ERE is safe because `etv_verdict_vocabulary_validate` (run above, fatal) -# restricts every word to `[a-z][a-z-]*`, so no character reaching this regex can be a metacharacter. -# Without that check a `.*` in the positive list would make every verdict-shaped line classify -# `positive`, including an explicit BLOCKED — which is why the validation is a hard exit, not a warn. +# Interpolating into an ERE is safe because every word is restricted to `[a-z][a-z-]*`, so no +# character reaching this regex can be a metacharacter. Without that a `.*` in the positive list +# would make every verdict-shaped line classify `positive`, including an explicit BLOCKED. +# +# WHAT ENFORCES IT is `etv_verdict_alternation` refusing unless validation set its sentinel — NOT +# the `if ! etv_verdict_vocabulary_validate` above. Saying "validated above, therefore safe" was the +# false premise that shipped the hole: a `set -u` abort inside that function skips both branches of +# the `if`, and the words then reached this line unvalidated. The call above is kept for its +# diagnostic; the refusal below is the gate. POS_ALTERNATION=$(etv_verdict_alternation positive) || { printf 'check-review-verdict: could not build the positive verdict pattern from %s\n' "$VOCABULARY_LIB" >&2; exit 2; } NEG_ALTERNATION=$(etv_verdict_alternation negative) || { diff --git a/scripts/lib/review-verdict-vocabulary.sh b/scripts/lib/review-verdict-vocabulary.sh index 4cf879d1c..dc12aa2d0 100644 --- a/scripts/lib/review-verdict-vocabulary.sh +++ b/scripts/lib/review-verdict-vocabulary.sh @@ -46,6 +46,24 @@ ETV_VERDICT_POSITIVE_WORDS=(mergeable approved lgtm) ETV_VERDICT_NEGATIVE_WORDS=(blocked not-mergeable) +# --- The validation sentinel. ------------------------------------------------------------------- +# Reset to 0 HERE, at load time, for two reasons. It defeats an inherited `ETV_VERDICT_VOCABULARY_OK=1` +# from the environment, and — the reason it exists — it makes "validated" a fact the DERIVED VIEWS +# can require, rather than something a caller is trusted to have checked. +# +# WHY A SENTINEL AND NOT A RETURN CODE. `etv_verdict_vocabulary_validate` used to be gated as +# `if ! etv_verdict_vocabulary_validate; then exit 2; fi`, and that is bypassable: under `set -u` an +# unbound-variable error inside a FUNCTION aborts the function but not the script, and in the +# `if ! f` form NEITHER branch is then taken — execution simply continues past the gate. Measured: +# with the negative list written as a scalar (`ETV_VERDICT_NEGATIVE_WORDS="blocked"`) and `.*` in the +# positive list, `check-review-verdict.sh` classified an explicit `BLOCKED @ ` as `positive`, +# exit 0, with only a stderr line the calling hook discards. That is the exact fail-open this whole +# file exists to make impossible. +# +# A control-flow gate can be skipped by an abort. A DATA dependency cannot: the words are now +# unobtainable unless validation ran all the way to its final line. +ETV_VERDICT_VOCABULARY_OK=0 + # --- Validation. ------------------------------------------------------------------------------- # The read side interpolates these words into an EXTENDED REGULAR EXPRESSION. That makes the list an # injection surface, and the failure direction is the dangerous one: a stray `.*` in the positive @@ -57,11 +75,33 @@ ETV_VERDICT_NEGATIVE_WORDS=(blocked not-mergeable) # Returns 0 when the vocabulary is usable, 1 otherwise (message on stderr). It never exits: the two # consumers fail closed with DIFFERENT codes (`post` dies 1, `check` exits 2 so its callers treat it # as an unreadable input), so the exit semantics belong to them, not here. -etv_verdict_vocabulary_validate() { - local word seen=' ' +# True when $1 names a set variable carrying the ARRAY attribute. Checked before any `${#name[@]}`, +# because that expansion is nounset-safe ONLY for a declared-empty array: on an UNSET name or on a +# SCALAR it is a fatal unbound-variable error, which is precisely the abort that used to skip +# validation entirely. `declare -p` answers without expanding anything. +etv_verdict__is_array() { + local declaration flags + declaration=$(declare -p "$1" 2>/dev/null) || return 1 + flags=${declaration#declare -} + flags=${flags%% *} + case "$flags" in + *a*) return 0 ;; + *) return 1 ;; + esac +} + +etv_verdict_vocabulary_validate() { + local word seen=' ' name + + ETV_VERDICT_VOCABULARY_OK=0 + + for name in ETV_VERDICT_POSITIVE_WORDS ETV_VERDICT_NEGATIVE_WORDS; do + if ! etv_verdict__is_array "$name"; then + printf 'review-verdict vocabulary: %s is not an array — declare it as %s=(word word), not as a string\n' "$name" "$name" >&2 + return 1 + fi + done - # `${#arr[@]}` is safe on an unset/empty array even under `set -u`, which `"${arr[@]}"` is not on - # bash 3.2 — so the count is checked BEFORE anything expands the arrays. if [ "${#ETV_VERDICT_POSITIVE_WORDS[@]}" -eq 0 ] || [ "${#ETV_VERDICT_NEGATIVE_WORDS[@]}" -eq 0 ]; then printf 'review-verdict vocabulary: the positive and negative lists must both be non-empty\n' >&2 return 1 @@ -88,6 +128,9 @@ etv_verdict_vocabulary_validate() { seen="$seen$word " done + # The ONLY assignment to 1 in this file, and it is the last statement of the successful path. Any + # earlier `return 1`, and any abort part-way through, leaves the sentinel at 0. + ETV_VERDICT_VOCABULARY_OK=1 return 0 } @@ -96,6 +139,11 @@ etv_verdict_vocabulary_validate() { # nothing. Case-insensitive, so the caller may pass the operator's raw argument. etv_verdict_class() { local token word + if [ "${ETV_VERDICT_VOCABULARY_OK:-0}" != 1 ]; then + printf 'review-verdict vocabulary: not validated — refusing to hand out verdict words\n' >&2 + return 1 + fi + token=$(printf '%s' "${1-}" | tr '[:upper:]' '[:lower:]') for word in ${ETV_VERDICT_POSITIVE_WORDS[@]+"${ETV_VERDICT_POSITIVE_WORDS[@]}"}; do @@ -121,6 +169,10 @@ etv_verdict_class() { etv_verdict_alternation() { local alternation='' word local words=() + if [ "${ETV_VERDICT_VOCABULARY_OK:-0}" != 1 ]; then + printf 'review-verdict vocabulary: not validated — refusing to hand out verdict words\n' >&2 + return 1 + fi case "${1-}" in positive) words=(${ETV_VERDICT_POSITIVE_WORDS[@]+"${ETV_VERDICT_POSITIVE_WORDS[@]}"}) ;; @@ -145,6 +197,10 @@ etv_verdict_alternation() { # vocabulary — the same drift this file exists to remove, one layer out. etv_verdict_words_display() { local word index=0 total out='' + if [ "${ETV_VERDICT_VOCABULARY_OK:-0}" != 1 ]; then + printf 'review-verdict vocabulary: not validated — refusing to hand out verdict words\n' >&2 + return 1 + fi set -- ${ETV_VERDICT_POSITIVE_WORDS[@]+"${ETV_VERDICT_POSITIVE_WORDS[@]}"} \ ${ETV_VERDICT_NEGATIVE_WORDS[@]+"${ETV_VERDICT_NEGATIVE_WORDS[@]}"} @@ -164,3 +220,12 @@ etv_verdict_words_display() { printf '%s\n' "$out" } + +# --- Reached-the-end marker. -------------------------------------------------------------------- +# A top-level `exit` in a SOURCED file terminates the sourcing script where it stands, so no check +# placed after the `source` can ever run — the reader returned exit 0 with empty stdout, violating +# its own "exactly one classification word" contract. Both consumers therefore source this file in a +# SUBSHELL first and require the marker below on stdout; a file that exits early never prints it. +# Defining a function is not enough (a truncated file can define every function and still stop +# short), so this is the LAST line and it must stay last. +etv_verdict_vocabulary_loaded() { printf 'etv-verdict-vocabulary-loaded\n'; } diff --git a/scripts/post-review-verdict.sh b/scripts/post-review-verdict.sh index 86115a8a3..ca1ef602d 100755 --- a/scripts/post-review-verdict.sh +++ b/scripts/post-review-verdict.sh @@ -58,9 +58,18 @@ _here=$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) \ VOCABULARY_LIB="$_here/lib/review-verdict-vocabulary.sh" [ -r "$VOCABULARY_LIB" ] \ || die "the shared verdict vocabulary is missing or unreadable at $VOCABULARY_LIB — no status was written" +# Probe-source in a subshell and require the end-of-file marker before trusting the file: a +# top-level `exit` in a sourced library terminates THIS script at the `source` line, which exited 0 +# having posted neither a status nor a comment. See the read side for the full reasoning. +# shellcheck source=lib/review-verdict-vocabulary.sh +vocabulary_probe=$( . "$VOCABULARY_LIB" >/dev/null 2>&1 && etv_verdict_vocabulary_loaded 2>/dev/null ) || vocabulary_probe='' +[ "$vocabulary_probe" = 'etv-verdict-vocabulary-loaded' ] \ + || die "the shared verdict vocabulary at $VOCABULARY_LIB did not load to completion (syntax error, truncated, or it exits at top level) — no status was written" # shellcheck source=lib/review-verdict-vocabulary.sh . "$VOCABULARY_LIB" \ || die "the shared verdict vocabulary at $VOCABULARY_LIB could not be sourced — no status was written" +# `set -e` makes this `die` reliable here, unlike on the read side — but the sentinel the library +# sets on validation's last line is what actually gates the words, on both sides. etv_verdict_vocabulary_validate \ || die "the shared verdict vocabulary at $VOCABULARY_LIB did not validate (see above) — no status was written" diff --git a/scripts/tests/test_check_review_verdict.py b/scripts/tests/test_check_review_verdict.py index 2c7c6f4ed..743e23640 100644 --- a/scripts/tests/test_check_review_verdict.py +++ b/scripts/tests/test_check_review_verdict.py @@ -429,7 +429,9 @@ def test_non_hex_head_is_an_input_error(): # completeness claim: the property below is PER-MEMBER — "each of these words classifies as exactly # one thing" — so a word missing from this list is simply an untested word, not a defect the list # conceals. It is emphatically NOT a claim that these are the only words the scripts accept. Proving -# THAT needs one shared vocabulary both scripts read, which is ersatztv#788. +# THAT is what the shared vocabulary in `scripts/lib/review-verdict-vocabulary.sh` supplies +# (ersatztv#788, landed); `test_review_verdict_vocabulary.py` makes the completeness claim against +# that one declaration, which is why this list may stay a per-member literal. POSITIVE_WORDS = ["MERGEABLE", "APPROVED", "LGTM"] NEGATIVE_WORDS = ["BLOCKED", "NOT-MERGEABLE"] @@ -463,7 +465,7 @@ def test_each_verdict_word_retains_its_established_polarity(word, expected): both flags and precedence decides. WHICH DIRECTION THIS CATCHES, MEASURED RATHER THAN REASONED — the first draft of this docstring - asserted it and was checked afterwards, which is the wrong order. `check-review-verdict.sh:212` + asserted it and was checked afterwards, which is the wrong order. `check-review-verdict.sh:279` reads `if [ "$is_pos" = 1 ]; then head_pos=1; else head_neg=1; fi`, so `is_pos` wins per line and an overlapping word resolves POSITIVE. Both mutations were run against this test: diff --git a/scripts/tests/test_review_verdict_vocabulary.py b/scripts/tests/test_review_verdict_vocabulary.py index b923583fe..63700e1cb 100644 --- a/scripts/tests/test_review_verdict_vocabulary.py +++ b/scripts/tests/test_review_verdict_vocabulary.py @@ -183,6 +183,10 @@ def test_a_MISSING_vocabulary_makes_the_write_side_refuse_to_post(sandbox): assert sandbox.posted_status_state() is None, "no status may be written without a vocabulary" +@pytest.mark.skipif( + hasattr(os, "geteuid") and os.geteuid() == 0, + reason="mode 000 does not make a file unreadable to root, and script-tests runs in a container", +) def test_an_UNREADABLE_vocabulary_is_refused_rather_than_skipped(sandbox): sandbox.vocabulary.chmod(0o000) try: @@ -304,3 +308,125 @@ def test_the_write_side_maps_the_shipped_words_onto_the_same_states(sandbox, tok matrix stays green if the negative arm maps onto `success` too.""" assert sandbox.write_side(token).returncode == 0 assert sandbox.posted_status_state() == state + + +# --- A control-flow gate can be SKIPPED; the sentinel is what actually holds. -------------------- +# +# Under `set -u`, an unbound-variable error inside a FUNCTION aborts the function but not the +# script, and in an `if ! validate` form NEITHER branch is then taken — so the `exit 2` never runs +# and execution continues past the gate. `check-review-verdict.sh` runs without `set -e`, so the +# words reached the regex unvalidated: with `.*` in the positive list and the negative list written +# as a scalar, an explicit `BLOCKED @ ` classified `positive`, exit 0. The calling hook +# discards stderr, so the only signal was invisible. +# +# The fix is a DATA dependency rather than a control-flow one: validation sets +# `ETV_VERDICT_VOCABULARY_OK=1` on its last line, and the derived views refuse without it. These +# tests pin the malformation classes that produce the abort. + + +def test_a_SCALAR_word_list_cannot_reach_the_regex_unvalidated(sandbox): + """The originally-measured fail-open, pinned end to end. + + Two faults at once, because that is the shape that produced `positive`: a metacharacter in the + positive list (which only matters if validation is skipped) and a scalar negative list (which is + what skips it). + """ + sandbox.edit_vocabulary(POSITIVE_DECL, 'ETV_VERDICT_POSITIVE_WORDS=(mergeable ".*")') + sandbox.edit_vocabulary(NEGATIVE_DECL, 'ETV_VERDICT_NEGATIVE_WORDS="blocked"') + + result = sandbox.read_side("BLOCKED") + assert result.stdout.strip() != "positive", ( + "an explicit BLOCKED verdict classified as positive — the word list reached the regex " + "without validation completing" + ) + assert result.returncode == 2 + + +def test_a_SCALAR_word_list_is_refused_even_with_no_metacharacter(sandbox): + """The single-fault case, which is the realistic wrong edit. + + Writing the list as a string is the natural mistake, and on its own it silently degraded every + negative verdict from `negative` to `unknown` — DENY downgraded to ASK — with no non-zero exit. + """ + sandbox.edit_vocabulary(NEGATIVE_DECL, 'ETV_VERDICT_NEGATIVE_WORDS="blocked not-mergeable"') + + result = sandbox.read_side("BLOCKED") + assert result.returncode == 2 + assert result.stdout.strip() != "negative", "expected a refusal, not a lucky classification" + assert "is not an array" in result.stderr + + +def test_an_UNSET_word_list_is_refused(sandbox): + sandbox.edit_vocabulary(NEGATIVE_DECL, "unset ETV_VERDICT_NEGATIVE_WORDS") + result = sandbox.read_side("BLOCKED") + assert result.returncode == 2 + assert result.stdout.strip() != "positive" + + +def test_a_library_that_EXITS_at_top_level_does_not_return_exit_0_with_no_verdict(sandbox): + """A top-level `exit` in a SOURCED file terminates the sourcing script where it stands. + + No check written after the `source` can run, so the reader returned exit 0 with EMPTY stdout — + violating its own "exactly one classification word" contract. A caller testing only the exit + code would read that as a successful classification. The subshell probe moves the failure + somewhere observable. + """ + sandbox.vocabulary.write_text("exit 0\n") + + result = sandbox.read_side("BLOCKED") + assert result.returncode == 2, f"exit {result.returncode} with stdout {result.stdout!r}" + assert result.stdout.strip() == "" + + write = sandbox.write_side("MERGEABLE") + assert write.returncode != 0 + assert sandbox.posted_status_state() is None + + +def test_a_TRUNCATED_library_is_refused_rather_than_half_used(sandbox): + """A file cut short can define every function it got to and still be incomplete. + + So the marker the probe requires is the LAST line of the library, not merely a function it + defines somewhere. + """ + text = sandbox.vocabulary.read_text() + marker = "etv_verdict_vocabulary_loaded()" + assert marker in text, "the end-of-file marker moved; this test no longer truncates anything" + # Cut exactly at the marker: everything before it is a file that defines every function it got + # to and is still incomplete. A fixed line count would drift as the library grows. + sandbox.vocabulary.write_text(text[: text.index(marker)]) + + result = sandbox.read_side("BLOCKED") + assert result.returncode == 2 + assert result.stdout.strip() != "positive" + + +def test_the_sentinel_cannot_be_PRE_SET_from_the_environment(sandbox): + """Otherwise the data dependency would be forgeable by whoever sets the environment.""" + env = dict(sandbox.env) + env["ETV_VERDICT_VOCABULARY_OK"] = "1" + sandbox.edit_vocabulary(NEGATIVE_DECL, 'ETV_VERDICT_NEGATIVE_WORDS="blocked"') + + result = subprocess.run( + ["bash", str(sandbox.reader), "--head", SHA_A], + input=json.dumps([{"body": f"Review-verdict: BLOCKED @ {SHA_A}"}]), + env=env, + capture_output=True, + text=True, + ) + assert result.returncode == 2, "an inherited sentinel must not stand in for validation" + assert result.stdout.strip() != "positive" + + +def test_a_VALID_vocabulary_still_sets_the_sentinel_and_classifies(sandbox): + """The positive control for every refusal above: the guard must not simply always refuse.""" + env = dict(sandbox.env) + env["ETV_VERDICT_VOCABULARY_OK"] = "1" + result = subprocess.run( + ["bash", str(sandbox.reader), "--head", SHA_A], + input=json.dumps([{"body": f"Review-verdict: BLOCKED @ {SHA_A}"}]), + env=env, + capture_output=True, + text=True, + ) + assert result.returncode == 0 + assert result.stdout.strip() == "negative"