fix(631): close a fail-open in the merge-consent gate that only CI could see
Running scripts/tests in CI for the first time turned up a real defect in the gate itself, not just in the harness. `jq -e` over EMPTY input exits 4 on jq >= 1.7 but 0 on jq 1.6 — verified against both binaries, not inferred. The docs-only pagination guard in pretooluse-merge-consent.sh leaned on that exit status to reject a transport failure. On jq 1.6, which the CI runner ships: page 2 errors -> gq returns empty -> jq guard wrongly PASSES -> n is empty so [ "$n" -lt 50 ] errors into false -> the loop walks PAST the failed page -> page 3 legitimately returns [] -> files_complete=yes over a PARTIAL list -> the docs-only exemption fires over unread pages that may be pure code. That is the very defect the guard's own comment describes, reintroduced one layer down by a jq version difference. Fixed by rejecting an empty body explicitly rather than inferring it from jq's exit status. The same hardening is applied to the review-verdict status read, which fell through to `vstate=""` -> deny (fail-CLOSED, so never a hole) but would have surfaced the wrong message. Why it survived: the existing transport-failure test asserts the right thing but can only observe the bug where jq is 1.6, so it passes on a developer Mac with the bug fully present — and the suite had never run anywhere else. The new test removes that dependency by shimming ONLY jq 1.6's empty-input exit status, so it pins the property on any host. Mutation-verified: revert the fix and it goes red on jq 1.8.2. The shim is deliberately narrow (no `-n`): a broader first version swallowed the `jq -n` calls `decide` uses to build its JSON, so the hook emitted nothing and every decision read as a passthrough — the verifier manufacturing the exemption it was meant to disprove. test_jq16_shim_actually_reproduces_the_quirk now pins the shim itself, `-n` case included. Suite: 113 passed under jq 1.8.2 AND under jq 1.6. Refs #631
This commit is contained in:
@@ -103,6 +103,18 @@ while [ "$page" -le 40 ]; do
|
||||
# the enumeration from a partial list. Require every row to carry a non-empty string `filename`
|
||||
# (an empty array is still valid — that is a genuine end-of-pagination). This also rejects arrays
|
||||
# of scalars, which would otherwise make the `.filename` extraction below fail under `set -e`.
|
||||
#
|
||||
# An EMPTY body is rejected EXPLICITLY here rather than left to jq's exit status, because that
|
||||
# status is not portable: `jq -e` over empty input exits 4 on jq >= 1.7 but **0 on jq 1.6**
|
||||
# (verified against both binaries — ersatztv#631). Relying on it made this guard fail OPEN on any
|
||||
# host with the older jq, including the CI runner, which ships jq 1.6. The chain: a transport
|
||||
# failure makes `gq` return empty, the jq guard wrongly passes, `n` is empty so `[ "$n" -lt 50 ]`
|
||||
# errors into false, the loop walks PAST the failed page, the NEXT page legitimately returns `[]`,
|
||||
# and `files_complete=yes` is set over a PARTIAL list — exempting a PR whose unread pages may be
|
||||
# pure code. That is the very defect the paragraph above describes, reintroduced one layer down.
|
||||
if [ -z "${raw//[[:space:]]/}" ]; then
|
||||
files_complete=no; break
|
||||
fi
|
||||
if ! printf '%s' "$raw" \
|
||||
| jq -e 'type == "array" and all(.[]; (.filename | type == "string" and length > 0) and (if .status == "renamed" then (.previous_filename | type == "string" and length > 0) else true end))' \
|
||||
>/dev/null 2>&1; then
|
||||
@@ -210,7 +222,11 @@ else
|
||||
# the first page and read as absent — a confusing false deny. The combined endpoint returns
|
||||
# latest-per-context, which is exactly the question being asked.
|
||||
vjson=$(gq "repos/$owner/$repo/commits/$sha/status?limit=100")
|
||||
if ! printf '%s' "$vjson" | jq -e '.statuses | type == "array"' >/dev/null 2>&1; then
|
||||
# Same portability point as the file-pagination guard above: do not let jq's empty-input exit
|
||||
# status decide this. Here the fallthrough happens to land on `vstate=""` -> deny (fail-CLOSED,
|
||||
# so this was never a hole), but it would have surfaced the wrong message — a "BLOCKED, no
|
||||
# verdict" deny instead of the "could not read the status" ask this branch exists to give.
|
||||
if [ -z "${vjson//[[:space:]]/}" ] || ! printf '%s' "$vjson" | jq -e '.statuses | type == "array"' >/dev/null 2>&1; then
|
||||
decide ask "H6/H10 merge gate: could not read the 'review-verdict/h10' status for PR #$pr head ${sha:0:7} (Gitea unreachable or an unexpected response). Confirm the current head is reviewed before scheduling an auto-merge."
|
||||
fi
|
||||
vstate=$(printf '%s' "$vjson" | jq -r '[.statuses[] | select(.context == "review-verdict/h10")] | first | .status // ""')
|
||||
|
||||
@@ -43,6 +43,25 @@ temp repo it creates itself, never this repository's history.
|
||||
lesson): a deliberately-failing test was confirmed to exit non-zero locally and to turn the CI job
|
||||
red on a scratch PR, before the passing state was accepted as meaningful.
|
||||
|
||||
**What running it in CI immediately found.** The first green-on-my-machine run went red twice, and
|
||||
both reds were real:
|
||||
|
||||
1. `ModuleNotFoundError: No module named 'yaml'` — the suite is not stdlib-only
|
||||
(`test_migration_equivalence.py` imports `migrate_decisions_split`, whose write path uses
|
||||
PyYAML). It passed locally only because the author's machine had PyYAML.
|
||||
2. A **fail-open in the merge-consent gate itself.** `jq -e` over EMPTY input exits 4 on jq ≥ 1.7
|
||||
but **0 on jq 1.6** (verified against both binaries), and the docs-only pagination guard leaned
|
||||
on that exit status to reject a transport failure. On jq 1.6 — which the CI runner ships — the
|
||||
failed page passed the guard, the loop walked past it, the next page legitimately returned `[]`,
|
||||
and `files_complete=yes` was set over a PARTIAL list: the docs-only exemption firing over unread
|
||||
pages that may be pure code. Fixed by rejecting an empty body explicitly instead of inferring it
|
||||
from jq's exit status.
|
||||
|
||||
The second one is the argument for this record in miniature. It sat in the gate that decides whether
|
||||
a PR skips the Done-when checks, it was covered by an existing test, and that test could not catch it
|
||||
on a developer Mac (jq 1.8) — only in CI, where the suite had never run. **Standing rule it leaves
|
||||
behind: never infer "empty input" from a jq exit status; check the string.**
|
||||
|
||||
It is not yet a *required* status check — `main` requires only `Build & test (.NET)`,
|
||||
`EF migration integrity` and `review-verdict/h10`. It reddens the run; promoting it to required is a
|
||||
branch-protection change left deliberately separate.
|
||||
|
||||
@@ -230,3 +230,109 @@ def test_exceeding_max_pages_withholds_the_exemption(hook):
|
||||
"""41 full pages: enumeration cannot be proven exhaustive, so no exemption."""
|
||||
hook.set_pages(*[_rows([f"docs/p{p}f{i}.md" for i in range(50)]) for p in range(41)])
|
||||
assert hook.exempted() is False
|
||||
|
||||
|
||||
# --- #631: the guard must not depend on jq's empty-input exit status ---------------------------
|
||||
#
|
||||
# `jq -e` over EMPTY input exits 4 on jq >= 1.7 but 0 on jq 1.6. The pagination guard originally
|
||||
# leaned on that status to reject a transport failure, so on jq 1.6 the failed page passed the
|
||||
# guard, the loop walked PAST it, the next page legitimately returned `[]`, and the enumeration
|
||||
# completed from a PARTIAL list — the docs-only exemption firing over unread pages.
|
||||
#
|
||||
# This was invisible for two compounding reasons: the suite never ran in CI at all (#631), and
|
||||
# `test_transport_failure_mid_pagination_withholds_the_exemption` above only exposes it when the
|
||||
# host jq happens to be 1.6 — it passes on a developer Mac (1.8.x) with the bug fully present.
|
||||
# So that test cannot pin this property; this one does, on ANY jq, by putting a shim on PATH that
|
||||
# reproduces the single 1.6 behaviour and nothing else.
|
||||
|
||||
_JQ16_SHIM = r'''#!/usr/bin/env python3
|
||||
"""jq wrapper reproducing exactly one jq-1.6 behaviour: `-e` over EMPTY input exits 0 (not 4).
|
||||
|
||||
Deliberately narrow. The quirk applies ONLY to a `-e` invocation that reads stdin; it must not
|
||||
touch `jq -n`, which the hook's `decide` uses to build its decision JSON and which legitimately
|
||||
has empty stdin. An earlier, broader version of this shim swallowed those `-n` calls, so the hook
|
||||
emitted nothing and every decision read as "passthrough" — the shim manufacturing the very result
|
||||
the test was trying to disprove.
|
||||
"""
|
||||
import os, subprocess, sys
|
||||
|
||||
argv = sys.argv[1:]
|
||||
uses_null_input = any(a in ("-n", "--null-input") for a in argv)
|
||||
wants_exit_status = any(a in ("-e", "--exit-status") for a in argv)
|
||||
|
||||
data = b"" if uses_null_input else sys.stdin.buffer.read()
|
||||
if wants_exit_status and not uses_null_input and not data.strip():
|
||||
sys.exit(0) # <-- the jq 1.6 quirk under test
|
||||
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
parts = [p for p in os.environ.get("PATH", "").split(os.pathsep) if os.path.abspath(p or ".") != here]
|
||||
for d in parts:
|
||||
cand = os.path.join(d, "jq")
|
||||
if os.path.isfile(cand) and os.access(cand, os.X_OK):
|
||||
sys.exit(subprocess.run([cand, *argv], input=data).returncode)
|
||||
sys.stderr.write("real jq not found\n")
|
||||
sys.exit(127)
|
||||
'''
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hook_jq16(tmp_path):
|
||||
"""Same harness as `hook`, plus a jq shim emulating jq 1.6's empty-input exit status."""
|
||||
bindir = tmp_path / "bin"; bindir.mkdir()
|
||||
(bindir / "curl").write_text(CURL_SHIM); (bindir / "curl").chmod(0o755)
|
||||
(bindir / "jq").write_text(_JQ16_SHIM); (bindir / "jq").chmod(0o755)
|
||||
state = tmp_path / "state"; state.mkdir()
|
||||
|
||||
env = dict(os.environ)
|
||||
env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"
|
||||
env["STUB_DIR"] = str(state)
|
||||
env["STUB_SHA"] = SHA
|
||||
env["ETV_GITEA_TOKEN"] = "stub"
|
||||
env["ETV_GITEA_URL"] = "http://gitea.example"
|
||||
env.pop("ETV_GITEA_BASICAUTH", None)
|
||||
|
||||
class Handle:
|
||||
def set_pages(self, *pages):
|
||||
(state / "pages.json").write_text(json.dumps(list(pages)))
|
||||
|
||||
def exempted(self):
|
||||
payload = {"tool_input": {"method": "merge", "owner": "timothy",
|
||||
"repo": "ersatztv", "pull_number": 42}}
|
||||
r = subprocess.run(["bash", str(HOOK)], input=json.dumps(payload),
|
||||
env=env, capture_output=True, text=True)
|
||||
assert r.returncode == 0, r.stderr
|
||||
return r.stdout.strip() == ""
|
||||
|
||||
return Handle()
|
||||
|
||||
|
||||
def test_jq16_shim_actually_reproduces_the_quirk(hook_jq16, tmp_path):
|
||||
"""Verify the verifier: the shim must really exit 0 on empty and still work otherwise.
|
||||
|
||||
Without this, a shim that silently failed to install would make the test below pass
|
||||
vacuously — reporting the guard safe on jq 1.6 without ever exercising the quirk."""
|
||||
jq = tmp_path / "bin" / "jq"
|
||||
|
||||
# the quirk itself
|
||||
empty = subprocess.run([str(jq), "-e", "type"], input=b"", capture_output=True)
|
||||
assert empty.returncode == 0, "shim did not reproduce jq 1.6's empty-input exit 0"
|
||||
|
||||
# ...and everything the shim must NOT disturb
|
||||
ok = subprocess.run([str(jq), "-r", "length"], input=b"[1,2,3]", capture_output=True)
|
||||
assert ok.returncode == 0 and ok.stdout.strip() == b"3", f"shim broke real jq delegation: {ok}"
|
||||
|
||||
# `jq -n` legitimately has empty stdin and MUST still produce output — the hook's `decide`
|
||||
# builds its decision JSON that way. A shim that swallowed it made every decision look like a
|
||||
# passthrough, i.e. manufactured the exemption the test below is trying to disprove.
|
||||
nullin = subprocess.run([str(jq), "-n", "--arg", "r", "hi", "{a:$r}"], input=b"", capture_output=True)
|
||||
assert nullin.returncode == 0 and b"hi" in nullin.stdout, f"shim broke `jq -n`: {nullin}"
|
||||
|
||||
|
||||
def test_transport_failure_withholds_exemption_even_on_jq16(hook_jq16):
|
||||
"""The #631 regression: a mid-pagination transport failure must withhold the exemption on a
|
||||
host whose jq returns 0 for empty input, not just on jq >= 1.7.
|
||||
|
||||
Page 1 = 50 docs rows (so the path list is non-empty and the exemption would genuinely fire),
|
||||
page 2 = transport failure, page 3 = a legitimate empty page. Pre-fix this returned True."""
|
||||
hook_jq16.set_pages(_rows([f"docs/f{i}.md" for i in range(50)]), "ERROR", [])
|
||||
assert hook_jq16.exempted() is False
|
||||
|
||||
Reference in New Issue
Block a user