From 523f0b4ab376d2c28a91651b21f95a736a6443df Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 28 Sep 2026 00:22:34 -0700 Subject: [PATCH] Validate the Rulesets Response Before ruleset_id() Reads It (#1971) ## Summary `repo-config/configure.sh`'s `ruleset_id()` per_page guard fails open on any non-array 2xx response from the rulesets API, not only the CR-mangled case #1880/#1972 fixed, because the guard's own comparison failure inside its `$(...)` subshell never reaches `set -e` (no `inherit_errexit`). ## The defect On a non-array response, `jqr 'length'` prints nothing, so the `[ "" -eq 100 ]` guard fails silently rather than tripping, and the following `ids=` extraction likewise falls through empty rather than aborting. `ruleset_id` returns 0, which both call sites read as "not found": the apply site would create a duplicate ruleset by name, and the check site would misreport "not found" instead of aborting. ## Fix Validate `$out` is a JSON array (`jq_has 'type == "array"' <<<"$out"`, matching the `entries` guard's own pattern) before either the per_page guard or the `ids=` extraction reads it, aborting with a "could not read live ruleset state" message on failure. ## Verification - New `tests/test_configure_ruleset_id.py` lifts `ruleset_id()`'s own lines and exercises it through a stubbed `gh`, invoked the way both real call sites invoke it (`id="$(ruleset_id ...)"`), which is what exposes the subshell-errexit defect. - Confirmed by reverting the fix: every non-array-response case then returns exit 0 with empty stdout (the "not found" misread), and the pre-existing per_page-cap, gh-failure, and duplicate-name cases stay passing throughout. - `shellcheck` and `shfmt -d` clean on `repo-config/configure.sh`. - `python3 -m unittest discover -s tests` (1777 tests), `python3 scripts/repo_gate.py`, and `python3 spec/validate.py` all pass. Closes on promotion: #1971 Co-Authored-By: Claude Sonnet 5 --- repo-config/configure.sh | 7 ++ tests/test_configure_ruleset_id.py | 146 +++++++++++++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100755 tests/test_configure_ruleset_id.py diff --git a/repo-config/configure.sh b/repo-config/configure.sh index eaac30342..c51976527 100755 --- a/repo-config/configure.sh +++ b/repo-config/configure.sh @@ -139,6 +139,13 @@ ruleset_id() { echo "Failed to list rulesets for $repo (check auth and repo access)." >&2 return 1 fi + # A non-array 2xx body (truncated or proxy-mangled) must not reach the length guard or the ids= extraction below. + # Depending on the shape, length or the .[] extraction below either errors or mis-reads it, inside this $(...) subshell where errexit does not propagate. + # Both call sites would then misread the unreadable response as "not found" instead of aborting. + if ! jq_has 'type == "array"' <<<"$out"; then + echo "Failed for $repo: could not read live ruleset state (the response was not a JSON array)." >&2 + return 1 + fi # Fail loud rather than silently narrow, because a full page means the single-fetch assumption no longer holds. # A missed lookup would make apply create a duplicate ruleset by name. # Abort so the caller stops, since it treats a non-zero return as "stop" and never as "not found". diff --git a/tests/test_configure_ruleset_id.py b/tests/test_configure_ruleset_id.py new file mode 100755 index 000000000..7b50416ac --- /dev/null +++ b/tests/test_configure_ruleset_id.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Exercise repo-config/configure.sh's ruleset_id() by running its own lines. + +The shell is lifted out of the file rather than restated here, so an edit that removes the +behavior fails these tests instead of leaving a reimplementation to agree with itself. Each +harness lifts the whole function under test and stubs only `gh`, the boundary it calls out to. + +Every case runs offline: `gh` is a shell function the harness defines, which is what lets a +2xx-but-unreadable response be exercised at all without firing a real call to GitHub. +""" + +from __future__ import annotations + +import json +import re +import shlex +import shutil +import subprocess +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CONFIGURE = ROOT / "repo-config" / "configure.sh" + + +def lift(pattern: str) -> str: + """The one region of configure.sh matching `pattern`, or a failure naming what was missing.""" + text = CONFIGURE.read_text(encoding="utf-8") + found = re.findall(pattern, text, re.MULTILINE | re.DOTALL) + if len(found) != 1: + raise AssertionError( + f"expected one match in {CONFIGURE.name} for {pattern!r}, found {len(found)}" + ) + return found[0] + + +def require(*tools: str) -> str: + """The bash path, skipping instead of failing where a tool the harness shells out to is absent.""" + for tool in tools: + if shutil.which(tool) is None: + raise unittest.SkipTest(f"no {tool} on PATH, so the script's own lines cannot be run") + return str(shutil.which("bash")) + + +def run_bash(script: str, *tools: str) -> subprocess.CompletedProcess[str]: + """The script under the same shell options configure.sh sets, with a bounded wait. + + The options are lifted rather than typed, because a harness running without them is blind to + exactly the error handling the lines under test rely on. + """ + bash = require("bash", *tools) + options = lift(r"^(set -[A-Za-z]+ [a-z]+)$") + return subprocess.run( + [bash, "-c", f"{options}\n{script}"], + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=False, + ) + + +JQR = lift(r"^(jqr\(\) \{ jq -r .*?\}\n)") +JQ_HAS = lift(r"^(jq_has\(\) \{ jq -e .*?\}\n)") +RULESET_ID = lift(r"^(ruleset_id\(\) \{\n.*?\n\}\n)") + + +def gh_stub(stdout: str, status: int = 0) -> str: + """A `gh` that answers with one canned document.""" + return f"gh() {{\n printf '%s' {json.dumps(stdout)}\n return {status}\n}}\n" + + +class RulesetIdCase(unittest.TestCase): + """ruleset_id() maps a name to an id, and aborts rather than reading "not found" on a + response it cannot trust.""" + + def lookup( + self, response: str, status: int = 0, name: str = "fixture" + ) -> subprocess.CompletedProcess[str]: + # Invoked the way both real call sites invoke it, `id="$(ruleset_id ...)"`, rather than as a bare top-level statement. + # The defect this guards is specific to running inside that command-substitution subshell. + # `set -e` does not apply there without `shopt -s inherit_errexit`, which this script does not set. + # So an unguarded failure inside the function falls through to the next line instead of aborting it. + script = ( + f"repo=ptr727/fixture\n{JQ_HAS}{JQR}{gh_stub(response, status)}{RULESET_ID}" + f'id="$(ruleset_id {shlex.quote(name)})"\nstatus=$?\nprintf \'%s\\n\' "$id"\nexit "$status"\n' + ) + return run_bash(script, "jq", "sed", "grep") + + def test_a_matching_name_resolves_to_its_id(self) -> None: + result = self.lookup(json.dumps([{"name": "fixture", "id": 42}])) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), "42") + + def test_no_match_returns_empty_without_failing(self) -> None: + result = self.lookup(json.dumps([{"name": "other", "id": 1}])) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), "") + + def test_a_non_array_2xx_body_aborts_rather_than_reading_as_not_found(self) -> None: + """The defect this guards: an unreadable-but-0-status response used to fall through to + the empty-ids case (returncode 0, no output), reading as "not found" instead of aborting.""" + for label, response in ( + ("an object", json.dumps({"message": "not found"})), + ("a scalar", "null"), + ("not JSON at all", "not json"), + ("truncated JSON", '[{"name": "fixture"'), + ): + with self.subTest(label=label): + result = self.lookup(response) + self.assertNotEqual( + result.returncode, + 0, + f"ruleset_id must abort on {label}, not read it as an empty match " + f"(stdout={result.stdout!r})", + ) + self.assertIn("could not read live ruleset state", result.stderr) + + def test_a_gh_api_failure_still_aborts(self) -> None: + """The pre-existing guard this fix sits beside: an outright gh failure already aborts.""" + result = self.lookup("", status=1) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Failed to list rulesets", result.stderr) + + def test_the_per_page_cap_still_aborts(self) -> None: + """The guard this fix sits ahead of: 100 rulesets (a valid array) still trips the cap.""" + result = self.lookup(json.dumps([{"name": f"r{i}", "id": i} for i in range(100)])) + self.assertNotEqual(result.returncode, 0) + self.assertIn("the per_page cap", result.stderr) + + def test_a_duplicate_name_uses_the_first_and_warns(self) -> None: + result = self.lookup( + json.dumps( + [ + {"name": "fixture", "id": 1}, + {"name": "fixture", "id": 2}, + ] + ) + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), "1") + self.assertIn("Using the first", result.stderr) + + +if __name__ == "__main__": + unittest.main()