From bfab2b3b15dc197d913ca73e130842df9c565f0a Mon Sep 17 00:00:00 2001 From: Andreas Richardson Date: Wed, 18 Nov 2026 10:59:40 +0000 Subject: [PATCH 1/4] fix(configure): check and enforce the publishing environments' branch policy --diff now checks each publishing environment the workflows name: npm-release and pypi must exist and allow exactly branch:main, and npm-prerelease must exist. --apply deletes any other branch policy on the restricted environments and names each one it removes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- scripts/configure.sh | 176 +++++++++++++----- tests/test_configure_environments.py | 260 +++++++++++++++++++++++++++ 2 files changed, 388 insertions(+), 48 deletions(-) create mode 100644 tests/test_configure_environments.py diff --git a/scripts/configure.sh b/scripts/configure.sh index 25681c6..b9619c7 100755 --- a/scripts/configure.sh +++ b/scripts/configure.sh @@ -15,7 +15,8 @@ # # Prints what it would change, and changes nothing, unless --apply is given. # --diff compares the repo's live merge and Actions settings with settings/, -# and reports classic branch protection, which the ruleset does not replace. +# reports classic branch protection, which the ruleset does not replace, 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). @@ -55,7 +56,10 @@ workflow_settings=$(mktemp) repository_settings=$(mktemp) api_error=$(mktemp) protection=$(mktemp) -trap 'rm -f "$workflow_settings" "$repository_settings" "$api_error" "$protection"' EXIT +environment_file=$(mktemp) +policies_file=$(mktemp) +trap 'rm -f "$workflow_settings" "$repository_settings" "$api_error" "$protection" \ + "$environment_file" "$policies_file"' EXIT # Read first: a private repo gets no ruleset, so its gates are never used. visibility=$(gh api "repos/$repo" --jq .visibility) # Only a 404 means the repo has no workflows folder. gh prints that error body @@ -199,6 +203,88 @@ protection_summary() { | if length == 0 then "no status checks" else "requires " + join(", ") end' "$protection" } +# Publishing environments. npm-release and pypi are limited to main, with +# `main` their only branch policy: the workflows add no check of their own, so +# that policy alone stops a workflow on another branch minting the publishing +# token. npm-prerelease is dispatched by hand from any branch a beta is built +# from, so it is left open. Only the environments the repo's workflows name: a +# repo that publishes nowhere gets none. +# +# Every environment the workflows' jobs name, in any form a job can declare it +# (see the awk program). Matched as whole lines below, so npm-release never +# matches npm-prerelease. +environments=$(printf '%s\n' "${all_workflows:-}" | awk -f "$here/scripts/workflow-environments.awk") +names_environment() { + case " +$environments +" in + *" +$1 +"*) return 0 ;; + esac + return 1 +} + +# The environment, left in $environment_file. Returns 1 where it does not +# exist; any other error aborts. Called directly, never in $(...), so that the +# exit stops the script. +read_environment() { + if gh api "repos/$repo/environments/$1" >"$environment_file" 2>"$api_error"; then + return 0 + fi + if grep 'HTTP 404' "$api_error" >/dev/null; then + return 1 + fi + echo "could not read $repo's $1 environment:" >&2 + cat "$api_error" >&2 + exit 1 +} + +# The environment's branch policies as ` :` lines, left in +# $policies_file. GitHub answers 404 where the environment is missing or not +# limited to custom policies, and either way it has none; any other error +# aborts. Called directly, as above. +read_branch_policies() { + if gh api --paginate "repos/$repo/environments/$1/deployment-branch-policies" \ + --jq '.branch_policies[] | "\(.id) \(.type):\(.name)"' >"$policies_file" 2>"$api_error"; then + return 0 + fi + : >"$policies_file" + if grep 'HTTP 404' "$api_error" >/dev/null; then + return 0 + fi + echo "could not read $repo's $1 branch policies:" >&2 + cat "$api_error" >&2 + exit 1 +} + +# Appends a line to $environment_drift where the environment is not what it +# should be: for main, present and limited to exactly `branch:main`; for any, +# merely present. +check_environment() { + local name=$1 limit=$2 live want=branch:main + [ "$limit" = main ] || want="any branch" + if ! read_environment "$name"; then + live=missing + elif [ "$limit" != main ]; then + return 0 + else + live=$(jq -r '.deployment_branch_policy + | if . == null then "any branch" + elif .protected_branches then "protected branches" + elif .custom_branch_policies then "custom" + else "any branch" end' "$environment_file") + if [ "$live" = custom ]; then + read_branch_policies "$name" + live=$(cut -d' ' -f2- "$policies_file" | sort | paste -sd, - | sed 's/,/, /g') + live=${live:-no branch} + fi + fi + [ "$live" = "$want" ] || + environment_drift="${environment_drift} environment $name: $live -> $want +" +} + if [ "$mode" = --diff ]; then # Command substitution drops trailing newlines, so print each part rather # than concatenating them. @@ -208,11 +294,21 @@ if [ "$mode" = --diff ]; then if has_classic_protection; then classic=" classic branch protection on $default_branch ($(protection_summary)) -> none, the ruleset replaces it" fi - if [ -n "$repository$workflow$classic" ]; then + environment_drift= + for name in npm-release pypi; do + if names_environment "$name"; then + check_environment "$name" main + fi + done + if names_environment npm-prerelease; then + check_environment npm-prerelease any + fi + if [ -n "$repository$workflow$classic$environment_drift" ]; then echo "$repo differs from settings/ (live -> tracked):" [ -z "$repository" ] || echo "$repository" [ -z "$workflow" ] || echo "$workflow" [ -z "$classic" ] || echo "$classic" + [ -z "$environment_drift" ] || printf '%s' "$environment_drift" exit 1 fi echo "$repo matches settings/ (release-please: $uses_release_please)" @@ -229,6 +325,35 @@ run() { fi } +# Sends a publishing environment. For main: limited to custom branch policies, +# with `main` the only one. Any other, added in the UI say, is deleted, since +# its branches could otherwise mint the publishing token. +environment() { + local name=$1 limit=$2 id rule has_main=false verb=removes + if [ "$limit" != main ]; then + run gh api -X PUT "repos/$repo/environments/$name" --silent + return + fi + run gh api -X PUT "repos/$repo/environments/$name" --silent --input - <<'JSON' +{"deployment_branch_policy": {"protected_branches": false, "custom_branch_policies": true}} +JSON + [ "$mode" = --apply ] || verb="would remove" + read_branch_policies "$name" + # Read on fd 3, so that nothing run in the loop can consume the list. + while read -r id rule <&3; do + if [ "$rule" = branch:main ]; then + has_main=true + continue + fi + echo "$name: $verb branch policy $rule (only main may publish)" + run gh api -X DELETE "repos/$repo/environments/$name/deployment-branch-policies/$id" --silent + done 3<"$policies_file" + if [ "$has_main" = false ]; then + run gh api -X POST "repos/$repo/environments/$name/deployment-branch-policies" \ + --silent -f name=main -f type=branch + fi +} + echo "$repo is $visibility" # Auto-merge is switched on only after the ruleset that gates it is in place @@ -314,57 +439,12 @@ else "vulnerability reporting, code scanning, the main ruleset" fi -# Publishing environments, limited to main so a workflow on another branch -# cannot mint the publishing token. Only the ones the repo's workflows name: -# a repo that publishes nowhere gets none. -environment() { - local name=$1 limit=$2 - if [ "$limit" = main ]; then - run gh api -X PUT "repos/$repo/environments/$name" --silent --input - <<'JSON' -{"deployment_branch_policy": {"protected_branches": false, "custom_branch_policies": true}} -JSON - # Captured, then matched: no grep -q at the end of a pipeline, which - # under pipefail can read a match as a miss. - policies=$(gh api "repos/$repo/environments/$name/deployment-branch-policies" \ - --jq '.branch_policies[].name' 2>/dev/null) || policies= - case " -$policies -" in - *" -main -"*) ;; - *) - run gh api -X POST "repos/$repo/environments/$name/deployment-branch-policies" \ - --silent -f name=main -f type=branch - ;; - esac - else - run gh api -X PUT "repos/$repo/environments/$name" --silent - fi -} - -# Every environment the workflows' jobs name, in any form a job can declare it -# (see the awk program). Matched as whole lines below, so npm-release never -# matches npm-prerelease. -environments=$(printf '%s\n' "${all_workflows:-}" | awk -f "$here/scripts/workflow-environments.awk") -names_environment() { - case " -$environments -" in - *" -$1 -"*) return 0 ;; - esac - return 1 -} - if names_environment npm-release; then environment npm-release main echo "then on npmjs.com: add a trusted publisher for publish-release.yml" \ "(environment npm-release)" fi if names_environment npm-prerelease; then - # Dispatched by hand from any branch a beta is built from. environment npm-prerelease any echo "then on npmjs.com: add a trusted publisher for publish-prerelease.yml" \ "(environment npm-prerelease)" diff --git a/tests/test_configure_environments.py b/tests/test_configure_environments.py new file mode 100644 index 0000000..33f4901 --- /dev/null +++ b/tests/test_configure_environments.py @@ -0,0 +1,260 @@ +"""configure.sh checks and enforces the publishing environments' branch policy. + +Run against a fake gh that keeps the repo's environments 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" + +WORKFLOW = ( + "jobs:\n" + " release:\n" + " environment: npm-release\n" + " beta:\n" + " environment:\n" + " name: npm-prerelease\n" + " python:\n" + " environment: pypi\n" +) + +# 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. +FAKE_GH = r"""#!{python} +import base64, 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, fields = "GET", 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 == "-f": + k, v = args[i + 1].split("=", 1); fields[k] = v; i += 1 + elif a == "--input": + 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)) +envs = state["environments"] +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 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="public", default_branch="main", allow_auto_merge=False) + out(repo) +elif method == "GET" and rest == "/contents/.github/workflows": + out([{{"path": ".github/workflows/publish.yml"}}]) +elif method == "GET" and rest == "/contents/.github/workflows/publish.yml": + 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": + out([]) +elif parts[:1] == ["environments"]: + name = parts[1] + env = envs.get(name) + if len(parts) == 2 and method == "GET": + if env is None: + not_found() + out({{"name": name, "deployment_branch_policy": env["policy"]}}) + elif len(parts) == 2 and method == "PUT": + env = envs.setdefault(name, {{"policy": None, "branches": []}}) + if not sys.stdin.isatty(): + body = sys.stdin.read().strip() + if body: + env["policy"] = json.loads(body)["deployment_branch_policy"] + save() + elif len(parts) == 3 and method == "GET": + if env is None or not (env["policy"] or {{}}).get("custom_branch_policies"): + not_found() + out({{"total_count": len(env["branches"]), "branch_policies": env["branches"]}}) + elif len(parts) == 3 and method == "POST": + new_id = max([b["id"] for b in env["branches"]] + [0]) + 1 + env["branches"].append({{"id": new_id, "name": fields["name"], "type": fields["type"]}}) + save() + elif len(parts) == 4 and method == "DELETE": + env["branches"] = [b for b in env["branches"] if str(b["id"]) != parts[3]] + save() + else: + sys.exit(99) +elif method == "GET": + not_found() +""" + +RESTRICTED = {"protected_branches": False, "custom_branch_policies": True} + + +def main_only(*extra: dict) -> dict: + return {"policy": RESTRICTED, "branches": [{"id": 1, "name": "main", "type": "branch"}, *extra]} + + +CLEAN = { + "npm-release": main_only(), + "pypi": main_only(), + "npm-prerelease": {"policy": None, "branches": []}, +} + + +@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 / "publish.yml").write_text(WORKFLOW) + (tmp_path / "calls").touch() + return tmp_path + + +def configure(fake: Path, environments: dict, *args: str, keep: bool = False): + if not keep: + (fake / "state.json").write_text(json.dumps({"environments": environments})) + (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 test_diff_is_clean_when_each_environment_is_right(fake): + result, _ = configure(fake, CLEAN, "--diff") + assert result.returncode == 0, result.stdout + result.stderr + assert "matches settings/" in result.stdout + + +@pytest.mark.parametrize( + ("name", "env", "line"), + [ + ("npm-release", {"policy": None, "branches": []}, "npm-release: any branch -> branch:main"), + ( + "npm-release", + {"policy": {"protected_branches": True, "custom_branch_policies": False}, "branches": []}, + "npm-release: protected branches -> branch:main", + ), + ("npm-release", None, "npm-release: missing -> branch:main"), + ( + "npm-release", + main_only({"id": 7, "name": "feature/*", "type": "branch"}), + "npm-release: branch:feature/*, branch:main -> branch:main", + ), + ("pypi", {"policy": RESTRICTED, "branches": []}, "pypi: no branch -> branch:main"), + ( + "pypi", + {"policy": RESTRICTED, "branches": [{"id": 1, "name": "main", "type": "tag"}]}, + "pypi: tag:main -> branch:main", + ), + ("npm-prerelease", None, "npm-prerelease: missing -> any branch"), + ], +) +def test_diff_reports_an_environment_that_drifted(fake, name, env, line): + environments = dict(CLEAN) + if env is None: + del environments[name] + else: + environments[name] = env + result, _ = configure(fake, environments, "--diff") + assert result.returncode == 1, result.stdout + result.stderr + assert f" environment {line}\n" in result.stdout + + +def test_diff_leaves_npm_prerelease_open(fake): + environments = dict(CLEAN) + environments["npm-prerelease"] = main_only({"id": 5, "name": "beta/*", "type": "branch"}) + result, _ = configure(fake, environments, "--diff") + assert result.returncode == 0, result.stdout + + +def test_apply_removes_each_extra_policy_then_diff_is_clean(fake): + environments = dict(CLEAN) + environments["npm-release"] = main_only( + {"id": 7, "name": "feature/*", "type": "branch"}, + {"id": 8, "name": "v*", "type": "tag"}, + ) + result, calls = configure(fake, environments, "--apply") + assert result.returncode == 0, result.stderr + assert "npm-release: removes branch policy branch:feature/* (only main may publish)" in result.stdout + assert "npm-release: removes branch policy tag:v* (only main may publish)" in result.stdout + deletes = [c for c in calls if c.startswith("api -X DELETE")] + assert deletes == [ + f"api -X DELETE repos/example/repo/environments/npm-release/deployment-branch-policies/{i} --silent" + for i in (7, 8) + ] + assert not any("-X POST" in c and "deployment-branch-policies" in c for c in calls) + result, _ = configure(fake, {}, "--diff", keep=True) + assert result.returncode == 0, result.stdout + + +def test_apply_restricts_an_open_environment_then_diff_is_clean(fake): + environments = dict(CLEAN) + environments["pypi"] = {"policy": None, "branches": []} + result, _ = configure(fake, environments, "--apply") + assert result.returncode == 0, result.stderr + result, _ = configure(fake, {}, "--diff", keep=True) + assert result.returncode == 0, result.stdout + + +def test_dry_run_says_what_it_would_remove_and_changes_nothing(fake): + environments = dict(CLEAN) + environments["npm-release"] = main_only({"id": 7, "name": "feature/*", "type": "branch"}) + result, calls = configure(fake, environments) + assert result.returncode == 0, result.stderr + assert "npm-release: would remove branch policy branch:feature/* (only main may publish)" in result.stdout + assert ( + "would run: gh api -X DELETE repos/example/repo/environments/npm-release/" + "deployment-branch-policies/7 --silent" + ) in result.stdout + assert not any(c.startswith("api -X") for c in calls) + result, _ = configure(fake, {}, "--diff", keep=True) + assert result.returncode == 1 From 5f3909d016b66ba1e62acb6609ccd9bcbfe15e0f Mon Sep 17 00:00:00 2001 From: Andreas Richardson Date: Wed, 18 Nov 2026 10:59:42 +0000 Subject: [PATCH 2/4] docs(standards): say how configure holds the environments' branch policy Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- STANDARDS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/STANDARDS.md b/STANDARDS.md index c0018a9..810856b 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -359,6 +359,15 @@ are gone. `--diff` reports it as drift. `--apply` warns and prints the command that removes it, but leaves it in place, since it can hold settings the ruleset does not. +**The publishing environments' branch policy is the only guard.** The publish +workflows add no branch check of their own, so `npm-release` and `pypi` must +allow exactly one branch policy, `branch:main`. `--diff` reports either one as +drift where it is missing, open to any branch or protected branches, or allows +anything besides `main`; `npm-prerelease`, dispatched from any branch on +purpose, only where it is missing. `--apply` deletes every other branch policy +on the two, naming each one, since a branch added in the UI could otherwise mint +the publishing token. + **Private repos on GitHub Free** get no rulesets, branch protection, secret scanning or private vulnerability reporting. `configure.sh` skips them rather than failing. From 991e51db21a91245a5e5512757a9900806232c3a Mon Sep 17 00:00:00 2001 From: Andreas Richardson Date: Wed, 18 Nov 2026 11:12:20 +0000 Subject: [PATCH 3/4] fix(configure): add main before removing policies, and read names safely Adds branch:main before deleting any other policy, refuses a policy GitHub reports with no type, matches environment names in any case, and no longer reads an environment out of a block scalar in a script. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- scripts/configure.sh | 31 +++++++------ scripts/workflow-environments.awk | 15 +++++++ tests/test_configure_environments.py | 67 +++++++++++++++++++++++++--- 3 files changed, 94 insertions(+), 19 deletions(-) diff --git a/scripts/configure.sh b/scripts/configure.sh index b9619c7..b2c9437 100755 --- a/scripts/configure.sh +++ b/scripts/configure.sh @@ -212,8 +212,10 @@ protection_summary() { # # Every environment the workflows' jobs name, in any form a job can declare it # (see the awk program). Matched as whole lines below, so npm-release never -# matches npm-prerelease. -environments=$(printf '%s\n' "${all_workflows:-}" | awk -f "$here/scripts/workflow-environments.awk") +# matches npm-prerelease, and in lower case, since GitHub's environment names +# ignore case. +environments=$(printf '%s\n' "${all_workflows:-}" | awk -f "$here/scripts/workflow-environments.awk" | + tr '[:upper:]' '[:lower:]') names_environment() { case " $environments @@ -241,12 +243,13 @@ read_environment() { } # The environment's branch policies as ` :` lines, left in -# $policies_file. GitHub answers 404 where the environment is missing or not +# $policies_file; a policy with no type reads `untyped:`, since a tag +# can be named main too. GitHub answers 404 where the environment is missing or not # limited to custom policies, and either way it has none; any other error # aborts. Called directly, as above. read_branch_policies() { if gh api --paginate "repos/$repo/environments/$1/deployment-branch-policies" \ - --jq '.branch_policies[] | "\(.id) \(.type):\(.name)"' >"$policies_file" 2>"$api_error"; then + --jq '.branch_policies[] | "\(.id) \(.type // "untyped"):\(.name)"' >"$policies_file" 2>"$api_error"; then return 0 fi : >"$policies_file" @@ -329,7 +332,7 @@ run() { # with `main` the only one. Any other, added in the UI say, is deleted, since # its branches could otherwise mint the publishing token. environment() { - local name=$1 limit=$2 id rule has_main=false verb=removes + local name=$1 limit=$2 id rule verb=removes if [ "$limit" != main ]; then run gh api -X PUT "repos/$repo/environments/$name" --silent return @@ -339,19 +342,21 @@ environment() { JSON [ "$mode" = --apply ] || verb="would remove" read_branch_policies "$name" + if grep ' untyped:' "$policies_file" >/dev/null; then + echo "$name has a branch policy GitHub reports with no type, so it could be a branch or a tag; check it in the repo's environment settings" >&2 + exit 1 + fi + # main first, so a failure part way never leaves main unable to publish. + if ! grep ' branch:main$' "$policies_file" >/dev/null; then + run gh api -X POST "repos/$repo/environments/$name/deployment-branch-policies" \ + --silent -f name=main -f type=branch + fi # Read on fd 3, so that nothing run in the loop can consume the list. while read -r id rule <&3; do - if [ "$rule" = branch:main ]; then - has_main=true - continue - fi + [ "$rule" != branch:main ] || continue echo "$name: $verb branch policy $rule (only main may publish)" run gh api -X DELETE "repos/$repo/environments/$name/deployment-branch-policies/$id" --silent done 3<"$policies_file" - if [ "$has_main" = false ]; then - run gh api -X POST "repos/$repo/environments/$name/deployment-branch-policies" \ - --silent -f name=main -f type=branch - fi } echo "$repo is $visibility" diff --git a/scripts/workflow-environments.awk b/scripts/workflow-environments.awk index c6c2992..990ce5c 100644 --- a/scripts/workflow-environments.awk +++ b/scripts/workflow-environments.awk @@ -6,6 +6,9 @@ # environment: # name: pypi # +# Text inside a block scalar (`run: |`, say) is skipped, so an example in a +# script never counts as a declaration. +# # A line-based reading, not a YAML parser, so configure.sh needs nothing beyond # awk. POSIX awk only: macOS ships BWK awk, which has no gensub. @@ -30,6 +33,18 @@ function indent(line) { next } +# Inside a block scalar: every line indented deeper than its key is text. +scalar { + if (indent(line) > scalar_indent) + next + scalar = 0 +} + +line ~ /:[ \t]*[|>][-+0-9]*[ \t]*$/ { + scalar = 1 + scalar_indent = indent(line) +} + # Inside a block mapping under `environment:`: look for its name, and leave it # at the first line indented no deeper than the key. block { diff --git a/tests/test_configure_environments.py b/tests/test_configure_environments.py index 33f4901..93a0062 100644 --- a/tests/test_configure_environments.py +++ b/tests/test_configure_environments.py @@ -39,7 +39,7 @@ args = sys.argv[2:] with open(os.path.join(fake, "calls"), "a") as log: log.write(" ".join(sys.argv[1:]) + "\n") -method, jq, endpoint, fields = "GET", None, None, {{}} +method, jq, endpoint, fields, body_from = "GET", None, None, {{}}, None i = 0 while i < len(args): a = args[i] @@ -50,7 +50,7 @@ elif a == "-f": k, v = args[i + 1].split("=", 1); fields[k] = v; i += 1 elif a == "--input": - i += 1 + body_from = args[i + 1]; i += 1 elif not a.startswith("-") and endpoint is None: endpoint = a i += 1 @@ -99,16 +99,17 @@ def out(value): out({{"name": name, "deployment_branch_policy": env["policy"]}}) elif len(parts) == 2 and method == "PUT": env = envs.setdefault(name, {{"policy": None, "branches": []}}) - if not sys.stdin.isatty(): - body = sys.stdin.read().strip() - if body: - env["policy"] = json.loads(body)["deployment_branch_policy"] + # gh sends a body only when --input names it. + if body_from == "-": + env["policy"] = json.loads(sys.stdin.read())["deployment_branch_policy"] save() elif len(parts) == 3 and method == "GET": if env is None or not (env["policy"] or {{}}).get("custom_branch_policies"): not_found() out({{"total_count": len(env["branches"]), "branch_policies": env["branches"]}}) elif len(parts) == 3 and method == "POST": + if os.path.exists(os.path.join(fake, "post-fails")): + sys.exit(1) new_id = max([b["id"] for b in env["branches"]] + [0]) + 1 env["branches"].append({{"id": new_id, "name": fields["name"], "type": fields["type"]}}) save() @@ -258,3 +259,57 @@ def test_dry_run_says_what_it_would_remove_and_changes_nothing(fake): assert not any(c.startswith("api -X") for c in calls) result, _ = configure(fake, {}, "--diff", keep=True) assert result.returncode == 1 + assert " environment npm-release: branch:feature/*, branch:main -> branch:main\n" in result.stdout + + +def test_apply_adds_main_before_removing_anything(fake): + # A failed add leaves the old policy, so main can still publish. + environments = dict(CLEAN) + environments["npm-release"] = {"policy": RESTRICTED, "branches": [{"id": 3, "name": "*", "type": "branch"}]} + (fake / "post-fails").touch() + result, calls = configure(fake, environments, "--apply") + assert result.returncode != 0 + assert not any(c.startswith("api -X DELETE") for c in calls) + state = json.loads((fake / "state.json").read_text()) + assert state["environments"]["npm-release"]["branches"] == [{"id": 3, "name": "*", "type": "branch"}] + + +def test_apply_refuses_a_policy_with_no_type(fake): + # It could be a tag named main, so it is neither kept nor deleted blindly. + environments = dict(CLEAN) + environments["npm-release"] = {"policy": RESTRICTED, "branches": [{"id": 4, "name": "main"}]} + result, _ = configure(fake, environments, "--diff") + assert result.returncode == 1 + assert " environment npm-release: untyped:main -> branch:main\n" in result.stdout + result, calls = configure(fake, environments, "--apply") + assert result.returncode == 1 + assert "no type" in result.stderr + assert not any("deployment-branch-policies" in c and "-X" in c for c in calls) + + +def test_environment_names_ignore_case(fake): + # GitHub treats NPM-RELEASE as npm-release. + (fake / "publish.yml").write_text(WORKFLOW.replace("environment: npm-release", "environment: NPM-Release")) + environments = dict(CLEAN) + environments["npm-release"] = {"policy": None, "branches": []} + result, _ = configure(fake, environments, "--diff") + assert result.returncode == 1 + assert " environment npm-release: any branch -> branch:main\n" in result.stdout + + +def test_an_example_in_a_script_names_no_environment(fake): + (fake / "publish.yml").write_text( + "jobs:\n" + " docs:\n" + " steps:\n" + " - run: |\n" + " cat < Date: Wed, 18 Nov 2026 11:19:48 +0000 Subject: [PATCH 4/4] test(configure): check the failed add was attempted Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwM29SqUigCfHvjshEYUDk --- tests/test_configure_environments.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_configure_environments.py b/tests/test_configure_environments.py index 93a0062..996e5d1 100644 --- a/tests/test_configure_environments.py +++ b/tests/test_configure_environments.py @@ -269,6 +269,10 @@ def test_apply_adds_main_before_removing_anything(fake): (fake / "post-fails").touch() result, calls = configure(fake, environments, "--apply") assert result.returncode != 0 + assert ( + "api -X POST repos/example/repo/environments/npm-release/deployment-branch-policies" + " --silent -f name=main -f type=branch" + ) in calls assert not any(c.startswith("api -X DELETE") for c in calls) state = json.loads((fake / "state.json").read_text()) assert state["environments"]["npm-release"]["branches"] == [{"id": 3, "name": "*", "type": "branch"}]