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:
@@ -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():
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user