From 13b9264566e04877544e814343f8fcac18747641 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 13 Nov 2026 21:49:31 +0000 Subject: [PATCH] chore(template-sync): sync to v1.15.4 --- .github/scripts/README.md | 18 +- .github/scripts/setup_environments.sh | 209 +++++++++++++++ .github/scripts/template_sync.py | 61 ++++- .github/scripts/test_environments.py | 243 ++++++++++++++++++ .github/scripts/test_release_scripts.py | 93 ++++++- .github/scripts/test_template_sync.py | 87 +++++++ .github/template-sync-state.json | 2 +- .github/workflows/README.md | 28 +- .github/workflows/moderate-bug-fix.yml | 30 +++ .github/workflows/moderate-bug-triage.yml | 31 +++ .github/workflows/moderate-feature-build.yml | 30 +++ .github/workflows/moderate-feature-triage.yml | 31 +++ .github/workflows/release.yml | 31 +++ .github/workflows/template-sync.yml | 30 +++ docs/TEMPLATE.md | 45 ++++ scripts/README.md | 8 +- scripts/develop.sh | 54 ++-- 17 files changed, 1005 insertions(+), 26 deletions(-) create mode 100755 .github/scripts/setup_environments.sh create mode 100644 .github/scripts/test_environments.py diff --git a/.github/scripts/README.md b/.github/scripts/README.md index c75d4f6..143edca 100644 --- a/.github/scripts/README.md +++ b/.github/scripts/README.md @@ -4,6 +4,12 @@ tags and prints the next `tag=` / `version=` / `prerelease=` for `../workflows/release.yml`, given a release channel and a SemVer 2 bump. +- `setup_environments.sh` — creates or updates the `release`, `moderation` + and `template-sync` GitHub environments (default-branch-only deployment + rule) and prints the commands that move their secrets in; dry run unless + `--apply` (see `../../docs/TEMPLATE.md`, "Moderation and template-sync + environments"). `test_environments.py` runs the workflows' environment + check step against a stub `gh`. - `template_sync_manifest.py` — parses `../template-sync-manifest.yml` and checks that every git-tracked path matches exactly one tier; backs both the `template-sync-manifest` prek hook and @@ -30,6 +36,16 @@ `conflicts=0|1` line to `$GITHUB_OUTPUT`. `apply` catches its broad failure with `logging.exception` rather than a `noqa`, so instances that don't select ruff's `BLE` rules see no unused-`noqa` finding. + `apply` also creates the `ignore`-tier files a release introduces: an + exact-path `ignore` entry (not a glob or directory) whose file is in the new + tag but absent from the previous synced tag and from the instance is copied + in and listed under "New instance-owned files" in the PR body. An existing + file is never touched; a file the previous tag already had is not recreated, + so a deliberate deletion sticks (the state file records only the synced tag, + so the previous tag's tree is what tells a new path from a deleted one). + Which tier a path has is decided by the *upstream* tag's manifest alone: + the instance's own manifest, which classifies its tree for its own + instances, plays no part in a sync from its parent. `apply` is not atomic: on exit 2, files written before the error stay on disk. CI is safe because the runner checkout is discarded and the sync state does not advance. After a failed manual run, reset the working tree @@ -40,7 +56,7 @@ or `git init --bare` act on the outer repository, e.g. flipping its `core.bare`) and keeps only a test identity. - `test_template_sync.py` — stdlib `unittest` tests for - `template_sync.py`'s replace and merge tiers (including the executable + `template_sync.py`'s replace and merge tiers, new ignore-tier files (including the executable bit, re-running a merge, symlinked destinations, and `git merge-file` errors raising instead of counting as conflicts, binary files counting as conflicts, symlinked destinations kept on removal, one tree walk for diff --git a/.github/scripts/setup_environments.sh b/.github/scripts/setup_environments.sh new file mode 100755 index 0000000..bc9055f --- /dev/null +++ b/.github/scripts/setup_environments.sh @@ -0,0 +1,209 @@ +#!/usr/bin/env bash +# Create or update the GitHub environments the template's workflows run +# privileged jobs in, so each only runs from the default branch, and print the +# commands that move its secrets into it: +# +# release release.yml OCI_REGISTRY_USERNAME OCI_REGISTRY_PASSWORD +# NPM_TOKEN CARGO_REGISTRY_TOKEN +# moderation moderate-*.yml ANTHROPIC_API_KEY +# template-sync template-sync.yml TEMPLATE_SYNC_TOKEN +# +# Dry run by default: only `gh api` GETs. `--apply` is required to PUT an +# environment and POST its branch policy. Secrets are never moved or deleted +# (values can't be read back): the script prints the `gh secret set --env` / +# `gh secret delete` commands for a human to run. Organization secrets are +# listed by name and visibility, and the ones visible to every repository are +# flagged (a branch workflow can read them; an environment can't stop that). +# Existing reviewers and wait timers on an environment are kept. +# +# Usage: +# setup_environments.sh [--apply] [--env NAME]... [--org ORG] REPO... +# +# REPO is `owner/name`, or a bare name taken under --org (default: the owner of +# the current directory's `gh repo view`). --env may repeat and defaults to +# all three. Needs `gh` authenticated as a repository admin and `jq`. +set -euo pipefail + +ORG= +APPLY=false +ENVS=() + +secrets_of() { + case "$1" in + release) echo OCI_REGISTRY_USERNAME OCI_REGISTRY_PASSWORD NPM_TOKEN CARGO_REGISTRY_TOKEN ;; + moderation) echo ANTHROPIC_API_KEY ;; + template-sync) echo TEMPLATE_SYNC_TOKEN ;; + esac +} +workflow_of() { + case "$1" in + release) echo release.yml ;; + moderation) echo moderate-bug-triage.yml ;; + template-sync) echo template-sync.yml ;; + esac +} + +usage() { + sed -n '2,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//' +} + +repos=() +while [ $# -gt 0 ]; do + case "$1" in + --apply) APPLY=true ;; + --dry-run) APPLY=false ;; + --env) + case "${2:-}" in release | moderation | template-sync) ENVS+=("$2") ;; + *) echo "--env must be release, moderation or template-sync" >&2; exit 2 ;; + esac + shift ;; + --org) ORG="${2:?--org needs a value}"; shift ;; + -h | --help) usage; exit 0 ;; + -*) echo "unknown option: $1" >&2; usage >&2; exit 2 ;; + *) repos+=("$1") ;; + esac + shift +done +if [ "${#repos[@]}" -eq 0 ]; then + usage >&2 + exit 2 +fi +[ "${#ENVS[@]}" -gt 0 ] || ENVS=(release moderation template-sync) +[ -n "$ORG" ] || ORG=$(gh repo view --json owner -q .owner.login) + +echo "Mode: $($APPLY && echo APPLY || echo "DRY RUN (no changes; pass --apply)"); environments: ${ENVS[*]}" + +# gh api GET that prints nothing instead of failing on 404. +get() { + local out + if out=$(gh api "$@" 2> /dev/null); then + printf '%s\n' "$out" + fi +} + +status=0 + +echo +echo "== organization $ORG: secrets" +org_json=$(get "orgs/$ORG/actions/secrets") +if [ -z "$org_json" ]; then + echo " (cannot list organization secrets: needs org admin; skipped)" +else + while IFS=' ' read -r name vis; do + [ -n "$name" ] || continue + owner_env= + for e in "${ENVS[@]}"; do + for s in $(secrets_of "$e"); do [ "$s" = "$name" ] && owner_env=$e; done + done + [ -n "$owner_env" ] || continue + echo " $name: visibility=$vis ($owner_env secret)" + if [ "$vis" = all ]; then + echo " FLAG: visible to every repository, from any branch. Remediate (not run by this script):" + echo " per repo that needs it: gh secret set $name --env $owner_env -R $ORG/" + echo " then: gh secret delete $name --org $ORG" + fi + done < <(jq -r '.secrets[]? | "\(.name) \(.visibility)"' <<< "$org_json") +fi + +for r in "${repos[@]}"; do + case "$r" in */*) repo="$r" ;; *) repo="$ORG/$r" ;; esac + echo + echo "== $repo" + default=$(gh api "repos/$repo" -q .default_branch) || { + echo " ERROR: cannot read the repository (no access?)" + status=1 + continue + } + repo_json=$(get "repos/$repo/actions/secrets") + if [ -z "$repo_json" ]; then + echo " ERROR: cannot list repository secrets (needs admin access)" + status=1 + continue + fi + repo_secrets=$(jq -r '.secrets[]?.name' <<< "$repo_json") + + for env_name in "${ENVS[@]}"; do + echo " -- environment $env_name" + env_json=$(get "repos/$repo/environments/$env_name") + want_flags='{"protected_branches":false,"custom_branch_policies":true}' + have_flags=null + [ -z "$env_json" ] || have_flags=$(jq -c '.deployment_branch_policy // null' <<< "$env_json") + if [ -z "$env_json" ] || [ "$have_flags" != "$want_flags" ]; then + # A PUT replaces what it omits, so carry over existing protection rules. + body=$(jq -c --argjson flags "$want_flags" ' + {deployment_branch_policy: $flags} + + (if . == null then {} else + ([.protection_rules[]? | select(.type == "wait_timer") | .wait_timer][0] + // null | if . == null then {} else {wait_timer: .} end) + + ([.protection_rules[]? | select(.type == "required_reviewers")][0] + // null | if . == null then {} else + {prevent_self_review: .prevent_self_review, + reviewers: [.reviewers[] | {type: .type, id: .reviewer.id}]} end) + end)' <<< "${env_json:-null}") + [ -n "$env_json" ] && echo " exists, policy is $have_flags -> custom branch policies" \ + || echo " missing -> create with custom branch policies" + echo " PUT repos/$repo/environments/$env_name $body" + if $APPLY; then + gh api --method PUT "repos/$repo/environments/$env_name" --input - <<< "$body" > /dev/null + echo " done" + fi + else + echo " ok (custom branch policies)" + fi + + # Policies can be listed only once custom policies are on (else 404). + policies=$(get "repos/$repo/environments/$env_name/deployment-branch-policies") + have_default=false + if [ -n "$policies" ]; then + have_default=$(jq --arg b "$default" '[.branch_policies[]? | select(.name == $b and .type == "branch")] | length > 0' <<< "$policies") + while IFS= read -r extra; do + [ -n "$extra" ] || continue + echo " policy: unexpected '$extra' (not removed by this script; delete it by hand: the workflows' check wants exactly one rule)" + status=1 + done < <(jq -r --arg b "$default" '.branch_policies[]? | select(.name != $b or .type != "branch") | "\(.type):\(.name)"' <<< "$policies") + fi + if [ "$have_default" = true ]; then + echo " policy: branch '$default' ok" + else + echo " policy: add branch '$default'" + echo " POST repos/$repo/environments/$env_name/deployment-branch-policies name=$default type=branch" + if $APPLY; then + gh api --method POST "repos/$repo/environments/$env_name/deployment-branch-policies" \ + -f name="$default" -f type=branch > /dev/null + echo " done" + fi + fi + + env_secrets=$(get "repos/$repo/environments/$env_name/secrets" | jq -r '.secrets[]?.name') + wf=$(workflow_of "$env_name") + ready=no + if get "repos/$repo/contents/.github/workflows/$wf" -H "Accept: application/vnd.github.raw" \ + | grep -q "environment: $env_name"; then + ready=yes + fi + echo " $wf on $default declares 'environment: $env_name': $ready" + found=false + for s in $(secrets_of "$env_name"); do + in_repo=false + in_env=false + grep -qx "$s" <<< "$repo_secrets" && in_repo=true + grep -qx "$s" <<< "$env_secrets" && in_env=true + $in_repo || $in_env || continue + found=true + echo " secret $s: repo-level=$in_repo, $env_name-environment=$in_env" + if $in_repo && ! $in_env; then + echo " gh secret set $s --env $env_name -R $repo # paste the value; it can't be read back" + fi + if $in_repo; then + echo " gh secret delete $s -R $repo # only after the environment copy exists and the workflow has run once" + fi + done + $found || echo " secrets: none of $(secrets_of "$env_name") at repo or environment level" + if [ "$ready" = no ] && [ "$found" = true ]; then + echo " NOTE: move secrets only after this repo's $wf has 'environment: $env_name' (template sync);" + echo " an older workflow reads repository secrets and would find none." + fi + done +done + +exit "$status" diff --git a/.github/scripts/template_sync.py b/.github/scripts/template_sync.py index 9d258c6..1ad7d97 100644 --- a/.github/scripts/template_sync.py +++ b/.github/scripts/template_sync.py @@ -13,7 +13,8 @@ release channel, print the latest tag in that channel. - ``apply``: 3-way-apply the ``replace``/``merge`` tiers from a manifest between two template checkouts (the previously-synced tag and the new one) - and the instance's own working tree; print a summary and list any + and the instance's own working tree, and create the exact-path ``ignore`` + files the new release introduces; print a summary and list any merge conflicts. - ``check-apply``: confirm an ``apply`` exit status of 0 or 1 against its summary file, so a crash that exits 1 is not read as merge conflicts. @@ -368,6 +369,49 @@ def apply_merge( return {"merged": merged, "conflicts": conflicts, "binary": binary} +def starter_paths(root: Path, tiers: dict[str, list[str]]) -> set[str]: + """Return the ``ignore``-tier files under ``root`` named by an exact path. + + Only an exact-path entry is a starting copy the template hands over. A + glob (``docs/plans/[0-9]*.md``) or a directory entry matches the template's + own working documents or an instance's own content, which no instance + should receive. + """ + exact = { + pattern + for pattern in tiers["ignore"] + if not pattern.endswith("/") and "*" not in pattern and "?" not in pattern + } + return { + path + for path in exact + if (root / path).is_file() and not is_bytecode(path) and classify(path, tiers) == ["ignore"] + } + + +def apply_ignore_new( + old_root: Path, new_root: Path, instance_root: Path, paths: set[str] +) -> dict[str, list[str]]: + """Create ignore-tier files this release introduces; return {"created": [...]}. + + The instance owns an ``ignore`` file, so one that exists (or is a symlink) + is never touched. A file is created only when the previous release did not + have it at all, so a file the instance deleted on purpose is not brought + back by every sync. The state file records only the synced tag, so the + previous release's tree is the record of which paths are new. + """ + created: list[str] = [] + for path in sorted(paths): + src = new_root / path + dst = instance_root / path + if os.path.lexists(old_root / path) or os.path.lexists(dst): + continue + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + created.append(path) + return {"created": created} + + def _annotation_escape(value: str, *, prop: bool = False) -> str: """Percent-encode ``value`` for a GitHub workflow command (property or message).""" value = value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") @@ -395,6 +439,9 @@ def cmd_apply(args: argparse.Namespace) -> int: summary = { "replace": apply_replace(args.old_ref, args.new_ref, args.instance_root, replace_paths), "merge": apply_merge(args.old_ref, args.new_ref, args.instance_root, merge_paths), + "ignore": apply_ignore_new( + args.old_ref, args.new_ref, args.instance_root, starter_paths(args.new_ref, tiers) + ), } except Exception as err: # Any failure must exit 2: an uncaught exception exits 1, which reads @@ -480,6 +527,18 @@ def pr_body(summary: dict[str, dict[str, list[str]]], old_tag: str, new_tag: str "Resolve every conflict above before merging: text files have `<<<<<<<` markers; " "a binary file has none (it is left at the instance's version).", ] + created = summary.get("ignore", {}).get("created", []) + if created: + lines += [ + "", + "### New instance-owned files", + "", + "This release introduces these `ignore`-tier files. They were created from the " + "template because this repo lacked them; this repo owns them from now on, and " + "later syncs never overwrite them.", + "", + ] + lines += [f"- `{path}`" for path in created] if "pyproject.toml" in summary["merge"]["merged"] + summary["merge"]["conflicts"]: lines += [ "", diff --git a/.github/scripts/test_environments.py b/.github/scripts/test_environments.py new file mode 100644 index 0000000..73e607d --- /dev/null +++ b/.github/scripts/test_environments.py @@ -0,0 +1,243 @@ +"""Guard: secret-holding jobs run in an environment and verify it fail-fast. + +``release`` is covered in ``test_release_scripts.py``. Here: the ``moderation`` +environment (the moderate-* gate and Claude jobs, which read +``ANTHROPIC_API_KEY``) and ``template-sync`` (``TEMPLATE_SYNC_TOKEN``), and the +check step that reads the environment's deployment branch policy with the +job's own token. The step's shell is run against a stub ``gh``. +""" + +from __future__ import annotations + +import json +import os +import re +import stat +import subprocess +import tempfile +import unittest +from pathlib import Path + +SCRIPTS = Path(__file__).resolve().parent +WORKFLOWS = SCRIPTS.parent / "workflows" +DOCS = SCRIPTS.parent.parent / "docs" / "TEMPLATE.md" +SECRET_REF = re.compile(r"secrets\s*\.\s*(?!GITHUB_TOKEN\b)|secrets\s*\[|secrets\s*:\s*inherit") + +# workflow file -> (environment, jobs that must declare it) +EXPECTED = { + "moderate-bug-triage.yml": ("moderation", {"gate", "triage"}), + "moderate-feature-triage.yml": ("moderation", {"gate", "triage"}), + "moderate-bug-fix.yml": ("moderation", {"gate", "fix"}), + "moderate-feature-build.yml": ("moderation", {"gate", "build"}), + "template-sync.yml": ("template-sync", {"sync"}), +} +CHECKED = {**EXPECTED, "release.yml": ("release", {"version"})} + + +def jobs(text: str) -> dict[str, str]: + """Return {job name: body} of the top-level jobs, comment lines dropped.""" + section = text.split("\njobs:\n", 1)[1] + found = {} + for m in re.finditer(r"^ ([a-z][\w-]*):\n(.*?)(?=^ [a-z][\w-]*:\n|\Z)", section, re.M | re.S): + found[m.group(1)] = "\n".join( + line for line in m.group(2).splitlines() if not line.lstrip().startswith("#") + ) + return found + + +def check_script(job_body: str) -> str: + """Return the ``run`` block of the environment check step, dedented.""" + m = re.search( + r"- name: Check the \S+ environment is restricted.*?\n {8}run: \|\n((?: {10}[^\n]*\n|\n)+)", + job_body + "\n", + re.S, + ) + assert m, "no environment check step" + return "\n".join(line[10:] for line in m.group(1).splitlines()).rstrip() + "\n" + + +class EnvironmentDeclarationTest(unittest.TestCase): + def test_secret_holding_jobs_declare_the_environment_and_no_others(self) -> None: + for name, (env, wanted) in EXPECTED.items(): + for job, body in jobs((WORKFLOWS / name).read_text()).items(): + with self.subTest(workflow=name, job=job): + declared = re.search(r"^ environment: (.+)$", body, re.M) + self.assertEqual( + declared.group(1) if declared else None, env if job in wanted else None + ) + if SECRET_REF.search(body): + self.assertIn(job, wanted, "reads a secret outside the environment") + + def test_every_environment_line_is_a_plain_name(self) -> None: + """An expression could let a dispatcher pick an unrestricted environment.""" + for name in CHECKED: + for m in re.finditer( + r"^ +environment:[ \t]*(.*)$", (WORKFLOWS / name).read_text(), re.M + ): + with self.subTest(workflow=name): + self.assertRegex(m.group(1), r"^[a-z][a-z-]*$") + + def test_environments_have_no_reviewer_or_expression_dependence_on_triggers(self) -> None: + """Only default-branch event triggers (issues, schedule) or dispatch, so a branch rule fits.""" + for name in EXPECTED: + text = (WORKFLOWS / name).read_text() + on = text.split("\non:\n", 1)[1].split("\n\n", 1)[0] + triggers = set(re.findall(r"^ ([a-z_]+):", on, re.M)) + with self.subTest(workflow=name): + self.assertTrue(triggers <= {"issues", "schedule", "workflow_dispatch"}, triggers) + + +class EnvironmentCheckStepTest(unittest.TestCase): + def test_check_runs_before_the_first_secret_use_in_a_job_that_can_read_it(self) -> None: + for name, (env, wanted) in CHECKED.items(): + for job, body in jobs((WORKFLOWS / name).read_text()).items(): + if job not in wanted or job in {"triage", "fix", "build"}: + continue # those need the gate, which checks first + with self.subTest(workflow=name, job=job): + at = body.index(f"- name: Check the {env} environment") + for m in SECRET_REF.finditer(body): + self.assertLess(at, m.start()) + self.assertIn(f"ENVIRONMENT_NAME: {env}", body) + self.assertIn("GH_TOKEN: ${{ github.token }}", body) + + def test_claude_jobs_need_the_checking_gate(self) -> None: + for name, (_, wanted) in EXPECTED.items(): + if name == "template-sync.yml": + continue + claude = next(iter(wanted - {"gate"})) + with self.subTest(workflow=name): + self.assertIn("needs: gate", jobs((WORKFLOWS / name).read_text())[claude]) + + def test_job_can_read_environments(self) -> None: + """``actions: read`` is the permission the environments GET endpoints need.""" + for name, (_, wanted) in CHECKED.items(): + text = (WORKFLOWS / name).read_text() + for job in wanted: + if job in {"triage", "fix", "build"}: + continue + with self.subTest(workflow=name, job=job): + own = re.search( + r"^ permissions:\n((?: .*\n)+)", jobs(text)[job] + "\n", re.M + ) + top = text.split("\njobs:\n", 1)[0] + perms = own.group(1) if own else top + self.assertIn("actions: read", perms) + + def test_the_check_step_is_identical_everywhere(self) -> None: + scripts = { + name: check_script( + jobs((WORKFLOWS / name).read_text())[ + "gate" if "gate" in wanted else "sync" if "sync" in wanted else "version" + ] + ) + for name, (_, wanted) in CHECKED.items() + } + self.assertEqual(len(set(scripts.values())), 1, list(scripts)) + + def test_docs_describe_the_environments(self) -> None: + text = DOCS.read_text() + for needle in ( + "Moderation and template-sync environments", + "setup_environments.sh", + "gh secret set NAME --env ", + ): + self.assertIn(needle, text) + + +class EnvironmentCheckScriptTest(unittest.TestCase): + """Run the step's shell against a stub ``gh`` that serves canned JSON.""" + + script = check_script(jobs((WORKFLOWS / "moderate-bug-triage.yml").read_text())["gate"]) + + def run_check( + self, + env_json: dict | None, + policies: list[str] | None = None, + env_error: str = "gh: Not Found (HTTP 404)", + ) -> subprocess.CompletedProcess[str]: + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + bindir = tmp_path / "bin" + bindir.mkdir() + data = { + "env": env_json, + "policies": [ + {"type": p.split(":")[0], "name": p.split(":")[1]} for p in policies or [] + ], + } + (tmp_path / "data.json").write_text(json.dumps(data)) + stub = bindir / "gh" + stub.write_text( + "#!/usr/bin/env bash\n" + 'url="$2"\n' + 'case "$url" in\n' + f" */environments/*/deployment-branch-policies) jq -c '{{branch_policies: .policies}}' {tmp}/data.json | jq \"${{4:-.}}\" -r ;;\n" + f' */environments/*) if [ "$(jq -r .env {tmp}/data.json)" = null ]; then echo {json.dumps(env_error)} >&2; exit 1; fi; jq -c .env {tmp}/data.json ;;\n' + " *) echo main ;;\n" + "esac\n" + ) + stub.chmod(stub.stat().st_mode | stat.S_IEXEC) + return subprocess.run( # noqa: S603 -- fixed argv, local stub + ["bash", "-eo", "pipefail", "-c", self.script], + env={ + "PATH": f"{bindir}:{os.environ['PATH']}", + "GITHUB_REPOSITORY": "o/r", + "ENVIRONMENT_NAME": "moderation", + "TMPDIR": tmp, + }, + capture_output=True, + text=True, + check=False, + ) + + GOOD = { + "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True} + } + + def test_accepts_a_single_default_branch_rule(self) -> None: + proc = self.run_check(self.GOOD, ["branch:main"]) + self.assertEqual(proc.returncode, 0, proc.stderr + proc.stdout) + + def test_rejects_a_missing_environment(self) -> None: + proc = self.run_check(None) + self.assertEqual(proc.returncode, 1) + self.assertIn("does not exist", proc.stdout) + + def test_rejects_an_environment_without_a_branch_policy(self) -> None: + for env_json in ({"deployment_branch_policy": None}, {}): + proc = self.run_check(env_json) + with self.subTest(env=env_json): + self.assertEqual(proc.returncode, 1) + self.assertIn("default branch 'main' only", proc.stdout) + + def test_rejects_protected_branches_mode(self) -> None: + env_json = { + "deployment_branch_policy": { + "protected_branches": True, + "custom_branch_policies": False, + } + } + self.assertEqual(self.run_check(env_json).returncode, 1) + + def test_rejects_extra_or_wrong_rules(self) -> None: + for rules in ( + [], + ["branch:dev"], + ["branch:main", "branch:dev"], + ["tag:main"], + ["branch:main", "tag:v*"], + ): + with self.subTest(rules=rules): + self.assertEqual(self.run_check(self.GOOD, rules).returncode, 1) + + def test_an_unreadable_environment_warns_and_continues(self) -> None: + proc = self.run_check( + None, env_error="gh: Resource not accessible by integration (HTTP 403)" + ) + self.assertEqual(proc.returncode, 0) + self.assertIn("::warning::", proc.stdout) + self.assertIn("unverified", proc.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/test_release_scripts.py b/.github/scripts/test_release_scripts.py index 9d9cb2b..6552b49 100644 --- a/.github/scripts/test_release_scripts.py +++ b/.github/scripts/test_release_scripts.py @@ -632,7 +632,8 @@ def test_no_vendor_installer_script_is_run(self) -> None: self.assertNotIn("download_installer", self.text) for tool in ("uv", "prek"): self.assertRegex( - self.text, rf'fetch_checked "https://github\.com/[^"]*/\${{{tool}_asset}}\.tar\.gz"' + self.text, + rf'install_checked_tarball "https://github\.com/[^"]*/\${{{tool}_asset}}\.tar\.gz"', ) self.assertIn("install_claude ", self.text) self.assertRegex(self.text, r"(?m)^claude_signing_fpr=[0-9A-F]{40}$") @@ -741,6 +742,96 @@ def test_fetch_checked_rejects_a_wrong_or_missing_checksum(self) -> None: self.assertNotEqual(result.returncode, 0) self.assertNotIn("verified", result.stdout) + def test_install_claude_stops_gpg_agent_and_removes_the_keyring(self) -> None: + """The temporary GNUPGHOME is killed (gpg-agent, dirmngr) and removed once verification is done.""" + found = re.search(r"^install_claude\(\) \{\n.*?^\}\n", self.text, re.MULTILINE | re.DOTALL) + self.assertIsNotNone(found) + body = found.group(0) # type: ignore[union-attr] + kill = body.index('gpgconf --homedir "$gnupg_home" --kill all') + self.assertLess(body.index("--verify"), kill) + self.assertLess(kill, body.index('rm -rf "$gnupg_home"')) + + def run_install_checked_tarball( + self, tarball: bytes, checksum: str | None = None, member: str = "tool-1/bin" + ) -> tuple[subprocess.CompletedProcess[str], tuple[bytes, int] | None]: + """Run ``install_checked_tarball`` for ``member`` against a fake ``curl`` serving ``tarball``. + + ``checksum`` overrides the published digest; returns the result and the installed + file's ``(contents, mode)``, or ``None`` when nothing was installed. + """ + digest = checksum or hashlib.sha256(tarball).hexdigest() + with tempfile.TemporaryDirectory() as tmp: + served = Path(tmp) / "served" + dest = Path(tmp) / "dest" + served.mkdir() + dest.mkdir() + (served / "tool.tar.gz").write_bytes(tarball) + (served / "tool.tar.gz.sha256").write_text(f"{digest} tool.tar.gz\n") + curl_body = ( + 'while [ $# -gt 0 ]; do case "$1" in -o) out=$2;; http*) url=$1;; esac; shift; done\n' + f'cp "{served}/${{url##*/}}" "$out"\n' + ) + result, _ = self.run_bash( + ("tmp_path", "fetch", "fetch_checked", "install_checked_tarball"), + f'install_checked_tarball "https://example.invalid/tool.tar.gz" "{dest}" "{member}"\n' + "echo installed\n", + curl_body, + ) + installed = dest / Path(member).name + kept = ( + (installed.read_bytes(), installed.stat().st_mode) if installed.exists() else None + ) + return result, kept + + @staticmethod + def make_tarball(files: dict[str, bytes]) -> bytes: + """Return a gzipped tarball of ``files`` (name to contents).""" + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as archive: + for name, content in files.items(): + info = tarfile.TarInfo(name) + info.size = len(content) + archive.addfile(info, io.BytesIO(content)) + return buffer.getvalue() + + def test_install_checked_tarball_extracts_and_installs_executable(self) -> None: + """A tarball with a matching checksum installs the named member, mode 0755.""" + result, kept = self.run_install_checked_tarball( + self.make_tarball({"tool-1/bin": b"binary"}) + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("installed", result.stdout) + self.assertIsNotNone(kept) + contents, mode = kept # type: ignore[misc] + self.assertEqual(contents, b"binary") + self.assertEqual(mode & 0o777, 0o755) + + def test_install_checked_tarball_rejects_a_checksum_mismatch(self) -> None: + """A wrong published digest aborts before anything is installed.""" + result, kept = self.run_install_checked_tarball( + self.make_tarball({"tool-1/bin": b"binary"}), checksum="0" * 64 + ) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("installed", result.stdout) + self.assertIsNone(kept) + + def test_install_checked_tarball_rejects_an_empty_file(self) -> None: + """An empty download fails even when its checksum is the (matching) digest of nothing.""" + result, kept = self.run_install_checked_tarball(b"") + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("installed", result.stdout) + self.assertIn("empty", result.stderr) + self.assertIsNone(kept) + + def test_install_checked_tarball_rejects_a_missing_member(self) -> None: + """A tarball lacking the named member aborts rather than installing nothing.""" + result, kept = self.run_install_checked_tarball( + self.make_tarball({"tool-1/other": b"binary"}) + ) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("installed", result.stdout) + self.assertIsNone(kept) + @staticmethod def gpg_key(home: Path, name: str) -> tuple[str, bytes]: """Create a throwaway signing key in ``home``; return its fingerprint and armored public key.""" diff --git a/.github/scripts/test_template_sync.py b/.github/scripts/test_template_sync.py index 8edb528..2cfd22e 100644 --- a/.github/scripts/test_template_sync.py +++ b/.github/scripts/test_template_sync.py @@ -937,6 +937,93 @@ def test_workflow_opens_conflicted_sync_as_draft(self) -> None: self.assertIn('PYTHONDONTWRITEBYTECODE: "1"', text) +class NewIgnoreFilesTest(unittest.TestCase): + """A new exact-path ignore-tier file is created once and then instance-owned.""" + + TIERS: dict[str, list[str]] = { + "replace": ["tool.sh"], + "ignore": ["compose.instance.yml", "docs/plans/[0-9]*.md", "src/"], + "merge": [], + } + + def run_apply(self, old: Path, new: Path, inst: Path) -> dict[str, dict[str, list[str]]]: + """Run ``cmd_apply`` over the trees with ``TIERS``; return its summary.""" + manifest = old.parent / "manifest.yml" + manifest.write_text( + "".join( + f"{tier}:\n" + "".join(f" - {p}\n" for p in pats) + for tier, pats in self.TIERS.items() + ) + ) + args = argparse.Namespace(manifest=manifest, old_ref=old, new_ref=new, instance_root=inst) + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(template_sync.cmd_apply(args), 0) + summary: dict[str, dict[str, list[str]]] = json.loads(out.getvalue()) + return summary + + def trees(self, tmp: str) -> tuple[Path, Path, Path]: + """Make empty old/new/instance trees.""" + old, new, inst = (Path(tmp) / n for n in ("old", "new", "inst")) + for d in (old, new, inst): + d.mkdir() + return old, new, inst + + def test_created_when_missing_and_listed_in_pr_body(self) -> None: + """A file new in this release is copied, reported and named in the PR body.""" + with tempfile.TemporaryDirectory() as tmp: + old, new, inst = self.trees(tmp) + write(new / "compose.instance.yml", b"services: {}\n", 0o644) + summary = self.run_apply(old, new, inst) + self.assertEqual((inst / "compose.instance.yml").read_bytes(), b"services: {}\n") + self.assertEqual(summary["ignore"]["created"], ["compose.instance.yml"]) + body = template_sync.pr_body(summary, "v1.0.0", "v1.1.0", "o/t") + self.assertIn("### New instance-owned files", body) + self.assertIn("- `compose.instance.yml`", body) + + def test_not_overwritten_when_present(self) -> None: + """An existing instance file keeps its content and is not reported.""" + with tempfile.TemporaryDirectory() as tmp: + old, new, inst = self.trees(tmp) + write(new / "compose.instance.yml", b"new\n", 0o644) + write(inst / "compose.instance.yml", b"mine\n", 0o644) + summary = self.run_apply(old, new, inst) + self.assertEqual((inst / "compose.instance.yml").read_bytes(), b"mine\n") + self.assertEqual(summary["ignore"]["created"], []) + body = template_sync.pr_body(summary, "v1.0.0", "v1.1.0", "o/t") + self.assertNotIn("New instance-owned files", body) + + def test_not_resurrected_after_deliberate_deletion(self) -> None: + """A file the previous release already had is not recreated in an instance lacking it.""" + with tempfile.TemporaryDirectory() as tmp: + old, new, inst = self.trees(tmp) + write(old / "compose.instance.yml", b"old\n", 0o644) + write(new / "compose.instance.yml", b"new\n", 0o644) + summary = self.run_apply(old, new, inst) + self.assertFalse((inst / "compose.instance.yml").exists()) + self.assertEqual(summary["ignore"]["created"], []) + + def test_globs_and_directories_are_not_starter_files(self) -> None: + """Template plans (a glob) and ``src/`` (a directory) are never handed to instances.""" + with tempfile.TemporaryDirectory() as tmp: + old, new, inst = self.trees(tmp) + write(new / "docs/plans/2026-01-x.md", b"plan\n", 0o644) + write(new / "src/app.py", b"x\n", 0o644) + summary = self.run_apply(old, new, inst) + self.assertEqual(summary["ignore"]["created"], []) + self.assertFalse((inst / "docs").exists()) + self.assertFalse((inst / "src").exists()) + + def test_symlink_in_instance_is_left_alone(self) -> None: + """A (dangling) symlink at the path counts as present.""" + with tempfile.TemporaryDirectory() as tmp: + old, new, inst = self.trees(tmp) + write(new / "compose.instance.yml", b"new\n", 0o644) + (inst / "compose.instance.yml").symlink_to(inst / "elsewhere") + self.run_apply(old, new, inst) + self.assertFalse((inst / "elsewhere").exists()) + + class DirectlyInvokedScriptsAreExecutableTest(unittest.TestCase): """A workflow step that names a script as the command needs mode 755 (exit 126 otherwise).""" diff --git a/.github/template-sync-state.json b/.github/template-sync-state.json index ad38024..685a507 100644 --- a/.github/template-sync-state.json +++ b/.github/template-sync-state.json @@ -1,4 +1,4 @@ { "template_repo": "craftainer/template-base", - "synced_tag": "v1.15.3" + "synced_tag": "v1.15.4" } diff --git a/.github/workflows/README.md b/.github/workflows/README.md index a00e043..dd7ff84 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -67,7 +67,19 @@ fails the job before the sync state advances. The job then exits with `apply`'s own status when that is 2 or higher (so the log and the step's exit code tell an error from conflicts) and the summary is printed as valid - only after that check. The sync never copies Python bytecode + only after that check. The `ignore` tier is instance-owned: sync never overwrites or deletes an + `ignore` file. The one exception is a new starting copy: an exact-path + `ignore` entry whose file the new tag introduces (the previous synced tag + lacks it) is created when the instance lacks it, and the PR body lists it + under "New instance-owned files". A glob or directory entry is never + created, nor is a file the previous tag already had, so a file the instance + deleted stays deleted. A path's tier comes from the upstream tag's manifest + only, so when a parent's `ignore` file (template-docker's `README.md`, + `Dockerfile`, `image.mk`) is also listed by the instance's own manifest + (template-fastapi or -react, which ship their own versions), the parent's + `ignore` wins for that sync: the instance's copy is left as it is, and its + own manifest classifies the path only for the instance's own instances. + The sync never copies Python bytecode (`__pycache__/`, `*.pyc`), and the apply step sets `PYTHONDONTWRITEBYTECODE` so running the script cannot create any in the template checkout. @@ -262,8 +274,13 @@ Activating this in a given repo/fork takes two one-time steps, neither of which is itself a workflow: provisioning a dedicated Anthropic Console workspace (its own `ANTHROPIC_API_KEY`, a monthly spend limit, and a usage alert at 80% of it) and storing that key as the -`ANTHROPIC_API_KEY` repository secret, then running `moderate-setup.yml` -once to create the labels below. +`ANTHROPIC_API_KEY` secret of the `moderation` environment (the `gate` +and Claude jobs declare `environment: moderation`; create it with +`../scripts/setup_environments.sh`, see `../../docs/TEMPLATE.md`, +"Moderation and template-sync environments"), then running +`moderate-setup.yml` once to create the labels below. The `gate` job's +first step fails the run if that environment is missing or isn't +restricted to the default branch. Two independent label sequences track state, applied by the `apply` jobs (`gh issue edit`) from a fixed action-to-label table, or by a deterministic @@ -290,7 +307,7 @@ output — `secrets` isn't readable from `jobs..if` directly `jobs..env`. The real job then carries `if: needs.gate.outputs.has-key == 'true' && `, checked before checkout — so a fork or clone that hasn't set the -`ANTHROPIC_API_KEY` repository secret sees every one of these jobs show +`ANTHROPIC_API_KEY` secret sees every one of these jobs show **Skipped**, not **Failed**, and gets no failure-triggered email from GitHub's default Actions notifications. `moderate-cleanup.yml` has no such gate (see its own header comment) and always runs. @@ -421,7 +438,8 @@ variables/secrets, all optional: no-ops except during the first cron-scheduled week of the month. - `TEMPLATE_SYNC_CHANNEL` (variable, `stable` | `alpha` | `beta` | `rc`, default `stable`) — which tag channel to sync to. -- `TEMPLATE_SYNC_TOKEN` (secret) — a PAT used to read the template +- `TEMPLATE_SYNC_TOKEN` (secret, held in the `template-sync` environment the + `sync` job declares; first step checks it) — a PAT used to read the template repository and to push the sync branch / open the sync PR. It needs the `workflow` scope (classic PAT) or **Workflows: read/write** (fine-grained), because the default `GITHUB_TOKEN` can't push diff --git a/.github/workflows/moderate-bug-fix.yml b/.github/workflows/moderate-bug-fix.yml index 6a40069..085800e 100644 --- a/.github/workflows/moderate-bug-fix.yml +++ b/.github/workflows/moderate-bug-fix.yml @@ -40,12 +40,14 @@ jobs: if: github.event.label.name == 'bug:confirm' # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation outputs: has-key: ${{ steps.check.outputs.has-key }} repro-sha: ${{ steps.resolve-sha.outputs.sha }} # issues: write consumes the label; contents: read lets resolve-sha # read the branch tip (a job-level block replaces the workflow-level one). permissions: + actions: read contents: read issues: write env: @@ -59,6 +61,33 @@ jobs: env: ISSUE_NUMBER: ${{ github.event.issue.number }} run: gh issue edit "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" --remove-label "bug:confirm" + - name: Check the moderation environment is restricted to the default branch + env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT_NAME: moderation + run: | + # Fail-fast only: a writer can delete this step on their own branch. + # The enforcement is the environment's deployment branch policy. + # See docs/TEMPLATE.md, "Moderation and template-sync environments". + err=$(mktemp) + if ! env_json=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME" 2> "$err"); then + if grep -q 'HTTP 404' "$err"; then + echo "::error::Environment '$ENVIRONMENT_NAME' does not exist or is not readable. Create it with the setup in docs/TEMPLATE.md before running this workflow." + exit 1 + fi + echo "::warning::Cannot read environment '$ENVIRONMENT_NAME' with this token ($(head -c 200 "$err")); its branch policy is unverified." + exit 0 + fi + default_branch=$(gh api "repos/$GITHUB_REPOSITORY" --jq .default_branch) + flags=$(jq -r '.deployment_branch_policy | if . == null then "none" else "\(.custom_branch_policies)/\(.protected_branches)" end' <<< "$env_json") + policies= + if [ "$flags" = "true/false" ]; then + policies=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME/deployment-branch-policies" --jq '[.branch_policies[] | "\(.type):\(.name)"] | sort | join(",")') + fi + if [ "$policies" != "branch:$default_branch" ]; then + echo "::error::Environment '$ENVIRONMENT_NAME' must allow deployments from the default branch '$default_branch' only (custom branch policy, one rule 'branch:$default_branch'); found policy '$flags', rules '$policies'. Fix it with the setup in docs/TEMPLATE.md." + exit 1 + fi - id: check run: echo "has-key=${{ secrets.ANTHROPIC_API_KEY != '' }}" >> "$GITHUB_OUTPUT" # Resolves the repro branch's tip as early as possible and pins the @@ -90,6 +119,7 @@ jobs: contains(github.event.issue.labels.*.name, 'claude:ok')) }} # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation timeout-minutes: 20 permissions: contents: read diff --git a/.github/workflows/moderate-bug-triage.yml b/.github/workflows/moderate-bug-triage.yml index 4ea54ed..8b36ff3 100644 --- a/.github/workflows/moderate-bug-triage.yml +++ b/.github/workflows/moderate-bug-triage.yml @@ -28,9 +28,39 @@ jobs: gate: # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation + permissions: + actions: read outputs: has-key: ${{ steps.check.outputs.has-key }} steps: + - name: Check the moderation environment is restricted to the default branch + env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT_NAME: moderation + run: | + # Fail-fast only: a writer can delete this step on their own branch. + # The enforcement is the environment's deployment branch policy. + # See docs/TEMPLATE.md, "Moderation and template-sync environments". + err=$(mktemp) + if ! env_json=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME" 2> "$err"); then + if grep -q 'HTTP 404' "$err"; then + echo "::error::Environment '$ENVIRONMENT_NAME' does not exist or is not readable. Create it with the setup in docs/TEMPLATE.md before running this workflow." + exit 1 + fi + echo "::warning::Cannot read environment '$ENVIRONMENT_NAME' with this token ($(head -c 200 "$err")); its branch policy is unverified." + exit 0 + fi + default_branch=$(gh api "repos/$GITHUB_REPOSITORY" --jq .default_branch) + flags=$(jq -r '.deployment_branch_policy | if . == null then "none" else "\(.custom_branch_policies)/\(.protected_branches)" end' <<< "$env_json") + policies= + if [ "$flags" = "true/false" ]; then + policies=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME/deployment-branch-policies" --jq '[.branch_policies[] | "\(.type):\(.name)"] | sort | join(",")') + fi + if [ "$policies" != "branch:$default_branch" ]; then + echo "::error::Environment '$ENVIRONMENT_NAME' must allow deployments from the default branch '$default_branch' only (custom branch policy, one rule 'branch:$default_branch'); found policy '$flags', rules '$policies'. Fix it with the setup in docs/TEMPLATE.md." + exit 1 + fi - id: check run: echo "has-key=${{ secrets.ANTHROPIC_API_KEY != '' }}" >> "$GITHUB_OUTPUT" @@ -43,6 +73,7 @@ jobs: contains(github.event.issue.labels.*.name, 'claude:ok')) }} # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation timeout-minutes: 10 # Read-only: this job runs Claude against the issue's (untrusted) text, so # whatever a prompt injection reaches must not be able to push, comment or diff --git a/.github/workflows/moderate-feature-build.yml b/.github/workflows/moderate-feature-build.yml index aa27c09..45b0243 100644 --- a/.github/workflows/moderate-feature-build.yml +++ b/.github/workflows/moderate-feature-build.yml @@ -40,12 +40,14 @@ jobs: if: github.event.label.name == 'enhancement:confirm' # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation outputs: has-key: ${{ steps.check.outputs.has-key }} plan-sha: ${{ steps.resolve-sha.outputs.sha }} # issues: write consumes the label; contents: read lets resolve-sha # read the branch tip (a job-level block replaces the workflow-level one). permissions: + actions: read contents: read issues: write env: @@ -59,6 +61,33 @@ jobs: env: ISSUE_NUMBER: ${{ github.event.issue.number }} run: gh issue edit "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" --remove-label "enhancement:confirm" + - name: Check the moderation environment is restricted to the default branch + env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT_NAME: moderation + run: | + # Fail-fast only: a writer can delete this step on their own branch. + # The enforcement is the environment's deployment branch policy. + # See docs/TEMPLATE.md, "Moderation and template-sync environments". + err=$(mktemp) + if ! env_json=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME" 2> "$err"); then + if grep -q 'HTTP 404' "$err"; then + echo "::error::Environment '$ENVIRONMENT_NAME' does not exist or is not readable. Create it with the setup in docs/TEMPLATE.md before running this workflow." + exit 1 + fi + echo "::warning::Cannot read environment '$ENVIRONMENT_NAME' with this token ($(head -c 200 "$err")); its branch policy is unverified." + exit 0 + fi + default_branch=$(gh api "repos/$GITHUB_REPOSITORY" --jq .default_branch) + flags=$(jq -r '.deployment_branch_policy | if . == null then "none" else "\(.custom_branch_policies)/\(.protected_branches)" end' <<< "$env_json") + policies= + if [ "$flags" = "true/false" ]; then + policies=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME/deployment-branch-policies" --jq '[.branch_policies[] | "\(.type):\(.name)"] | sort | join(",")') + fi + if [ "$policies" != "branch:$default_branch" ]; then + echo "::error::Environment '$ENVIRONMENT_NAME' must allow deployments from the default branch '$default_branch' only (custom branch policy, one rule 'branch:$default_branch'); found policy '$flags', rules '$policies'. Fix it with the setup in docs/TEMPLATE.md." + exit 1 + fi - id: check run: echo "has-key=${{ secrets.ANTHROPIC_API_KEY != '' }}" >> "$GITHUB_OUTPUT" # Resolves the plan branch's tip as early as possible and pins the @@ -90,6 +119,7 @@ jobs: contains(github.event.issue.labels.*.name, 'claude:ok')) }} # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation timeout-minutes: 20 permissions: contents: read diff --git a/.github/workflows/moderate-feature-triage.yml b/.github/workflows/moderate-feature-triage.yml index ab5dad0..68659a0 100644 --- a/.github/workflows/moderate-feature-triage.yml +++ b/.github/workflows/moderate-feature-triage.yml @@ -28,9 +28,39 @@ jobs: gate: # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation + permissions: + actions: read outputs: has-key: ${{ steps.check.outputs.has-key }} steps: + - name: Check the moderation environment is restricted to the default branch + env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT_NAME: moderation + run: | + # Fail-fast only: a writer can delete this step on their own branch. + # The enforcement is the environment's deployment branch policy. + # See docs/TEMPLATE.md, "Moderation and template-sync environments". + err=$(mktemp) + if ! env_json=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME" 2> "$err"); then + if grep -q 'HTTP 404' "$err"; then + echo "::error::Environment '$ENVIRONMENT_NAME' does not exist or is not readable. Create it with the setup in docs/TEMPLATE.md before running this workflow." + exit 1 + fi + echo "::warning::Cannot read environment '$ENVIRONMENT_NAME' with this token ($(head -c 200 "$err")); its branch policy is unverified." + exit 0 + fi + default_branch=$(gh api "repos/$GITHUB_REPOSITORY" --jq .default_branch) + flags=$(jq -r '.deployment_branch_policy | if . == null then "none" else "\(.custom_branch_policies)/\(.protected_branches)" end' <<< "$env_json") + policies= + if [ "$flags" = "true/false" ]; then + policies=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME/deployment-branch-policies" --jq '[.branch_policies[] | "\(.type):\(.name)"] | sort | join(",")') + fi + if [ "$policies" != "branch:$default_branch" ]; then + echo "::error::Environment '$ENVIRONMENT_NAME' must allow deployments from the default branch '$default_branch' only (custom branch policy, one rule 'branch:$default_branch'); found policy '$flags', rules '$policies'. Fix it with the setup in docs/TEMPLATE.md." + exit 1 + fi - id: check run: echo "has-key=${{ secrets.ANTHROPIC_API_KEY != '' }}" >> "$GITHUB_OUTPUT" @@ -43,6 +73,7 @@ jobs: contains(github.event.issue.labels.*.name, 'claude:ok')) }} # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: moderation timeout-minutes: 10 # Read-only: this job runs Claude against the issue's (untrusted) text, so # whatever a prompt injection reaches must not be able to push, comment or diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5905159..f3c3141 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -68,6 +68,9 @@ jobs: version: # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + permissions: + actions: read + contents: read outputs: tag: ${{ steps.version.outputs.tag }} version: ${{ steps.version.outputs.version }} @@ -85,6 +88,34 @@ jobs: exit 1 fi + - name: Check the release environment is restricted to the default branch + env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT_NAME: release + run: | + # Fail-fast only: a writer can delete this step on their own branch. + # The enforcement is the environment's deployment branch policy. + # See docs/TEMPLATE.md, "Moderation and template-sync environments". + err=$(mktemp) + if ! env_json=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME" 2> "$err"); then + if grep -q 'HTTP 404' "$err"; then + echo "::error::Environment '$ENVIRONMENT_NAME' does not exist or is not readable. Create it with the setup in docs/TEMPLATE.md before running this workflow." + exit 1 + fi + echo "::warning::Cannot read environment '$ENVIRONMENT_NAME' with this token ($(head -c 200 "$err")); its branch policy is unverified." + exit 0 + fi + default_branch=$(gh api "repos/$GITHUB_REPOSITORY" --jq .default_branch) + flags=$(jq -r '.deployment_branch_policy | if . == null then "none" else "\(.custom_branch_policies)/\(.protected_branches)" end' <<< "$env_json") + policies= + if [ "$flags" = "true/false" ]; then + policies=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME/deployment-branch-policies" --jq '[.branch_policies[] | "\(.type):\(.name)"] | sort | join(",")') + fi + if [ "$policies" != "branch:$default_branch" ]; then + echo "::error::Environment '$ENVIRONMENT_NAME' must allow deployments from the default branch '$default_branch' only (custom branch policy, one rule 'branch:$default_branch'); found policy '$flags', rules '$policies'. Fix it with the setup in docs/TEMPLATE.md." + exit 1 + fi + - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/.github/workflows/template-sync.yml b/.github/workflows/template-sync.yml index a89b8ad..00fe447 100644 --- a/.github/workflows/template-sync.yml +++ b/.github/workflows/template-sync.yml @@ -24,6 +24,7 @@ on: required: false permissions: + actions: read contents: write pull-requests: write @@ -34,7 +35,36 @@ jobs: sync: # renovate: datasource=github-runners depName=ubuntu runs-on: ${{ vars.CI_RUNNER || 'ubuntu-24.04' }} + environment: template-sync steps: + # Before the checkout below, the first use of TEMPLATE_SYNC_TOKEN. + - name: Check the template-sync environment is restricted to the default branch + env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT_NAME: template-sync + run: | + # Fail-fast only: a writer can delete this step on their own branch. + # The enforcement is the environment's deployment branch policy. + # See docs/TEMPLATE.md, "Moderation and template-sync environments". + err=$(mktemp) + if ! env_json=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME" 2> "$err"); then + if grep -q 'HTTP 404' "$err"; then + echo "::error::Environment '$ENVIRONMENT_NAME' does not exist or is not readable. Create it with the setup in docs/TEMPLATE.md before running this workflow." + exit 1 + fi + echo "::warning::Cannot read environment '$ENVIRONMENT_NAME' with this token ($(head -c 200 "$err")); its branch policy is unverified." + exit 0 + fi + default_branch=$(gh api "repos/$GITHUB_REPOSITORY" --jq .default_branch) + flags=$(jq -r '.deployment_branch_policy | if . == null then "none" else "\(.custom_branch_policies)/\(.protected_branches)" end' <<< "$env_json") + policies= + if [ "$flags" = "true/false" ]; then + policies=$(gh api "repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT_NAME/deployment-branch-policies" --jq '[.branch_policies[] | "\(.type):\(.name)"] | sort | join(",")') + fi + if [ "$policies" != "branch:$default_branch" ]; then + echo "::error::Environment '$ENVIRONMENT_NAME' must allow deployments from the default branch '$default_branch' only (custom branch policy, one rule 'branch:$default_branch'); found policy '$flags', rules '$policies'. Fix it with the setup in docs/TEMPLATE.md." + exit 1 + fi # TEMPLATE_SYNC_TOKEN, not the default GITHUB_TOKEN: checkout stores # this token for the later `git push`, and GITHUB_TOKEN can never # create or update files under .github/workflows/ -- which most diff --git a/docs/TEMPLATE.md b/docs/TEMPLATE.md index 79deb39..50df13e 100644 --- a/docs/TEMPLATE.md +++ b/docs/TEMPLATE.md @@ -239,6 +239,51 @@ Findings from the OWASP review (A03/A08), and what each now does: consumed images and features by digest, and an org ruleset requiring review for `.github/workflows/**`. See the [GitHub documentation](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments) and [npm's](https://docs.npmjs.com/trusted-publishers). +- **Moderation and template-sync environments (setup step for each + instance).** The jobs that read a secret declare an environment, the + same way `release.yml` does: `moderation` for the `gate` job and the + Claude job (`triage`/`fix`/`build`) of the four `moderate-*.yml` + workflows (`ANTHROPIC_API_KEY`), and `template-sync` for + `template-sync.yml`'s `sync` job (`TEMPLATE_SYNC_TOKEN`). The `apply` + and `cleanup` jobs read no secret (only the per-job `GITHUB_TOKEN` + permissions, which an environment cannot scope) and declare none. + Run `.github/scripts/setup_environments.sh` once per repository, **before + syncing the workflows that carry the `environment:` lines**: + `setup_environments.sh OWNER/REPO` is a dry run that prints what it + would do; `--apply` creates each environment with *Selected branches* + and one rule, the default branch, and keeps any reviewers or wait timer + already set; `--env NAME` limits it. It never touches secrets (values + can't be read back): it prints `gh secret set NAME --env ` + and `gh secret delete NAME` for you to run, and flags an organization + secret visible to all repositories, which any branch workflow can read + and which has to be recreated as an environment secret. A job reads an + environment secret only if it declares the environment, and an + environment secret overrides a repository one of the same name, so move + the secret after the workflow is synced and the environment exists. + The branch rule matches every trigger these workflows use: `issues` + (opened, reopened, closed, labeled) and `schedule` runs always have the + default branch as `GITHUB_REF` and `GITHUB_SHA`, and a + `workflow_dispatch` run has the branch it was dispatched on, so a + dispatch from another branch is refused, as intended. Use the branch + rule only: required reviewers or a wait timer would hold every issue + event until someone approves. Sources: + [events that trigger workflows](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) + (`GITHUB_REF`/`GITHUB_SHA` per event), + [managing environments](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments). + Referencing an environment that doesn't exist makes GitHub create it with + no rules, so the workflows check it themselves: the `gate` job (the first + step before it reads the secret), `template-sync.yml`'s first step and + `release.yml`'s `version` job read + `GET repos/{repo}/environments/{name}` and its + `deployment-branch-policies` with the job's own token (the + `actions: read` permission those endpoints need) and **fail** with a + message when the environment is missing or has no custom branch policy, + or its rules aren't exactly one `branch:`. If the token + cannot read the environment (a 401/403), the step only warns that the + policy is unverified, so a token or plan difference never blocks a + release or a moderation run. The check is a fail-fast diagnostic only: a + writer can delete it on their own branch. What enforces the rule is the + environment itself. - **Renovate waits 3 days before automerging.** The "patch and minor updates" group sets `minimumReleaseAge: "3 days"` (the age Renovate's own `security:minimumReleaseAgeNpm` preset uses) with diff --git a/scripts/README.md b/scripts/README.md index 1dba3d0..caa3bb0 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -16,9 +16,13 @@ to 4 times; timeouts are left to curl's own `--retry`), so CI's shared-IP HTTP 429s don't fail the image build. Local builds need no token. No vendor install script is run: `uv` and `prek` are release tarballs - checked against the `.sha256` published beside them (`fetch_checked`), + checked against the `.sha256` published beside them (`install_checked_tarball`, + built on `fetch_checked`; an empty download is rejected), and Claude Code's binary is checked against its GPG-signed - `manifest.json` (key fingerprint pinned in `claude_signing_fpr`); see + `manifest.json` (key fingerprint pinned in `claude_signing_fpr`; the temporary keyring's + gpg-agent is killed and the keyring removed once verified). `gnupg` and + `jq` stay installed: the devcontainer's hooks, moderation scripts and + `install_claude` tests use them. See `../docs/TEMPLATE.md`'s "Supply chain and release hardening". - `post-create.sh` — the devcontainer's `postCreateCommand`: git `safe.directory`, `prek install`, then every `post-create.d/*.sh`. diff --git a/scripts/develop.sh b/scripts/develop.sh index 6a19448..f600f45 100644 --- a/scripts/develop.sh +++ b/scripts/develop.sh @@ -153,6 +153,29 @@ fetch_checked() { (cd "$dir" && awk -v n="$name" '$2 == n { print; found = 1 } END { exit !found }' "${name}.sha256" | sha256sum -c -) } +# install_checked_tarball ...: fetch_checked's +# download of a .tar.gz release asset, then installs each (a path +# inside the tarball, e.g. uv-x86_64-unknown-linux-gnu/uv) into +# with mode 0755. Fails closed: a failed download, an empty file, a checksum +# mismatch or a missing member aborts before anything is installed. +install_checked_tarball() { + local url=$1 dest=$2 name dir member + shift 2 + name="${url##*/}" + tmp_path -d + dir="$tmp_result" + fetch_checked "$url" "$dir" + if [ ! -s "${dir}/${name}" ]; then + echo "downloaded ${name} is empty: ${url}" >&2 + return 1 + fi + tar -xzf "${dir}/${name}" -C "$dir" "$@" + for member in "$@"; do + install -m755 -t "$dest" "${dir}/${member}" + done + rm -rf "$dir" +} + # Fingerprint of Anthropic's Claude Code release signing key (see the docs # above); a key whose primary fingerprint differs is rejected. claude_signing_fpr=31DDDE24DDFAB679F42D7BD2BAA929FF1A7ECACE @@ -188,6 +211,10 @@ install_claude() { echo "Claude Code manifest is not signed by ${claude_signing_fpr}" >&2 return 1 } + # Stop the gpg-agent/dirmngr the import started and remove the keyring, + # so nothing lingers in the image layer. + gpgconf --homedir "$gnupg_home" --kill all + rm -rf "$gnupg_home" manifest_version="$(jq -er '.version' "${dir}/manifest.json")" if [ "$manifest_version" != "$version" ]; then echo "Claude Code manifest is for ${manifest_version}, expected ${version}" >&2 @@ -212,9 +239,14 @@ run_uv_python_install() { } # xz-utils: Node's own release tarballs are .tar.xz. gnupg and jq: verifying -# the Claude Code manifest's signature and reading its checksum. bubblewrap -# and socat: the dependencies of Claude Code's built-in sandbox on Linux, -# which the issue-moderation workflows require (run_claude.sh fails closed +# the Claude Code manifest's signature and reading its checksum. They are +# kept afterwards, not purged: the devcontainer's own checks need them -- +# jq for .claude/hooks/self-check.sh and the .github/scripts moderation +# scripts, gpg and jq for the install_claude tests in +# .github/scripts/test_release_scripts.py (which skip without them, so a +# purge would silently drop that coverage from `prek`). bubblewrap and +# socat: the dependencies of Claude Code's built-in sandbox on Linux, which +# the issue-moderation workflows require (run_claude.sh fails closed # without it). apt-get update apt-get install -y --no-install-recommends gnupg jq xz-utils bubblewrap socat @@ -243,12 +275,8 @@ case "$dpkg_arch" in esac uv_asset="uv-${rust_arch}-unknown-linux-gnu" -tmp_path -d -uv_tmpdir="$tmp_result" -fetch_checked "https://github.com/astral-sh/uv/releases/download/${uv_version}/${uv_asset}.tar.gz" "$uv_tmpdir" -tar -xzf "${uv_tmpdir}/${uv_asset}.tar.gz" -C "$uv_tmpdir" "${uv_asset}/uv" "${uv_asset}/uvx" -install -m755 -t /usr/local/bin "${uv_tmpdir}/${uv_asset}/uv" "${uv_tmpdir}/${uv_asset}/uvx" -rm -rf "$uv_tmpdir" +install_checked_tarball "https://github.com/astral-sh/uv/releases/download/${uv_version}/${uv_asset}.tar.gz" \ + /usr/local/bin "${uv_asset}/uv" "${uv_asset}/uvx" # python3 isn't otherwise a dependency of this template -- it's # infrastructure tooling only: prek (like pre-commit) needs *some* @@ -289,12 +317,8 @@ ln -s "/usr/local/lib/nodejs/${node_asset}/bin/npx" /usr/local/bin/npx # instance, regardless of language, is expected to run # `prek run --all-files --hook-stage manual` (see checks.yml). prek_asset="prek-${rust_arch}-unknown-linux-gnu" -tmp_path -d -prek_tmpdir="$tmp_result" -fetch_checked "https://github.com/j178/prek/releases/download/v${prek_version}/${prek_asset}.tar.gz" "$prek_tmpdir" -tar -xzf "${prek_tmpdir}/${prek_asset}.tar.gz" -C "$prek_tmpdir" "${prek_asset}/prek" -install -m755 -t /usr/local/bin "${prek_tmpdir}/${prek_asset}/prek" -rm -rf "$prek_tmpdir" +install_checked_tarball "https://github.com/j178/prek/releases/download/v${prek_version}/${prek_asset}.tar.gz" \ + /usr/local/bin "${prek_asset}/prek" # Created here, owned by vscode, because a fresh claude-config volume # (compose.yml) copies this directory's ownership and mode on first mount;