fix(648,649): security-review round 2 — close the version-parse hole and the untested caller contract

Two real defects, and three docs claims that were simply wrong.

jq-preflight.sh parsed the version by stripping around the first `-` and `.`, which
assumed the format is exactly `jq-X.Y`. A build printing `jq version 1.6` left major
empty; the sanity check concatenated major+minor into "6", which is non-empty and
all-digits, so it PASSED. The floor comparison then ran `[ "" -lt 1 ]`, which errors —
and `set -e` exempts a failing command in an `if` condition, so the conditional read
false and the script exited 0 having asserted nothing, after printing a plausible
"parsed" line. The silently-untested-axis failure this script exists to eliminate,
reproduced inside the script itself. Now parsed by explicit regex, failing closed with a
diagnosis when there is no <digits>.<digits> match. Also: `--expect` with no value exited
1 with empty output on both streams.

The hook's exit-status check was pinned by nothing: mutating `if files=$(...)` into
`files=$(...) || true; files_complete=yes` left the ENTIRE suite green. It survived only
by redundancy — the script writes stdout once, right before exit 0, so failures also
happen to yield empty stdout and `[ -n "$files" ]` catches it. Safe by accident, which is
the exact criticism this branch levels at the old code. Four tests now pin it, with a
stub that FAILS while emitting a docs-only list (the one case redundancy cannot absorb)
plus a positive control proving the harness can see the difference. Verified: the
mutation now turns exactly those tests red.

Docs corrections. The record claimed the --expect pin was safe because script-tests is
"advisory, not a required check" — false. The merge-consent hook reads the COMBINED
status (ci.advisory-red-blocks-the-merge-gate, #598), so firing the tripwire blocks every
non-docs-only merge until someone re-pins. Kept anyway, for a stated reason, but no
longer described as free. The record also asserted in the present tense that
review-verdict.yml checks out the base ref; it has no checkout step at all, so that is
now a future-tense requirement on the follow-up. And the documented .status allow-list
named GitHub's `removed`, which the code rejects.

The drift-guard regex anchored on `?limit=`, so a re-inlined copy written
`files?page=1&limit=50` would have walked past it.

Decisions-Edit: yes
This commit is contained in:
2026-07-26 22:21:07 +02:00
parent 2c10f057b8
commit 5e7623b8d5
6 changed files with 229 additions and 31 deletions
@@ -46,13 +46,28 @@ assumed. So the fix has to hold at 1.6, in every gate, regardless of which lane
is upgraded (a base-image bump, a host reimage, anything outside this repo's control), every PR
on `main` stops merging until someone notices and re-pins. A required merge gate cannot have a
failure mode that is "an upstream package manager did its job."
- `--expect 1.6` — pin and fail loudly. Used only by `script-tests`, which is advisory (it reddens the
run but is not one of the three required checks). `scripts/tests/` currently exercises the 1.6 code
path only because the runner happens to ship 1.6; if that silently changed, the 1.6 coverage this
whole contract depends on would evaporate with no signal. The tripwire forces a human decision —
re-pin after re-reading this record, or add a real 1.6 matrix leg — instead of letting the coverage
quietly disappear. Failing here costs a red on a non-required job; failing the same way on
`review-verdict.yml` costs every PR its ability to merge.
- `--expect 1.6` — pin and fail loudly. Used only by `script-tests`. `scripts/tests/` currently
exercises the 1.6 code path only because the runner happens to ship 1.6; if that silently changed,
the 1.6 coverage this whole contract depends on would evaporate with no signal. The tripwire forces
a human decision — re-pin after re-reading this record, or add a real 1.6 matrix leg — instead of
letting the coverage quietly disappear.
**Be honest about the cost: firing this tripwire DOES block merges.** An earlier draft of this
record claimed the pin was safe because `script-tests` is "advisory, not one of the required
checks". That reasoning is wrong, and the correction is worth recording because it is easy to make
twice. `.claude/hooks/pretooluse-merge-consent.sh` reads the **combined** commit status and denies
on anything that is not `success`/`skipped` — see `ci.advisory-red-blocks-the-merge-gate` (#598).
`script-tests` is a Gitea Actions job, so its red is a context folded into that combined state.
A jq bump therefore reddens `script-tests` and blocks every non-docs-only merge in the repo until
someone re-pins.
The pin is kept anyway, deliberately: the fix is a one-line edit to the `--expect` value in
`pr-checks.yml`, the failure message spells that out, and the alternative — silently losing the
only coverage of the version axis that produced three bugs in one day — is worse than a visible
stop. What is NOT acceptable is believing it is free. The difference from `review-verdict.yml` is
therefore one of *degree and recoverability*, not of "blocks merges vs doesn't": there the check is
required per-sha and a jq bump would deadlock merges with no in-repo remedy at all, whereas here a
human can unblock the repo in one commit.
**The three constructs to avoid, and their version-stable replacements:**
@@ -59,8 +59,12 @@ different.
in each caller:
- CR/LF rejection and `..` rejection on every path.
- A closed `.status` allow-list (`added`/`modified`/`removed`/`renamed`/`copied`), not an open
denylist.
- A closed `.status` allow-list — `added`/`deleted`/`changed`/`modified`/`renamed`/`copied`, not an
open denylist. Note `changed` and `deleted` are the values live Gitea 1.25.4 actually emits;
`modified` is accepted alongside `changed` because a closed list built from the wrong vocabulary
would gate every genuine docs-only PR. GitHub's `removed` is deliberately **not** in the list — an
earlier draft of this record said it was, which would have sent a maintainer looking for a value
the code rejects.
- `previous_filename` validated on **every** row the extraction consumes, not only rows whose
`.status` is `renamed` — a `modified`/`copied` row can still carry it, and an earlier fix that
validated only the `renamed` case was found incomplete for exactly this reason (see
@@ -71,9 +75,18 @@ in each caller:
list if it moved mid-enumeration, since paging is several round-trips and a force-push between them
would otherwise yield a list belonging to no single commit.
**`review-verdict.yml` also now checks out the PR's BASE ref, never the head**, so the workflow that
judges a PR cannot be rewritten by that same PR to weaken its own judgment — a PR editing
`review-verdict.yml` executes the *pre-PR* version of the gate against itself.
**Base-ref checkout — a REQUIREMENT on the follow-up, not yet a property of the tree.** When
`review-verdict.yml` is wired to this script it MUST check out the PR's BASE ref
(`ref: ${{ github.event.pull_request.base.sha }}`, plus `persist-credentials: false`), never the
head, so the workflow that judges a PR cannot be rewritten by that same PR to weaken its own
judgment.
Stated in the future tense deliberately. Today `review-verdict.yml` has **no `actions/checkout` step
at all** — it is a pure inline `run:` — so nothing about base-vs-head holds of it right now, and the
`PROTECTED` path list is the only thing standing between a PR and the gate. An earlier draft asserted
this in the present tense; a reader resolving this record from the catalog would have concluded the
self-rewrite hole was already closed. Adding a bare `run:` line in the follow-up is **not**
sufficient — the checkout and its `ref` are the security-relevant parts.
**Severity, stated honestly.** Every enumeration defect found in this area (#643) downgraded a
mechanical deny/ask to a human prompt on the hook side; none produced a silent self-merge on their
+29 -13
View File
@@ -53,7 +53,15 @@ MIN_VERSION="1.6"
expect=""
while [ "$#" -gt 0 ]; do
case "$1" in
--expect) expect="${2:-}"; shift 2 ;;
--expect)
# `shift 2` with a missing value fails under `set -e` and exits 1 with NOTHING on either
# stream — a CI step dying with an empty log is exactly the diagnostic hole this script exists
# to remove. Check explicitly instead.
if [ "$#" -lt 2 ] || [ -z "${2:-}" ]; then
echo "jq-preflight: --expect requires a <major.minor> value" >&2
exit 2
fi
expect="$2"; shift 2 ;;
*) echo "jq-preflight: unknown argument '$1'" >&2; exit 2 ;;
esac
done
@@ -65,23 +73,31 @@ fi
raw=$(jq --version 2>&1 || true)
# `jq --version` prints e.g. `jq-1.6`, `jq-1.7.1`, or on some builds `jq-1.8.2-dirty`.
version=${raw#jq-}
major=${version%%.*}
rest=${version#*.}
minor=${rest%%.*}
# Some builds append a suffix with no further dot ("jq-1.6-dirty", "jq-1.7rc1"), which would otherwise
# leave a non-numeric minor and fail closed on a perfectly ordinary jq. Keep the leading digits only.
major=${major%%[!0-9]*}
minor=${minor%%[!0-9]*}
# Parse with an explicit regex rather than by stripping around the first `-` and `.`.
#
# The strip approach had a hole that defeated the whole point of this script. It assumed the format
# is exactly `jq-X.Y`, so a build printing anything else — `jq version 1.6` (a distro wrapper),
# `JQ-1.6`, `jq-1.-6` — left ONE of major/minor empty. The old sanity check was
# `case "$major$minor" in *[!a-9]*|"")`, and on `jq version 1.6` that concatenation is "6": non-empty
# and all-digits, so the guard PASSED. The floor comparison then ran `[ "" -lt 1 ]`, which exits 2
# with "integer expression expected" — and `set -e` exempts a failing command in an `if` condition,
# so the whole conditional read false and the script exited 0 having asserted NOTHING, after printing
# a plausible-looking "parsed" line.
#
# That is the silently-untested-axis failure this script was written to eliminate, reproduced inside
# the script itself. Require a real `<digits>.<digits>` match, and fail closed when there isn't one.
if [[ "$raw" =~ ([0-9]+)\.([0-9]+) ]]; then
major="${BASH_REMATCH[1]}"
minor="${BASH_REMATCH[2]}"
else
echo "jq-preflight: could not parse a major.minor version out of '${raw}'. Refusing to assert a floor against an unparsed version — that would silently pass." >&2
exit 1
fi
# THIS LINE IS THE POINT of the no-arg mode: the jq version CI actually used is in the job log, so a
# future divergence can be diagnosed from the log alone rather than by guessing at the runner image.
echo "jq-preflight: jq version in use = ${raw} (parsed ${major}.${minor}; floor ${MIN_VERSION})"
case "$major$minor" in
*[!0-9]*|"") echo "jq-preflight: could not parse a major.minor out of '${raw}' — failing closed" >&2; exit 1 ;;
esac
min_major=${MIN_VERSION%%.*}
min_minor=${MIN_VERSION#*.}
if [ "$major" -lt "$min_major" ] || { [ "$major" -eq "$min_major" ] && [ "$minor" -lt "$min_minor" ]; }; then
+9 -3
View File
@@ -123,9 +123,15 @@ while [ "$page" -le "$MAX_PAGES" ]; do
# * `..` is rejected because the callers' allow-lists anchor `^docs/`, so `docs/../ErsatzTV/Program.cs`
# matches one. Git will not produce such a path; this guard's job is to fail closed on unexpected
# 2xx shapes rather than assume a well-behaved peer.
# * `.status` is checked against a CLOSED set. Without it the `renamed => previous_filename REQUIRED`
# clause is dodgeable by any other value — `"Renamed"` with a capital R, or an absent status —
# letting a `git mv ErsatzTV/Program.cs -> docs/a.md` drop its source path and read as docs-only.
# * `.status` is checked against a CLOSED set. Be precise about what this does and does not do:
# the extraction below emits `(.previous_filename // empty)` UNCONDITIONALLY, so a present
# `previous_filename` is never dropped on account of `.status`. What the closed set actually buys
# is rejecting rows whose vocabulary we do not recognise — where a source path may be absent, or
# carried in some other field we are not reading. Without it, `"Renamed"` with a capital R, or an
# absent status, silently takes the `else true` branch of the clause below and skips the
# "renamed rows MUST carry previous_filename" requirement entirely. (An earlier version of this
# comment claimed the source path would be "dropped", which is not the mechanism; a maintainer
# who tested that claim would find it false and might conclude the check is redundant.)
# `modified` is accepted alongside `changed` deliberately: live Gitea 1.25.4 emits `changed`, but a
# closed allow-list built from the wrong vocabulary is a worse failure than the hole it closes — it
# would gate every genuine docs-only PR on any version that spells it differently. The property is
+40
View File
@@ -123,6 +123,46 @@ def test_unknown_argument_is_a_usage_error(preflight):
assert preflight.run("--pin", "1.6").returncode == 2
def test_expect_without_a_value_is_a_usage_error_WITH_output(preflight):
"""`shift 2` on a missing value exits 1 under `set -e` with NOTHING on either stream. A CI step
that dies with an empty log is the diagnostic hole this script exists to remove."""
preflight.with_jq("jq-1.6")
r = preflight.run("--expect")
assert r.returncode == 2
assert "requires a <major.minor> value" in r.stderr
# --- Version parsing: the guard must never assert a floor against an unparsed version ----------
#
# The original strip-based parse assumed the format is exactly `jq-X.Y`. Anything else left major or
# minor EMPTY, and the sanity check concatenated them — so `jq version 1.6` produced "6", which is
# non-empty and all-digits, so the check PASSED. The floor comparison then ran `[ "" -lt 1 ]`, which
# errors; `set -e` exempts a failing command in an `if` condition, so the conditional read false and
# the script exited 0 having asserted NOTHING. That is this script's own stated failure mode,
# reproduced inside itself, which is why these cases are pinned rather than left to inspection.
@pytest.mark.parametrize("version_line", [
"jq version 1.6", # some distro wrappers print this form
"JQ-1.6",
"jq-1.6-dirty",
])
def test_unusual_but_parseable_version_forms_are_accepted(preflight, version_line):
preflight.with_jq(version_line)
r = preflight.run()
assert r.returncode == 0, f"{version_line!r}: {r.stderr}"
assert "parsed 1.6" in r.stdout
@pytest.mark.parametrize("version_line", ["jq-1.-6", "jq-.6", "not-a-version", ""])
def test_unparseable_version_fails_CLOSED_rather_than_asserting_nothing(preflight, version_line):
preflight.with_jq(version_line)
r = preflight.run()
assert r.returncode == 1, (
f"{version_line!r} exited {r.returncode}: an unparsed version must never reach — or "
"silently skip — the floor assertion")
assert "could not parse" in r.stderr
# --- Wiring guards: the preflight is worthless if a caller silently stops running it ------------
def test_script_tests_pins_the_jq_version():
+111 -3
View File
@@ -33,7 +33,7 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
SCRIPT = REPO_ROOT / "scripts" / "pr-changed-files.sh"
HOOK = REPO_ROOT / ".claude" / "hooks" / "pretooluse-merge-consent.sh"
WORKFLOW = REPO_ROOT / ".gitea" / "workflows" / "review-verdict.yml"
# (the enforced caller, .gitea/workflows/review-verdict.yml, is wired in the follow-up PR)
SHA = "a9e3e23abf337980ca4c05854f5b1e210099d08b"
OTHER_SHA = "b71c0d4e2f8a91b3c5d7e9f1a3b5c7d9e1f3a5b7"
@@ -237,6 +237,110 @@ def test_a_SHORT_page_does_not_end_the_enumeration(enumerate_files):
assert "ErsatzTV/Program.cs" in enumerate_files.paths()
# --- The CALLER contract: a non-zero exit must withhold the exemption, on its own -------------
#
# This is the single line the whole extraction rests on, and it was the one guard nothing pinned. A
# review mutated the hook's `if files=$(...)` into `files=$(...) || true; files_complete=yes` — i.e.
# ignore the exit status entirely — and the ENTIRE suite still passed.
#
# It survives today only by REDUNDANCY: the script writes stdout once, immediately before `exit 0`,
# so every failure path also happens to yield empty stdout, and the hook's independent
# `[ -n "$files" ]` check catches it. That is exactly the shape this PR criticises elsewhere — safe
# by accident rather than by assertion. Any future change that streams pages, or prints a partial
# list before failing, turns it into a live false exemption.
#
# So the stub below FAILS *while emitting a perfectly docs-only list*, which is the one combination
# the redundancy cannot absorb. The positive control immediately after it proves the harness can
# actually observe the difference, rather than reporting "not exempt" for some unrelated reason.
HOOK_STUB_CURL = r'''#!/usr/bin/env python3
import json, sys
url = [a for a in sys.argv[1:] if a.startswith("http")][-1]
if "/pulls/" in url and "/files" not in url:
print(json.dumps({"head": {"sha": "%s"}, "body": "no linked issue"}))
else:
print("{}")
''' % SHA
def _mirror_tree(tmp_path, stub_body):
"""Lay out a minimal repo mirror so the hook resolves OUR stub as the shared script.
The hook finds the script via `${BASH_SOURCE[0]}/../..`, so the mirror must reproduce the real
`.claude/hooks/` + `scripts/` shape rather than just dropping the stub anywhere.
"""
hooks = tmp_path / ".claude" / "hooks"
hooks.mkdir(parents=True)
(hooks / "pretooluse-merge-consent.sh").write_text(HOOK.read_text())
scripts = tmp_path / "scripts"
scripts.mkdir()
stub = scripts / "pr-changed-files.sh"
stub.write_text(stub_body)
stub.chmod(0o755)
bindir = tmp_path / "bin"; bindir.mkdir()
curl = bindir / "curl"; curl.write_text(HOOK_STUB_CURL); curl.chmod(0o755)
env = dict(os.environ)
env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"
env["ETV_GITEA_TOKEN"] = "stub"
env["ETV_GITEA_URL"] = "http://gitea.example"
env.pop("ETV_GITEA_BASICAUTH", None)
payload = {"tool_input": {"method": "merge", "owner": "timothy",
"repo": "ersatztv", "pull_number": 42}}
r = subprocess.run(["bash", str(hooks / "pretooluse-merge-consent.sh")],
input=json.dumps(payload), env=env, capture_output=True, text=True)
assert r.returncode == 0, r.stderr
# Exempt == passthrough == exit 0 with no decision JSON on stdout.
return r.stdout.strip() == ""
DOCS_ONLY_OUTPUT = 'printf "docs/a.md\\ndocs/b.md\\n"\n'
def test_a_FAILING_script_withholds_the_exemption_even_when_stdout_looks_docs_only(tmp_path):
exempt = _mirror_tree(tmp_path, "#!/usr/bin/env bash\n" + DOCS_ONLY_OUTPUT + "exit 1\n")
assert exempt is False, (
"the hook granted a docs-only exemption from the stdout of a script that FAILED — the exit "
"status is not being checked")
def test_positive_control_the_same_output_with_exit_0_DOES_exempt(tmp_path):
"""Without this, the test above could pass for any unrelated reason and prove nothing."""
exempt = _mirror_tree(tmp_path, "#!/usr/bin/env bash\n" + DOCS_ONLY_OUTPUT + "exit 0\n")
assert exempt is True, (
"the positive control failed, so the negative test above cannot be trusted to be measuring "
"the exit status at all")
def test_a_script_that_crashes_also_withholds_the_exemption(tmp_path):
"""Not every failure is a clean `exit 1` — a crash must not read as success either."""
exempt = _mirror_tree(
tmp_path, "#!/usr/bin/env bash\n" + DOCS_ONLY_OUTPUT + "kill -TERM $$\n")
assert exempt is False
def test_a_MISSING_script_withholds_the_exemption(tmp_path):
"""The transition window: the shared checkout has no such script until this lands."""
hooks = tmp_path / ".claude" / "hooks"
hooks.mkdir(parents=True)
(hooks / "pretooluse-merge-consent.sh").write_text(HOOK.read_text())
(tmp_path / "scripts").mkdir()
bindir = tmp_path / "bin"; bindir.mkdir()
curl = bindir / "curl"; curl.write_text(HOOK_STUB_CURL); curl.chmod(0o755)
env = dict(os.environ)
env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"
env["ETV_GITEA_TOKEN"] = "stub"
env["ETV_GITEA_URL"] = "http://gitea.example"
payload = {"tool_input": {"method": "merge", "owner": "timothy",
"repo": "ersatztv", "pull_number": 42}}
r = subprocess.run(["bash", str(hooks / "pretooluse-merge-consent.sh")],
input=json.dumps(payload), env=env, capture_output=True, text=True)
assert r.returncode == 0, r.stderr
assert r.stdout.strip() != "", "a missing shared script must not grant an exemption"
# --- Drift guard: the reason this file is worth having at all ----------------------------------
def test_the_hook_uses_the_shared_script_and_does_not_reimplement_it():
@@ -257,7 +361,11 @@ def test_the_hook_uses_the_shared_script_and_does_not_reimplement_it():
text = HOOK.read_text()
assert "scripts/pr-changed-files.sh" in text, (
f"{HOOK.relative_to(REPO_ROOT)} no longer calls the shared enumeration")
# An inline `pulls/<n>/files?limit=` fetch is the signature of a re-inlined copy.
assert not re.search(r"pulls/\$?\{?\w+\}?/files\?limit=", text), (
# An inline `pulls/<n>/files?` fetch is the signature of a re-inlined copy. Match on the endpoint
# alone, NOT on `?limit=` — an earlier version anchored the query string, so a copy written as
# `files?page=1&limit=50` would have walked straight past a guard that exists to stop exactly
# that. A drift guard one refactor away from decorative is worse than none, because it reads as
# coverage.
assert not re.search(r"pulls/\$?\{?\w+\}?/files\?", text), (
f"{HOOK.relative_to(REPO_ROOT)} appears to enumerate PR files inline again — "
"that is the duplication ersatztv#649 removed")