From 3ee0cf7cb942e0cd21041f72697a4e2721f5f7c7 Mon Sep 17 00:00:00 2001 From: Andreas Richardson Date: Sun, 29 Nov 2026 00:28:10 +0000 Subject: [PATCH 1/4] feat(configure): protect release tags with a tag ruleset Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- scripts/configure.sh | 72 +++++++- settings/ruleset-tags.json | 17 ++ tests/test_configure_environments.py | 9 +- tests/test_configure_tag_ruleset.py | 259 +++++++++++++++++++++++++++ 4 files changed, 348 insertions(+), 9 deletions(-) create mode 100644 settings/ruleset-tags.json create mode 100644 tests/test_configure_tag_ruleset.py diff --git a/scripts/configure.sh b/scripts/configure.sh index b2c9437..3f6b569 100755 --- a/scripts/configure.sh +++ b/scripts/configure.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # Applies the repository settings in STANDARDS.md to a GitHub repo: merge -# rules, security features, the default workflow token, the main ruleset, and -# the deployment environments its workflows publish from. +# rules, security features, the default workflow token, the main ruleset, the +# release tag ruleset, and the deployment environments its workflows publish +# from. # # Usage: scripts/configure.sh [--apply|--diff] # @@ -15,8 +16,9 @@ # # Prints what it would change, and changes nothing, unless --apply is given. # --diff compares the repo's live merge and Actions settings with settings/, -# reports classic branch protection, which the ruleset does not replace, and -# checks the branch policy of each publishing environment the workflows name. +# reports classic branch protection, which the ruleset does not replace, +# checks the release tag ruleset in a public repo, and checks the branch policy +# of each publishing environment the workflows name. # Actions may open PRs only in a repo whose workflows run release-please. # Needs an authenticated gh. Written for bash 3.2 (macOS's stock /bin/bash). @@ -46,6 +48,40 @@ drift() { | " \(.key): \($live[.key]) -> \(.value)"' } +# The release tag ruleset's id, found by its name in settings/ruleset-tags.json; +# empty where the repo has none. +tag_ruleset_id() { + local name + name=$(jq -r .name "$settings/ruleset-tags.json") + gh api --paginate "repos/$repo/rulesets" --jq ".[] | select(.name == \"$name\") | .id" +} + +# Where the tag ruleset differs from settings/ruleset-tags.json, as +# `key: live -> tracked` lines, or one line where it is missing. Compared on +# what the file sets: target, enforcement, the tags it covers, bypass actors +# and which rules it has. `|| return` because a failed read inside $(...) +# would otherwise read as a missing ruleset. +tag_ruleset_drift() { + local id name + name=$(jq -r .name "$settings/ruleset-tags.json") + id=$(tag_ruleset_id) || return + if [ -z "$id" ]; then + echo " ruleset $name: missing -> $(jq -r '.conditions.ref_name.include | join(", ")' \ + "$settings/ruleset-tags.json")" + return + fi + gh api "repos/$repo/rulesets/$id" | jq -r --arg name "$name" \ + --slurpfile want "$settings/ruleset-tags.json" ' + def shape: {target, enforcement, + include: (.conditions.ref_name.include // [] | sort), + exclude: (.conditions.ref_name.exclude // [] | sort), + bypass_actors: (.bypass_actors // []), + rules: ([.rules[]?.type] | sort)}; + shape as $live | $want[0] | shape | to_entries[] + | select($live[.key] != .value) + | " ruleset \($name) \(.key): \($live[.key] | tojson) -> \(.value | tojson)"' +} + # A repo running release-please lets Actions open PRs, because release-please # opens its release PR with GITHUB_TOKEN; every other repo keeps it off. # @@ -297,6 +333,12 @@ if [ "$mode" = --diff ]; then if has_classic_protection; then classic=" classic branch protection on $default_branch ($(protection_summary)) -> none, the ruleset replaces it" fi + # Like the main ruleset, only in a public repo: GitHub Free has no + # rulesets for private ones. + tags= + if [ "$visibility" = public ]; then + tags=$(tag_ruleset_drift) + fi environment_drift= for name in npm-release pypi; do if names_environment "$name"; then @@ -306,11 +348,12 @@ if [ "$mode" = --diff ]; then if names_environment npm-prerelease; then check_environment npm-prerelease any fi - if [ -n "$repository$workflow$classic$environment_drift" ]; then + if [ -n "$repository$workflow$classic$tags$environment_drift" ]; then echo "$repo differs from settings/ (live -> tracked):" [ -z "$repository" ] || echo "$repository" [ -z "$workflow" ] || echo "$workflow" [ -z "$classic" ] || echo "$classic" + [ -z "$tags" ] || echo "$tags" [ -z "$environment_drift" ] || printf '%s' "$environment_drift" exit 1 fi @@ -415,6 +458,23 @@ $workflows else run gh api -X POST "repos/$repo/rulesets" --silent --input - <<<"$ruleset" fi + # Release tags: no one may move or delete a v*.*.* tag once it exists. + # Creating one stays open, since release-please creates it with + # GITHUB_TOKEN; floating tags such as v1, and build-* or prerelease/*, + # stay free. .github/admin-bypass is not honoured here: it exists so the + # owner can commit to the default branch, which never needs a release tag + # moved, and a bypass would leave the tags callers pin as movable as + # before. A botched release gets a new version instead. + existing=$(tag_ruleset_id) + echo "protects release tags: no update, force push or deletion of" \ + "$(jq -r '.conditions.ref_name.include | join(", ")' "$settings/ruleset-tags.json")" + if [ -n "$existing" ]; then + run gh api -X PUT "repos/$repo/rulesets/$existing" --silent \ + --input "$settings/ruleset-tags.json" + else + run gh api -X POST "repos/$repo/rulesets" --silent \ + --input "$settings/ruleset-tags.json" + fi if [ "$auto_merge" = true ]; then run gh api -X PATCH "repos/$repo" --silent -F allow_auto_merge=true fi @@ -441,7 +501,7 @@ else # GitHub Free has no rulesets, branch protection, secret scanning or # private vulnerability reporting for private repos. echo "skipped for a private repo on GitHub Free: secret scanning, private" \ - "vulnerability reporting, code scanning, the main ruleset" + "vulnerability reporting, code scanning, the main and release tag rulesets" fi if names_environment npm-release; then diff --git a/settings/ruleset-tags.json b/settings/ruleset-tags.json new file mode 100644 index 0000000..da075cb --- /dev/null +++ b/settings/ruleset-tags.json @@ -0,0 +1,17 @@ +{ + "name": "release tags", + "target": "tag", + "enforcement": "active", + "conditions": { + "ref_name": { + "include": ["refs/tags/v*.*.*"], + "exclude": [] + } + }, + "bypass_actors": [], + "rules": [ + { "type": "deletion" }, + { "type": "non_fast_forward" }, + { "type": "update" } + ] +} diff --git a/tests/test_configure_environments.py b/tests/test_configure_environments.py index 996e5d1..509e2ab 100644 --- a/tests/test_configure_environments.py +++ b/tests/test_configure_environments.py @@ -30,8 +30,8 @@ ) # Answers the read calls configure.sh makes, as a public repo with no gate, no -# classic protection and no ruleset, whose merge and Actions settings match -# settings/. Environments live in $FAKE/state.json; every call is logged. +# classic protection and no main ruleset, whose merge, Actions and release tag +# settings match settings/. Environments live in $FAKE/state.json; every call is logged. FAKE_GH = r"""#!{python} import base64, json, os, subprocess, sys @@ -89,7 +89,9 @@ def out(value): elif method == "GET" and rest == "/actions/permissions/workflow": out(json.load(open({workflow!r}))) elif method == "GET" and rest == "/rulesets": - out([]) + out([{{"id": 1, "name": "release tags"}}]) +elif method == "GET" and rest == "/rulesets/1": + out(dict(json.load(open({tags!r})), id=1)) elif parts[:1] == ["environments"]: name = parts[1] env = envs.get(name) @@ -146,6 +148,7 @@ def fake(tmp_path): python=sys.executable, repository=str(SETTINGS / "repository.json"), workflow=str(SETTINGS / "actions-workflow.json"), + tags=str(SETTINGS / "ruleset-tags.json"), ) ) gh.chmod(0o755) diff --git a/tests/test_configure_tag_ruleset.py b/tests/test_configure_tag_ruleset.py new file mode 100644 index 0000000..25300b7 --- /dev/null +++ b/tests/test_configure_tag_ruleset.py @@ -0,0 +1,259 @@ +"""configure.sh creates, updates and checks the release tag ruleset. + +Run against a fake gh that keeps the repo's rulesets in a JSON file, so an +--apply is visible to the --diff that follows it. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +SETTINGS = ROOT / "settings" +TAGS = json.loads((SETTINGS / "ruleset-tags.json").read_text()) + +# A repo with no workflows, no .github/admin-bypass and no classic protection, +# whose merge and Actions settings match settings/. Its visibility and +# rulesets live in $FAKE/state.json; every call is logged. +FAKE_GH = r"""#!{python} +import json, os, subprocess, sys + +fake = os.environ["FAKE"] +args = sys.argv[2:] +with open(os.path.join(fake, "calls"), "a") as log: + log.write(" ".join(sys.argv[1:]) + "\n") +method, jq, endpoint, body_from = "GET", None, None, None +i = 0 +while i < len(args): + a = args[i] + if a == "-X": + method = args[i + 1]; i += 1 + elif a == "--jq": + jq = args[i + 1]; i += 1 + elif a in ("--input", "-f", "-F"): + if a == "--input": + body_from = args[i + 1] + i += 1 + elif not a.startswith("-") and endpoint is None: + endpoint = a + i += 1 +state_path = os.path.join(fake, "state.json") +state = json.load(open(state_path)) +rulesets = state["rulesets"] +base = "repos/example/repo" + +def not_found(): + print('{{"message":"Not Found","status":"404"}}') + sys.stderr.write("gh: Not Found (HTTP 404)\n") + sys.exit(1) + +def body(): + return json.load(sys.stdin if body_from == "-" else open(body_from)) + +def save(): + json.dump(state, open(state_path, "w")) + +def out(value): + text = json.dumps(value) + if jq is not None: + text = subprocess.run(["jq", "-r", jq], input=text, text=True, + capture_output=True, check=True).stdout + sys.stdout.write(text) + else: + print(text) + +rest = endpoint[len(base):] if endpoint.startswith(base) else None +parts = rest.strip("/").split("/") if rest else [] +if method == "GET" and rest == "": + repo = json.load(open({repository!r})) + repo.update(visibility=state["visibility"], default_branch="main", allow_auto_merge=False) + out(repo) +elif method == "GET" and rest == "/actions/permissions/workflow": + out(json.load(open({workflow!r}))) +elif parts[:1] == ["rulesets"]: + if os.path.exists(os.path.join(fake, "rulesets-fail")): + sys.stderr.write("gh: Server Error (HTTP 500)\n") + sys.exit(1) + if len(parts) == 1 and method == "GET": + out([{{"id": r["id"], "name": r["name"]}} for r in rulesets]) + elif len(parts) == 1 and method == "POST": + new = body() + new["id"] = max([r["id"] for r in rulesets] + [0]) + 1 + rulesets.append(new) + save() + elif len(parts) == 2: + match = [r for r in rulesets if str(r["id"]) == parts[1]] + if not match: + not_found() + if method == "GET": + out(match[0]) + elif method == "PUT": + match[0].clear() + match[0].update(body(), id=int(parts[1])) + save() + else: + sys.exit(99) + else: + sys.exit(99) +elif method == "GET": + not_found() +""" + + +def live(**changes) -> dict: + """The tracked ruleset as GitHub returns it, with the given keys changed.""" + ruleset = json.loads(json.dumps(TAGS)) + ruleset.update(id=7, source="example/repo", **changes) + return ruleset + + +@pytest.fixture +def fake(tmp_path): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + gh = bin_dir / "gh" + gh.write_text( + FAKE_GH.format( + python=sys.executable, + repository=str(SETTINGS / "repository.json"), + workflow=str(SETTINGS / "actions-workflow.json"), + ) + ) + gh.chmod(0o755) + (tmp_path / "calls").touch() + return tmp_path + + +def configure(fake: Path, rulesets: list | None, *args: str, visibility: str = "public"): + if rulesets is not None: + (fake / "state.json").write_text(json.dumps({"visibility": visibility, "rulesets": rulesets})) + (fake / "calls").write_text("") + jq_dir = os.path.dirname(shutil.which("jq") or "/usr/bin/jq") + result = subprocess.run( + ["/bin/bash", str(ROOT / "scripts/configure.sh"), "example/repo", *args], + env={"PATH": f"{fake / 'bin'}:{jq_dir}:/usr/bin:/bin", "FAKE": str(fake)}, + capture_output=True, + text=True, + stdin=subprocess.DEVNULL, + ) + return result, (fake / "calls").read_text().splitlines() + + +def tag_rulesets(fake: Path) -> list[dict]: + state = json.loads((fake / "state.json").read_text()) + return [r for r in state["rulesets"] if r["name"] == "release tags"] + + +def test_tracked_ruleset_guards_only_release_tags(): + assert TAGS["target"] == "tag" + assert TAGS["conditions"]["ref_name"] == {"include": ["refs/tags/v*.*.*"], "exclude": []} + assert sorted(r["type"] for r in TAGS["rules"]) == ["deletion", "non_fast_forward", "update"] + assert TAGS["bypass_actors"] == [] + + +def test_apply_creates_it_when_missing_then_diff_is_clean(fake): + result, calls = configure(fake, [], "--diff") + assert result.returncode == 1, result.stdout + result.stderr + assert " ruleset release tags: missing -> refs/tags/v*.*.*\n" in result.stdout + result, calls = configure(fake, [], "--apply") + assert result.returncode == 0, result.stderr + assert f"api -X POST repos/example/repo/rulesets --silent --input {SETTINGS / 'ruleset-tags.json'}" in calls + created = tag_rulesets(fake) + assert len(created) == 1 + assert created[0]["rules"] == TAGS["rules"] + result, _ = configure(fake, None, "--diff") + assert result.returncode == 0, result.stdout + result.stderr + assert "matches settings/" in result.stdout + + +def test_apply_updates_the_one_it_finds_by_name(fake): + main = {"id": 3, "name": "main", "target": "branch", "rules": []} + drifted = live(rules=[{"type": "deletion"}]) + result, calls = configure(fake, [main, drifted], "--apply") + assert result.returncode == 0, result.stderr + assert f"api -X PUT repos/example/repo/rulesets/7 --silent --input {SETTINGS / 'ruleset-tags.json'}" in calls + # The main ruleset is updated in place too, but never with the tag file. + assert not any(c.startswith("api -X PUT repos/example/repo/rulesets/3") and "ruleset-tags" in c for c in calls) + assert not any(c.startswith("api -X POST repos/example/repo/rulesets") and "ruleset-tags" in c for c in calls) + updated = tag_rulesets(fake) + assert len(updated) == 1 and updated[0]["id"] == 7 + assert updated[0]["rules"] == TAGS["rules"] + + +def test_diff_is_clean_when_it_matches(fake): + # GitHub adds keys of its own, and may list the rules in another order. + ruleset = live(rules=list(reversed(TAGS["rules"])), created_at="2026-01-01T00:00:00Z") + result, _ = configure(fake, [ruleset], "--diff") + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize( + ("changes", "line"), + [ + ( + {"rules": [{"type": "deletion"}, {"type": "non_fast_forward"}]}, + 'rules: ["deletion","non_fast_forward"] -> ["deletion","non_fast_forward","update"]', + ), + ( + {"conditions": {"ref_name": {"include": ["refs/tags/v*"], "exclude": []}}}, + 'include: ["refs/tags/v*"] -> ["refs/tags/v*.*.*"]', + ), + ({"enforcement": "evaluate"}, 'enforcement: "evaluate" -> "active"'), + ( + {"bypass_actors": [{"actor_id": 5, "actor_type": "RepositoryRole", "bypass_mode": "always"}]}, + 'bypass_actors: [{"actor_id":5,"actor_type":"RepositoryRole","bypass_mode":"always"}] -> []', + ), + ], +) +def test_diff_reports_drift(fake, changes, line): + result, _ = configure(fake, [live(**changes)], "--diff") + assert result.returncode == 1, result.stdout + result.stderr + assert f" ruleset release tags {line}\n" in result.stdout + + +def test_dry_run_says_what_it_would_run_and_changes_nothing(fake): + result, calls = configure(fake, []) + assert result.returncode == 0, result.stderr + assert ( + f"would run: gh api -X POST repos/example/repo/rulesets --silent --input {SETTINGS / 'ruleset-tags.json'}" + ) in result.stdout + assert not any(c.startswith("api -X") for c in calls) + assert tag_rulesets(fake) == [] + + +def test_a_failed_read_is_not_a_missing_ruleset(fake): + (fake / "rulesets-fail").touch() + result, _ = configure(fake, [], "--diff") + assert result.returncode != 0 + assert "missing" not in result.stdout + + +def test_admin_bypass_does_not_reach_the_tag_ruleset(fake): + # The fake has no .github/admin-bypass, so stand one in by answering it. + script = (fake / "bin/gh").read_text() + (fake / "bin/gh").write_text( + script.replace( + 'elif method == "GET":\n not_found()', + 'elif rest == "/contents/.github/admin-bypass":\n out({})\nelif method == "GET":\n not_found()', + ) + ) + result, _ = configure(fake, [], "--apply") + assert result.returncode == 0, result.stderr + assert "admins may bypass the ruleset" in result.stdout + assert tag_rulesets(fake)[0]["bypass_actors"] == [] + + +def test_private_repo_gets_none(fake): + result, calls = configure(fake, [], "--apply", visibility="private") + assert result.returncode == 0, result.stderr + assert not any("rulesets" in c for c in calls) + result, calls = configure(fake, [], "--diff", visibility="private") + assert result.returncode == 0, result.stdout + result.stderr + assert not any("rulesets" in c for c in calls) From 5949ea31f9e90c2fea847cdc2a4122c4a08759c1 Mon Sep 17 00:00:00 2001 From: Andreas Richardson Date: Sun, 29 Nov 2026 00:28:10 +0000 Subject: [PATCH 2/4] docs(standards): list the release tag ruleset and why Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- AGENTS.md | 8 ++++---- README.md | 5 +++-- STANDARDS.md | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1883286..020585a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,10 +36,10 @@ scripts/configure.sh [--apply|--diff] # dry run by default `conventions.yml` fetches it from this repo at the caller's pinned commit (`job.workflow_sha`) rather than copying it into each repo. - `settings/` holds the repository settings as data: merge types and the Actions - token (`repository.json`, `actions-workflow.json`), security features, and the - branch ruleset. `configure.sh` sends them, requiring each gate only where the - repo has the workflow that reports it (`scripts/ruleset.jq`); `--diff` reports - drift from them. + token (`repository.json`, `actions-workflow.json`), security features, the + branch ruleset and the release tag ruleset. `configure.sh` sends them, + requiring each gate only where the repo has the workflow that reports it + (`scripts/ruleset.jq`); `--diff` reports drift from them. ## Conventions diff --git a/README.md b/README.md index c9fdaa0..54c83ff 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,9 @@ counts. - **A template**: a shared core (issue and PR templates, Dependabot, `SECURITY.md`, `AGENTS.md`, lint settings, caller workflows) plus an overlay for Node, Python or TeX. -- **Repository settings** as code: squash only merges, security features and a - branch ruleset that requires the CI gates. +- **Repository settings** as code: squash only merges, security features, a + branch ruleset that requires the CI gates, and a tag ruleset that keeps + release tags from moving. ## Usage diff --git a/STANDARDS.md b/STANDARDS.md index 14429c1..c032393 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -344,6 +344,7 @@ workflow can open or approve a PR it was not built to. | Private vulnerability reporting | On (public repos) | | CodeQL default setup | On (public repos) | | Ruleset `main` | See below (public repos) | +| Ruleset `release tags` | See below (public repos) | The ruleset (`settings/ruleset-main.json`) blocks deletion and force pushes, requires linear history, a PR with resolved conversations and squash merge, and @@ -374,6 +375,23 @@ another PR lands, and in a solo repo two PRs rarely collide in a way the gates would catch. CI on `main` after the merge still does. "Update branch" stays available for when it is wanted. +**Release tags cannot move.** Callers pin the reusable workflows to an exact tag +such as `v1.1.0`, and `conventions.yml` fetches its checker at that commit, so a +moved or deleted tag would change what every caller runs. The `release tags` +ruleset (`settings/ruleset-tags.json`) blocks updating, force pushing and +deleting any tag matching `v*.*.*`. Creating one stays open, since +release-please creates it with `GITHUB_TOKEN`. The pattern is not `v*`: +atdr/latex-build moves its floating `v1` tag on every release, and `build-*` and +`prerelease/*` tags must stay free. It has no bypass actors, even in a repo that +commits `.github/admin-bypass`: committing to the default branch never needs a +release tag moved, and a botched release gets a new version instead. + +It is a ruleset rather than GitHub's immutable releases, which lock a release's +assets once it is published. Some repos upload to an existing release +(latex-build with `gh release upload --clobber`, capsule-caffeine from its +release workflows), and the badge would serve nobody: no third party pins these +tags, and the npm and PyPI packages already carry registry provenance. + **The ruleset replaces classic branch protection.** GitHub enforces both, so protection left over from before a repo adopted the gates still requires the check names its old workflows reported, and blocks every merge once those checks From 0bc171cbd9314bbc39cf469f451034d06b799427 Mon Sep 17 00:00:00 2001 From: Andreas Richardson Date: Sun, 29 Nov 2026 00:36:32 +0000 Subject: [PATCH 3/4] fix(configure): match only repo-owned rulesets by name Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- scripts/configure.sh | 8 ++++++-- tests/test_configure_environments.py | 2 +- tests/test_configure_tag_ruleset.py | 24 +++++++++++++++++++++--- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/scripts/configure.sh b/scripts/configure.sh index 3f6b569..d15163c 100755 --- a/scripts/configure.sh +++ b/scripts/configure.sh @@ -53,7 +53,10 @@ drift() { tag_ruleset_id() { local name name=$(jq -r .name "$settings/ruleset-tags.json") - gh api --paginate "repos/$repo/rulesets" --jq ".[] | select(.name == \"$name\") | .id" + # includes_parents=false: an organization ruleset of the same name is + # listed too by default, and can't be updated through the repo. + gh api --paginate "repos/$repo/rulesets?includes_parents=false" \ + --jq ".[] | select(.name == \"$name\") | .id" } # Where the tag ruleset differs from settings/ruleset-tags.json, as @@ -452,7 +455,8 @@ $workflows if [ "$copilot_review" = true ]; then echo "requests a Copilot review on every push: the repo has copilot-auto-merge.yml" fi - existing=$(gh api "repos/$repo/rulesets" --jq '.[] | select(.name == "main") | .id') + existing=$(gh api --paginate "repos/$repo/rulesets?includes_parents=false" \ + --jq '.[] | select(.name == "main") | .id') if [ -n "$existing" ]; then run gh api -X PUT "repos/$repo/rulesets/$existing" --silent --input - <<<"$ruleset" else diff --git a/tests/test_configure_environments.py b/tests/test_configure_environments.py index 509e2ab..25b69c9 100644 --- a/tests/test_configure_environments.py +++ b/tests/test_configure_environments.py @@ -88,7 +88,7 @@ def out(value): out({{"content": base64.b64encode(open(os.path.join(fake, "publish.yml"), "rb").read()).decode()}}) elif method == "GET" and rest == "/actions/permissions/workflow": out(json.load(open({workflow!r}))) -elif method == "GET" and rest == "/rulesets": +elif method == "GET" and rest == "/rulesets?includes_parents=false": out([{{"id": 1, "name": "release tags"}}]) elif method == "GET" and rest == "/rulesets/1": out(dict(json.load(open({tags!r})), id=1)) diff --git a/tests/test_configure_tag_ruleset.py b/tests/test_configure_tag_ruleset.py index 25300b7..a8df550 100644 --- a/tests/test_configure_tag_ruleset.py +++ b/tests/test_configure_tag_ruleset.py @@ -70,6 +70,8 @@ def out(value): print(text) rest = endpoint[len(base):] if endpoint.startswith(base) else None +rest, _, query = (rest or "").partition("?") +rest = rest if endpoint.startswith(base) else None parts = rest.strip("/").split("/") if rest else [] if method == "GET" and rest == "": repo = json.load(open({repository!r})) @@ -82,7 +84,9 @@ def out(value): sys.stderr.write("gh: Server Error (HTTP 500)\n") sys.exit(1) if len(parts) == 1 and method == "GET": - out([{{"id": r["id"], "name": r["name"]}} for r in rulesets]) + # GitHub lists inherited organization rulesets too, unless asked not to. + parents = [] if query == "includes_parents=false" else state.get("parents", []) + out([{{"id": r["id"], "name": r["name"]}} for r in rulesets + parents]) elif len(parts) == 1 and method == "POST": new = body() new["id"] = max([r["id"] for r in rulesets] + [0]) + 1 @@ -131,9 +135,10 @@ def fake(tmp_path): return tmp_path -def configure(fake: Path, rulesets: list | None, *args: str, visibility: str = "public"): +def configure(fake: Path, rulesets: list | None, *args: str, visibility: str = "public", parents: list = ()): if rulesets is not None: - (fake / "state.json").write_text(json.dumps({"visibility": visibility, "rulesets": rulesets})) + state = {"visibility": visibility, "rulesets": rulesets, "parents": list(parents)} + (fake / "state.json").write_text(json.dumps(state)) (fake / "calls").write_text("") jq_dir = os.path.dirname(shutil.which("jq") or "/usr/bin/jq") result = subprocess.run( @@ -257,3 +262,16 @@ def test_private_repo_gets_none(fake): result, calls = configure(fake, [], "--diff", visibility="private") assert result.returncode == 0, result.stdout + result.stderr assert not any("rulesets" in c for c in calls) + + +def test_an_inherited_ruleset_of_the_same_name_is_left_alone(fake): + org = {"id": 900, "name": "release tags"} + result, calls = configure(fake, [], "--apply", parents=[org]) + assert result.returncode == 0, result.stderr + assert not any("rulesets/900" in c for c in calls) + assert f"api -X POST repos/example/repo/rulesets --silent --input {SETTINGS / 'ruleset-tags.json'}" in calls + assert len(tag_rulesets(fake)) == 1 + + result, calls = configure(fake, [live()], "--diff", parents=[org]) + assert result.returncode == 0, result.stderr + assert "release tags" not in result.stdout From ff23547e798ffaa10a03ae5760c93b28c9ca48a2 Mon Sep 17 00:00:00 2001 From: Andreas Richardson Date: Sun, 29 Nov 2026 00:39:50 +0000 Subject: [PATCH 4/4] fix(configure): report unreadable bypass actors as drift Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- scripts/configure.sh | 7 +++++-- tests/test_configure_tag_ruleset.py | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/configure.sh b/scripts/configure.sh index d15163c..a76301a 100755 --- a/scripts/configure.sh +++ b/scripts/configure.sh @@ -62,7 +62,9 @@ tag_ruleset_id() { # Where the tag ruleset differs from settings/ruleset-tags.json, as # `key: live -> tracked` lines, or one line where it is missing. Compared on # what the file sets: target, enforcement, the tags it covers, bypass actors -# and which rules it has. `|| return` because a failed read inside $(...) +# and which rules it has. GitHub leaves bypass_actors out for a caller who +# can't edit the ruleset, so an absent list is reported as unreadable, never +# as the empty one tracked. `|| return` because a failed read inside $(...) # would otherwise read as a missing ruleset. tag_ruleset_drift() { local id name @@ -78,7 +80,8 @@ tag_ruleset_drift() { def shape: {target, enforcement, include: (.conditions.ref_name.include // [] | sort), exclude: (.conditions.ref_name.exclude // [] | sort), - bypass_actors: (.bypass_actors // []), + bypass_actors: (if has("bypass_actors") then .bypass_actors + else "unreadable without admin access" end), rules: ([.rules[]?.type] | sort)}; shape as $live | $want[0] | shape | to_entries[] | select($live[.key] != .value) diff --git a/tests/test_configure_tag_ruleset.py b/tests/test_configure_tag_ruleset.py index a8df550..9999f33 100644 --- a/tests/test_configure_tag_ruleset.py +++ b/tests/test_configure_tag_ruleset.py @@ -223,6 +223,15 @@ def test_diff_reports_drift(fake, changes, line): assert f" ruleset release tags {line}\n" in result.stdout +def test_diff_does_not_read_absent_bypass_actors_as_none(fake): + # GitHub omits the field for a caller who can't edit the ruleset. + ruleset = live() + del ruleset["bypass_actors"] + result, _ = configure(fake, [ruleset], "--diff") + assert result.returncode == 1, result.stdout + result.stderr + assert ' ruleset release tags bypass_actors: "unreadable without admin access" -> []\n' in result.stdout + + def test_dry_run_says_what_it_would_run_and_changes_nothing(fake): result, calls = configure(fake, []) assert result.returncode == 0, result.stderr