From 491bddc192f4914315e2f20a66ac3841eb4b4dc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 23:15:30 +0000 Subject: [PATCH 1/5] ci-gate: fold the tamper guard into the gate's verdict; caller template fixes The pull_request_target tamper guard never started (account Actions policy: "Event 'pull_request_target' is not allowed to trigger Actions workflows."). Interim per the owner's ruling: the guard runs inside the gate's own verdict, from the default-branch paths, with no second status context. - ci-gate-tamper-guard.sh: EXTRA_PROTECTED_FILE (exact, validated .github/workflows paths); guard-result/guard-touched lines tell a verdict from an error; --match unchanged. - ci-gate-publish.sh: before the verdict, run the guard for each open same-repository PR headed by the SHA (GUARD_PRS, else the workflow_run event's pull_requests confirmed by GET pulls/, else commits//pulls). Unapproved: failure "gate files changed without owner approval: ". Any guard error: no verdict. - Protected set widens to every workflow named in the repository's profile. - ci-gate-sweep.sh passes the same-repository PRs it lists; ci-gate.yml fetches the guard and hands the event's PRs through env. - Retire the pull_request_target guard: suite caller removed, reusable and template marked deprecated (kept while consumers reference them). - Caller template and suite caller: permissions {} with job-level grants; Dependabot excluded from gate-pr; gate skips workflow_dispatch from a non-default ref; zizmor dangerous-triggers ignore with justification; actions.lock note is the empty file-level entry, not de-onboarding. - docs/CI-GATE.adoc: new Tamper guard section and residual limits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDi2sk6iYihWBAsHfzH --- .github/workflows/ci-gate-caller.yml | 55 ++++--- .../workflows/ci-gate-tamper-guard-caller.yml | 20 --- .github/workflows/ci-gate-tamper-guard.yml | 8 + .github/workflows/ci-gate.yml | 22 ++- config/workflow-lock-scope.json | 7 +- docs/CI-GATE.adoc | 46 ++++-- scripts/ci-gate-publish.sh | 75 +++++++++ scripts/ci-gate-sweep.sh | 15 +- scripts/ci-gate-tamper-guard.sh | 34 +++- templates/ci-gate-caller.yml | 72 ++++++--- templates/ci-gate-tamper-guard-caller.yml | 8 + tests/ci-gate-tamper-guard.sh | 52 +++++- tests/ci-gate.sh | 149 +++++++++++++++++- 13 files changed, 452 insertions(+), 111 deletions(-) delete mode 100644 .github/workflows/ci-gate-tamper-guard-caller.yml diff --git a/.github/workflows/ci-gate-caller.yml b/.github/workflows/ci-gate-caller.yml index 17900817..8add7249 100644 --- a/.github/workflows/ci-gate-caller.yml +++ b/.github/workflows/ci-gate-caller.yml @@ -4,50 +4,65 @@ # ./.github/workflows/ci-gate.yml (so the gate runs at the suite's own default-branch commit, with no # second pin to drift), and the context is "CI / gate", the one this repository's `main` ruleset requires. # -# workflow_run, schedule and workflow_dispatch all run from the DEFAULT branch, so a pull request cannot -# edit this file or the profile (profiles/ci-gate/hyperpolymath/proven-cicd-and-workflows.json) that -# judges it. The pull request that first adds this file therefore never receives `CI / gate` itself and -# is merged past the gate once (docs/CI-GATE.adoc, "Bootstrap"); the gate-pr job at the end removes that need. +# workflow_run and schedule run from the DEFAULT branch, so a pull request cannot edit this file or the +# profile (profiles/ci-gate/hyperpolymath/proven-cicd-and-workflows.json) that judges it on those paths. +# workflow_dispatch runs the file of the ref it is started from; the `gate` job does nothing for a +# workflow_dispatch from a ref other than the default branch (its `if:`). The pull request that first +# adds this file never receives `CI / gate` from the default-branch paths and is merged past the gate +# once (docs/CI-GATE.adoc, "Bootstrap"); the gate-pr job at the end removes that need. +# +# TAMPER GUARD: folded into the gate's verdict (docs/CI-GATE.adoc, "Tamper guard"). A same-repository +# pull request that touches a gate file or a workflow named in the profile fails `CI / gate` until the +# OWNER applies `gate-change-approved` after the newest commit. AGENTS MUST NEVER APPLY THAT LABEL. +# Only the default-branch paths are trusted; gate-pr runs the pull request's own copy of this file. # # The job id MUST stay `gate` and the workflow name MUST stay `CI gate`: the reusable drops runs of # that name from the evaluation, and the `if:` below keeps the gate from triggering itself. # There is deliberately NO `concurrency:` block. The pull_request job at the end is permanent # (docs/CI-GATE.adoc, "The pull_request start"); tests/ci-gate.sh pins its shape. +# Permissions: none at workflow level; each job grants exactly what the reusable asks for. # No `secrets:` line: the reusable consumes none. name: CI gate on: pull_request: - workflow_run: + workflow_run: # zizmor: ignore[dangerous-triggers] the gate never checks out or runs pull request code; it reads API metadata only workflows: ["**", "!CI gate"] types: [completed, in_progress] schedule: - cron: "7,22,37,52 * * * *" workflow_dispatch: {} -permissions: - statuses: write - actions: read - contents: read - pull-requests: read +permissions: {} jobs: gate: - if: github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.name != 'CI gate') + if: github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.name != 'CI gate') && (github.event_name != 'workflow_dispatch' || github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) + permissions: + statuses: write + actions: read + contents: read + pull-requests: read uses: ./.github/workflows/ci-gate.yml with: context: "CI / gate" - # The pull_request start. workflow_run, schedule and workflow_dispatch run only from the default - # branch, so without this job the pull request that adds or changes the gate never gets the status - # and a ruleset requiring it blocks that very pull request. This job runs from the pull request's own - # branch and posts the same verdict, waiting (bounded) for the checks named in the profile to report. - # Same-repository branches only: a fork's or Dependabot's pull_request token cannot write statuses, - # and those are covered by the workflow_run job. No trust decision uses github.actor. - # Because a pull request can edit this file, the Gate tamper guard (ci-gate-tamper-guard.yml, run from - # the default branch) fails a pull request that touches gate files unless the owner has approved it. + # The pull_request start. workflow_run and schedule run only from the default branch, so without this + # job the pull request that adds or changes the gate never gets the status and a ruleset requiring it + # blocks that very pull request. This job runs from the pull request's own branch and posts the same + # verdict, waiting (bounded) for the checks named in the profile to report. + # Same-repository branches only, and not Dependabot's: a fork's or Dependabot's pull_request token is + # read-only and cannot write statuses; the workflow_run job covers both. The Dependabot test only + # EXCLUDES a run (it can never grant anything), so it is not a trust decision; none uses github.actor. + # Because a pull request can edit this file, this path is PR-controlled: it runs the tamper guard for + # early feedback only. The trusted guard is the default-branch `gate` job above. gate-pr: - if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]' + permissions: + statuses: write + actions: read + contents: read + pull-requests: read uses: ./.github/workflows/ci-gate.yml with: context: "CI / gate" diff --git a/.github/workflows/ci-gate-tamper-guard-caller.yml b/.github/workflows/ci-gate-tamper-guard-caller.yml deleted file mode 100644 index 17834a71..00000000 --- a/.github/workflows/ci-gate-tamper-guard-caller.yml +++ /dev/null @@ -1,20 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -# Gate tamper guard - the suite guards its own gate files. pull_request_target runs this file from the -# DEFAULT branch, so a pull request cannot edit it; the job never checks out or runs pull request code -# (it reads the changed-file list through the API). Local reusable, like ci-gate-caller.yml. -# A pull request that touches gate files fails this check until the OWNER applies the label -# `gate-change-approved` after the newest commit. AGENTS MUST NEVER APPLY THAT LABEL. -# No `secrets:` line, minimal permissions. See docs/CI-GATE.adoc, "Tamper guard". -name: Gate tamper guard - -on: - pull_request_target: - types: [opened, reopened, synchronize, edited, labeled, unlabeled] - -permissions: - pull-requests: read - contents: read - -jobs: - guard: - uses: ./.github/workflows/ci-gate-tamper-guard.yml diff --git a/.github/workflows/ci-gate-tamper-guard.yml b/.github/workflows/ci-gate-tamper-guard.yml index 7f86b6c1..41c17a68 100644 --- a/.github/workflows/ci-gate-tamper-guard.yml +++ b/.github/workflows/ci-gate-tamper-guard.yml @@ -1,4 +1,12 @@ # SPDX-License-Identifier: MPL-2.0 +# ⚠ DEPRECATED (2026-11-23). This guard has NEVER started: every run ends in startup_failure because +# the account Actions policy refuses its trigger with +# "Event 'pull_request_target' is not allowed to trigger Actions workflows." +# (rsr-template-repo 30/30, resource-algebra 50/50, this suite 30/30). The guard now runs INSIDE the +# gate's own verdict (ci-gate.yml -> scripts/ci-gate-publish.sh -> scripts/ci-gate-tamper-guard.sh; +# docs/CI-GATE.adoc, "Tamper guard"). Do not install it anywhere new. It is kept only while consumers +# still reference it; a later pass removes their pull_request_target caller, then this file. +# # # ci-gate-tamper-guard.yml (reusable) - fail a pull request that touches the gate's own files # unless the owner approved the change with the label `gate-change-approved`. diff --git a/.github/workflows/ci-gate.yml b/.github/workflows/ci-gate.yml index 871f1dce..9b97abd9 100644 --- a/.github/workflows/ci-gate.yml +++ b/.github/workflows/ci-gate.yml @@ -27,6 +27,14 @@ # publisher on each distinct head SHA (scripts/ci-gate-sweep.sh), with no early pending. That bounds # nothing by itself: a sweep is one more last-writer-wins evaluator (docs/CI-GATE.adoc, "Residual limit"). # +# TAMPER GUARD: before the verdict, the publisher runs scripts/ci-gate-tamper-guard.sh (fetched with the +# other scripts) for every open same-repository pull request whose head is the evaluated SHA (workflow_run: +# the event's pull_requests, else commits//pulls; sweep: the pull requests it lists; pull_request: +# its own number). A pull request that touches a gate file or a workflow named in the profile without the +# owner's `gate-change-approved` label makes the verdict `failure` ("gate files changed without owner +# approval: "); a guard error is "no verdict". Only the default-branch paths (workflow_run, sweep) +# are trusted; the pull_request path runs the pull request's own caller (docs/CI-GATE.adoc, "Tamper guard"). +# # FAIL CLOSED: a missing or invalid profile, an empty `job.workflow_sha`, any API error, or # any event other than workflow_run, schedule or workflow_dispatch is a failure, never a pass or a pending. # @@ -45,7 +53,8 @@ # "**" (docs/CI-GATE.adoc, "API budget"). # # The caller must grant: statuses: write, actions: read, contents: read, pull-requests: read -# (the last one is read only by the sweep, to list open pull requests). +# (the last one is read by the sweep, to list open pull requests, and by the tamper guard). Grant them at +# JOB level, with `permissions: {}` at workflow level (templates/ci-gate-caller.yml). # No `secrets:` — the reusable consumes none. name: CI gate (reusable) @@ -264,6 +273,7 @@ jobs: fetch scripts/validate-ci-gate-profile.sh fetch scripts/ci-gate-publish.sh fetch scripts/ci-gate-sweep.sh + fetch scripts/ci-gate-tamper-guard.sh fetch profiles/ci-gate/validate.jq fetch profiles/ci-gate/select-runs.jq mkdir -p "$suite/profiles/ci-gate/${REPO%%/*}" @@ -278,6 +288,8 @@ jobs: env: WF_REPO: ${{ job.workflow_repository }} WF_SHA: ${{ job.workflow_sha }} + PR_NUMBER: ${{ github.event.pull_request.number }} + WORKFLOW_RUN_PRS: ${{ toJSON(github.event.workflow_run.pull_requests) }} # All of the reading, the settle guard and the publishing is scripts/ci-gate-publish.sh # (fetched from the suite above), so a stub `gh` can test it offline. On schedule and # workflow_dispatch scripts/ci-gate-sweep.sh runs that same publisher once per open pull @@ -285,10 +297,14 @@ jobs: run: | set -euo pipefail if [[ "$EVENT_NAME" == workflow_run ]]; then - SUITE="$suite" WORK="$RUNNER_TEMP/ci-gate-work" WAIT_SECONDS=0 bash "$suite/scripts/ci-gate-publish.sh" + # tamper guard: the pull requests this run names (else the publisher looks them up) + GUARD_EVENT_PRS="$WORKFLOW_RUN_PRS" SUITE="$suite" WORK="$RUNNER_TEMP/ci-gate-work" WAIT_SECONDS=0 \ + bash "$suite/scripts/ci-gate-publish.sh" elif [[ "$EVENT_NAME" == pull_request ]]; then # pull_request path: one evaluation, so wait (bounded) for the required checks to report. - SUITE="$suite" WORK="$RUNNER_TEMP/ci-gate-work" WAIT_SECONDS=$((WAIT_MINUTES * 60)) \ + # tamper guard for this pull request too: early feedback only, since this path runs the + # pull request's own caller (docs/CI-GATE.adoc, "Tamper guard"). + GUARD_PRS="$PR_NUMBER" SUITE="$suite" WORK="$RUNNER_TEMP/ci-gate-work" WAIT_SECONDS=$((WAIT_MINUTES * 60)) \ bash "$suite/scripts/ci-gate-publish.sh" else SUITE="$suite" WORK="$RUNNER_TEMP/ci-gate-sweep" bash "$suite/scripts/ci-gate-sweep.sh" diff --git a/config/workflow-lock-scope.json b/config/workflow-lock-scope.json index e6c171a0..bfea7ad4 100644 --- a/config/workflow-lock-scope.json +++ b/config/workflow-lock-scope.json @@ -19,12 +19,7 @@ { "path": ".github/workflows/ci-gate-tamper-guard.yml", "mode": "immutable", - "reason": "Reusable tamper guard: uses no actions, never checks out or runs pull request code; reads changed files, label events and commit dates through the API." - }, - { - "path": ".github/workflows/ci-gate-tamper-guard-caller.yml", - "mode": "immutable", - "reason": "The suite guards its own gate files: pull_request_target caller of the local reusable guard; runs from the default branch, no checkout, minimal permissions." + "reason": "DEPRECATED reusable tamper guard (pull_request_target is refused by the account Actions policy; the guard now runs inside ci-gate.yml). Kept while consumers still reference it: uses no actions, never checks out or runs pull request code." }, { "path": ".github/workflows/ci-gate-caller.yml", diff --git a/docs/CI-GATE.adoc b/docs/CI-GATE.adoc index 756b76a4..c66ce82e 100644 --- a/docs/CI-GATE.adoc +++ b/docs/CI-GATE.adoc @@ -6,8 +6,9 @@ context `CI/gate`, and nothing emitted it. This is a swappable interim gate that A3 `estate-gate` replaces it by changing one pin and one context name in each caller. * Reusable: `.github/workflows/ci-gate.yml` (job id `gate`). -* Caller: `templates/ci-gate-caller.yml` (`__CICD_SUITE_SHA__`, DE-ONBOARDED from `actions.lock` like the Rust CI caller). The suite gates itself with `.github/workflows/ci-gate-caller.yml` (context `CI / gate`, the local reusable). +* Caller: `templates/ci-gate-caller.yml` (`__CICD_SUITE_SHA__`; listed in `actions.lock` as an empty file-level entry, `'.github/workflows/ci-gate.yml': []`, with no leaf record: GitHub's lockfile does not pin reusable-workflow calls, a leaf record fails `gh actions-lock` as "Unused lockfile entry" and no entry fails as "not-pinned"; proven on trope-checker, echo-types, hermeneia and panic-attack). The suite gates itself with `.github/workflows/ci-gate-caller.yml` (context `CI / gate`, the local reusable). * Sweep: `scripts/ci-gate-sweep.sh`, run by the reusable on `schedule` and `workflow_dispatch`. +* Tamper guard: `scripts/ci-gate-tamper-guard.sh`, run by the publisher inside the verdict (see "Tamper guard"). * Verdict (pure, offline): `scripts/ci-gate-verdict.sh`; profile validator `scripts/validate-ci-gate-profile.sh` with `profiles/ci-gate/validate.jq`. * Required-check lists: `profiles/ci-gate//.json`, derived as recorded in link:../profiles/ci-gate/README.adoc[profiles/ci-gate/README.adoc]. * Controls: `tests/ci-gate.sh` (run by the `Composite shell contract` job of `code-hygiene-self-test.yml`). @@ -89,7 +90,7 @@ The reusable accepts `workflow_run`, `pull_request`, `schedule` and `workflow_di |Field |Statement |Events |`workflow_run` (one commit), `pull_request` (the pull request head, through the same-repository `gate-pr` job), `schedule` and `workflow_dispatch` (a sweep of every open pull request head and the default branch head, at most 100 SHAs). Any other event is refused: red job, no status. (default `CI/gate`; the one swappable name; 1 to 128 characters: an alphanumeric first, then `[A-Za-z0-9._/-]` with single interior spaces, so `CI/gate` and `CI / gate` pass and a leading, trailing or repeated space, a tab or a newline does not; the regex `^[A-Za-z0-9]([A-Za-z0-9._/-]| [A-Za-z0-9._/-]){0,127}$` alone would admit up to 255 characters, so the length is checked separately; the validation step and the failure fallback carry the identical guard), `timeout_minutes` (default 180). The repository is never an input: the profile is selected by `github.repository`. No `secrets:`. |Side effects |On an `in_progress` event a first `POST /repos/{repo}/statuses/{head_sha}` of `pending`; then a verdict POST, repeated if the settle guard or the post-write verification finds the runs moved (at most 5 rounds on `workflow_run`, then `pending` "runs still changing"; `pull_request` continues settling until the wait deadline, then fails), with the context, state, description (at most 140 characters) and a `target_url` to the gate run, except that a write identical in context, state and description to the status already standing is skipped; each write is preceded by a read of the combined status of the commit; a step summary. Nothing else is written. Pending is a normal wait for the next `workflow_run`. On `pull_request`, unfinished checks are polled until the elapsed wait deadline; a success invalidated by moving runs is replaced with pending before waiting, and unsettled runs at the deadline produce failure. -|Permissions |Granted by the caller: `statuses: write`, `actions: read`, `contents: read`, `pull-requests: read` (read only by the sweep). The reusable asks for exactly these and no more. +|Permissions |Granted by the caller at JOB level (`permissions: {}` at workflow level): `statuses: write`, `actions: read`, `contents: read`, `pull-requests: read` (the sweep lists open pull requests; the tamper guard reads a pull request's files, label events and commits). The reusable asks for exactly these and no more. |Subjects |The head commit of the triggering workflow run or pull request, in the repository the caller lives in. Required checks are Actions job names in the suite's profile for that repository. Third-party checks are out of scope. |Failure and refusal |Any event other than `workflow_run`, `pull_request`, `schedule` or `workflow_dispatch`: refused, red job, no status. A sweep that ends with any SHA in failure or error is red. A missing, empty, malformed, wrong-repository or self-naming profile, an empty `job.workflow_repository` or `job.workflow_sha`, or any API error: failure; the job is red and a final step posts a failure status if none was published. A failed verdict also exits the job non-zero. No code from the consumer or a pull request is checked out or executed, and no `${{ }}` reaches a `run:` script (values travel through `env:`). |Controls |`tests/ci-gate.sh`: the context guard extracted from the workflow itself (accepts `CI/gate` and `CI / gate`, rejects leading, trailing and repeated spaces, tab, newline, empty and 129 characters, identical in both places, the dogfood caller's context passes), the publisher end to end with the context `CI / gate`; the unchanged-status skip (unchanged, changed state, changed description, failing or malformed read, other context, `die()`, sweep); a 200 KB workflow run record through the publisher; run paths with an `@` suffix (matches the bare file, never another file); positive control (all present and successful); negatives with exact states for a required name with no job (headline: nothing active), an unrelated run still active (pending) and past the timeout (failure), two producers of one name with one still queued (pending), two same-named jobs in one run with one failing, superseded runs, a second attempt, the gate's own run ignored, failed/cancelled/skipped/neutral/timed_out/action_required/stale/startup_failure jobs, malformed inputs, description length;; the status writer extracted from the workflow and driven through the early pending step, the failure fallback, the publisher and the sweep with a stubbed `gh` (rate limited then written, with the `Retry-After`, `x-ratelimit-reset` and backoff waits; rate limited to exhaustion by attempts and by time, giving `rate limited, no verdict`; a 500 and a permissions 403 not retried; a duplicate skipped; a new state, another description and another context written; the sweep stopping), the per-SHA `concurrency` block; the sweep (a stale success corrected to failure, a stuck pending corrected to success, SHA de-duplication, the cap and its warning, one SHA's API error not stopping the others, the non-zero exit); the validator rejects malformed JSON, wrong repository, empty list, the gate's own contexts, duplicate members and unclean names; the shipped profiles validate and are JCS-serialised; static guards (no `${{` in any `run:`, no `uses:`, `workflow_call` only, template has a same-repository `gate-pr` job on `pull_request` and excludes that event from `gate`, no `concurrency` block, both `workflow_run` types, `schedule`, `workflow_dispatch` and `pull-requests: read`; the suite's own caller). @@ -98,6 +99,10 @@ The reusable accepts `workflow_run`, `pull_request`, `schedule` and `workflow_di == Known limits +* `wait_minutes` (default 30, maximum 50) can be shorter than a long required check (for example a 45-minute Idris2 or "Standards pipeline" job): `gate-pr` then gives up with `failure: gave up after N min`. Every later pull request has the `workflow_run` evaluator, which re-evaluates when that check completes; only the pull request that adds the caller lacks it. Re-run `gate-pr` there. +* A producer workflow filtered to `branches: [main]` never runs for a stacked pull request that targets another branch, so its required checks read `never reported` and the gate fails. Profile only producers that run for every base branch, or retarget the stack to `main`. +* `timeout_minutes` (default 180) counts from the earliest workflow run on the commit, so a pull request reopened more than 180 minutes after its runs started can time out on a fresh run of the same head. A new commit resets it. +* The tamper guard is folded into this gate and narrows, not closes, the hole of a pull request rewriting a profiled producer into a no-op; fork pull requests are not guarded ("Tamper guard"). * Bootstrap: see "Bootstrap" below. * A repository instantiated from the template gets the caller but no suite profile: the gate fails closed until a profile is added here. * Anyone with write access can post a `CI/gate` status by hand; the rulesets do not pin an integration. @@ -107,9 +112,9 @@ The reusable accepts `workflow_run`, `pull_request`, `schedule` and `workflow_di == Bootstrap -`workflow_run` and `schedule` run only from the default branch (and `workflow_dispatch` only for a workflow file that exists there). During bootstrap, the permanent `pull_request` path starts `gate-pr` from the pull request branch. It calls the reusable, waits within the configured budget for required checks, and publishes the required status on the pull request head (`CI/gate` for consumers, `CI / gate` for the suite). This lets a same-repository bootstrap pull request satisfy the gate before the caller reaches the default branch. +`workflow_run` and `schedule` run only from the default branch (and `workflow_dispatch` only for a workflow file that exists there). A `workflow_dispatch` run uses the workflow file of the ref it is started from, which can be any branch; the caller's `gate` job does nothing for a `workflow_dispatch` from a ref other than the default branch. That stops a mistaken manual run; it does not stop someone who can push from dispatching a branch that edits the file. During bootstrap, the permanent `pull_request` path starts `gate-pr` from the pull request branch. It calls the reusable, waits within the configured budget for required checks, and publishes the required status on the pull request head (`CI/gate` for consumers, `CI / gate` for the suite). This lets a same-repository bootstrap pull request satisfy the gate before the caller reaches the default branch. -The caller must grant `statuses: write`; a fork's or Dependabot's `pull_request` token cannot write statuses. The same-repository condition excludes forks, but does not grant a restricted token write access. Those pull requests depend on the default-branch `workflow_run` evaluator, which is unavailable until bootstrap is merged. After bootstrap, `workflow_run` evaluates later pull requests and reruns, including fork heads; `gate-pr` remains enabled for same-repository pull requests. Bootstrap does not make the pull request branch trusted: see "Tamper guard" below. +The caller must grant `statuses: write`; a fork's or Dependabot's `pull_request` token is read-only and cannot write statuses. `gate-pr` therefore excludes forks (same-repository condition) and Dependabot (`github.event.pull_request.user.login != 'dependabot[bot]'`, by pull request author; it only excludes a run and never grants one). Those pull requests depend on the default-branch `workflow_run` evaluator, which is unavailable until bootstrap is merged. After bootstrap, `workflow_run` evaluates later pull requests and reruns, including fork heads; `gate-pr` remains enabled for same-repository pull requests. Bootstrap does not make the pull request branch trusted: see "Tamper guard" below. == The suite gates itself @@ -117,7 +122,7 @@ The caller must grant `statuses: write`; a fork's or Dependabot's `pull_request` == The pull_request start -`workflow_run`, `schedule` and `workflow_dispatch` run only from the default branch, so on their own the gate can never run on the pull request that adds it, while a ruleset that requires the status blocks that very pull request. Every caller therefore also has a `gate-pr` job on `pull_request` (same-repository branches only: a fork's or Dependabot's `pull_request` token cannot write statuses; those are gated by the `workflow_run` job, which also re-evaluates after late workflows). It calls the same reusable and the same verdict; only the starting point and one wait differ. This start is permanent. +`workflow_run` and `schedule` run only from the default branch (and the caller's `gate` job ignores a `workflow_dispatch` started from any other ref), so on their own the gate can never run on the pull request that adds it, while a ruleset that requires the status blocks that very pull request. Every caller therefore also has a `gate-pr` job on `pull_request` (same-repository branches only, and not Dependabot's: a fork's or Dependabot's `pull_request` token cannot write statuses; those are gated by the `workflow_run` job, which also re-evaluates after late workflows). It calls the same reusable and the same verdict; only the starting point and one wait differ. This start is permanent. * The reusable resolves the head SHA from `github.event.pull_request.head.sha` (or `workflow_run.head_sha`); any other event is refused. * During bootstrap there is no default-branch `workflow_run` evaluator yet, and a `pull_request` run can start before the other workflows have created their runs. So `scripts/ci-gate-publish.sh` runs with `WAIT_SECONDS` (input `wait_minutes`, default 30, maximum 50 to reserve ten minutes of the 60-minute job for setup and final publication; `poll_seconds`, default 20): while the verdict only means "not finished" (`pending`, `never reported: ...`, `never completed: ...`) it polls without publishing the unfinished verdict, except that it replaces a success published by this invocation with pending if post-write verification detects changed runs. API calls and verdict evaluation count toward the elapsed wait budget; each sleep is capped at the time remaining. Completed-run jobs are cached within the publisher invocation while the run ID, attempt, status, conclusion and update time remain unchanged; active-run jobs are fetched on every poll. Before sleeping, the publisher reads the core API quota and increases the poll delay to spread estimated request costs over the reset window, reserving quota for final status publication. A real failure, and success, are written at once. When the wait is used up, `pending` becomes `failure: gave up after N min: waiting for ...`; `never reported` already names what is missing. The verdict script is unchanged; the wait keys on its descriptions, which `tests/ci-gate.sh` pins. @@ -126,20 +131,33 @@ The caller must grant `statuses: write`; a fork's or Dependabot's `pull_request` == Tamper guard -Because the `pull_request` job runs from the pull request's own branch, a pull request can edit the gate and pass itself. The tamper guard makes that visible: `.github/workflows/ci-gate-tamper-guard.yml` (reusable), called from a workflow on `pull_request_target`, which GitHub runs from the DEFAULT branch, so the pull request cannot edit the guard that judges it. It never checks out or runs pull request code. It reads the changed files (`previous_filename` of a rename included), the label events and the commit dates through the API (permissions `pull-requests: read`, `contents: read`; no secrets) and fetches its one script, `scripts/ci-gate-tamper-guard.sh`, from the suite at the pinned commit. +The `pull_request` job (`gate-pr`) runs the caller from the pull request's own branch, so a pull request can edit the gate and pass itself on that path. The tamper guard makes such a change visible, and it is part of the gate's own verdict: no second status context, so no ruleset change. -*Gate files:* `.github/workflows/ci-gate*.yml` and `.yaml` (callers, reusable, guard callers), `scripts/check-required-contexts.sh`, `scripts/ci-gate-*.sh`, `scripts/validate-ci-gate-profile.sh`, `templates/ci-gate*.yml`, `profiles/ci-gate/**`. A pull request that touches one fails the check `guard / check` unless the owner has applied the label `gate-change-approved` AFTER the pull request's newest commit. +*Where it runs.* Before the verdict, `scripts/ci-gate-publish.sh` runs `scripts/ci-gate-tamper-guard.sh` (fetched from the suite at `job.workflow_sha`, like the other scripts) for every OPEN, SAME-REPOSITORY pull request whose head is the evaluated commit: -*Approval, and who may give it.* The label is the owner's act. *Agents must never apply it.* It is re-checked on `labeled`, `unlabeled` and `synchronize`. The label is valid only if (a) its latest label event is `labeled`, (b) the actor of that event holds `admin` on the repository (`GET repos/{repo}/collaborators/{login}/permission` answers `.permission == "admin"`; a write or maintain actor, a deleted account, a bot, an unreadable or unexpected answer all refuse, and the check fails closed), and (c) that event is later than the newest commit date of the pull request, so the owner re-applies it after every push. The label name is the single `APPROVAL_LABEL` default in `scripts/ci-gate-tamper-guard.sh` (`gate-change-approved`; the owner has yet to confirm the final name); this document and the templates repeat it, and `tests/ci-gate-tamper-guard.sh` fails if they drift. Not verified live: that the `pull_request_target` token with `pull-requests: read` and `contents: read` may read the collaborator permission endpoint; if it may not, the guard fails closed for every gate-file pull request until the permission is granted. +* `workflow_run`: the pull requests in `github.event.workflow_run.pull_requests` whose `head.sha` is the commit and whose head and base repository ids agree, each confirmed open, same-repository and still at that head with `GET pulls/{n}`; if none is left, `GET commits/{sha}/pulls`, kept if open, same-repository and headed by that commit; +* `schedule` / `workflow_dispatch` (the sweep): the same-repository pull requests the sweep already listed for that head (no extra lookup); +* `pull_request` (`gate-pr`): its own number. -*The limit, stated plainly.* A commit date is written by the pusher, and GitHub gives a read-only job no reliable push time, so a deliberate backdating or a force-push of older commits can defeat the comparison. And all agents act with the owner's account, so the label cannot tell the owner from an agent. This guard is tamper-EVIDENT and deliberate, not tamper-proof. A review-based approval is impossible because the owner cannot approve their own pull requests. +The per-pull-request calls (changed files, label events, the labeller's permission, commit dates) are made only for a matched pull request; a commit that heads no open pull request costs the one lookup on `workflow_run` and nothing on a sweep. The guard never checks out or runs pull request code. -*Stronger form (proposed, not built).* Require commits that touch gate files to be signed by the owner's own key once the separate agent signing key exists, and have the guard verify the signer of each such commit from the API's `verification` data. +*Protected paths.* `.github/workflows/ci-gate*.yml` and `.yaml` (callers, reusable, the deprecated guard), `scripts/check-required-contexts.sh`, `scripts/ci-gate-*.sh`, `scripts/validate-ci-gate-profile.sh`, `templates/ci-gate*.yml`, `profiles/ci-gate/**`, AND every `workflow` path named in that repository's profile (passed to the script as `EXTRA_PROTECTED_FILE`, exact paths, each validated against the profile's workflow-path rule). A rename counts through its old and its new name. The producer workflows are protected because a pull request could otherwise rewrite one into a no-op job with the same name and pass the gate; with the guard, that rewrite needs the owner's approval. It narrows that hole; it does not close it (A3 does). -*Listing it in the profile.* The check is `{job: "guard / check", workflow: ".github/workflows/ci-gate-tamper-guard.yml"}` (suite local caller: `.github/workflows/ci-gate-tamper-guard-caller.yml`). It is NOT in any shipped profile yet, for two reasons that the owner should weigh: a `pull_request_target` workflow runs only from the default branch, so on the pull request that adds the guard the entry would read `never reported` and the gate would fail its own introduction; and a `pull_request_target` run's `head_sha` is not shown to be the pull request head, so whether the gate's per-commit run listing sees it is unverified. List it after the guard is on main and one later pull request shows its run in `actions/runs?head_sha=`. +*Verdict.* A matched pull request that touches a protected path without approval makes the status `failure` at once, whatever the checks say: `gate files changed without owner approval: ` (clipped to 140 characters). With approval, the normal verdict stands. Any API error of the guard or of the lookup is "no verdict": `failure`, a red job, `ci-gate: tamper guard could not check PR #` (fail closed). + +*Approval, and who may give it.* The label `gate-change-approved`. The label is the owner's act. *Agents must never apply it.* The label is valid only if (a) its latest label event is `labeled`, (b) the actor of that event holds `admin` on the repository (`GET repos/{repo}/collaborators/{login}/permission` answers `.permission == "admin"`; a write or maintain actor, a deleted account, a bot, an unreadable or unexpected answer all refuse, and the check fails closed), and (c) that event is later than the newest commit date of the pull request, so the owner re-applies it after every push. Applying or removing the label raises no `workflow_run` event: the next sweep (at most about 15 minutes) or any later workflow run re-evaluates the head, or the owner re-runs `gate-pr` or starts `workflow_dispatch` on the default branch. The label name is the single `APPROVAL_LABEL` default in `scripts/ci-gate-tamper-guard.sh` (`gate-change-approved`); this document and the templates repeat it, and `tests/ci-gate-tamper-guard.sh` fails if they drift. + +*Which paths are trusted.* Only the default-branch paths: `workflow_run` and the sweep, whose caller, pin and profile a pull request cannot change. The `gate-pr` path runs the guard too, for early feedback, but that path is PR-controlled: a pull request can edit its own caller to drop the guard (for example by pinning another reusable). Its status is then overwritten by the next default-branch evaluation of the same head (last-writer-wins, "Residual limit"). + +*Not guarded.* A fork pull request is not matched (the event and the lookup keep same-repository heads only). Its `gate-pr` never runs, and the default-branch evaluations judge it with the default branch's caller and the pinned suite, so a fork cannot change the gate that judges it; but a fork pull request that edits gate files or producer workflows is not flagged by the guard, and merging it changes them. Review fork pull requests that touch those paths by hand. + +*The limit, stated plainly.* A commit date is written by the pusher, and GitHub gives a read-only job no reliable push time, so a deliberate backdating or a force-push of older commits can defeat the comparison. And all agents act with the owner's account, so the label cannot tell the owner from an agent. This guard is tamper-EVIDENT and deliberate, not tamper-proof. A review-based approval is impossible because the owner cannot approve their own pull requests. Not verified live: that the gate's token (`pull-requests: read`, `contents: read`) may read the label events and the collaborator permission endpoint; if it may not, the guard fails closed (no verdict) for every pull request that touches a protected path. + +*Long-term fix.* The A3 signed gate (owner ruling, 2026-11-23). Proposed meanwhile, not built: require commits that touch gate files to be signed by the owner's own key once the separate agent signing key exists, and have the guard verify the signer from the API's `verification` data. + +*The retired `pull_request_target` guard.* `.github/workflows/ci-gate-tamper-guard.yml` (reusable) and `templates/ci-gate-tamper-guard-caller.yml` are DEPRECATED. They never started: the account's Actions policy answers "Event 'pull_request_target' is not allowed to trigger Actions workflows.", and every guard run in rsr-template-repo (30/30), resource-algebra (50/50) and this suite (30/30) ended in `startup_failure`. The suite's own caller (`.github/workflows/ci-gate-tamper-guard-caller.yml`) is removed. The reusable stays while consumers reference it. A later pass, per consumer: delete `.github/workflows/ci-gate-tamper-guard.yml` (the `pull_request_target` caller) and its `actions.lock` entry, re-pin `ci-gate.yml` to a suite commit that contains this guard, and take the new caller text from `templates/ci-gate-caller.yml`; once no consumer references the reusable, delete it, its template and its lock-scope entry. == What the owner must do once per repository -. Merge the pull request that adds the gate. The `gate-pr` job posts the status on it, so no ruleset edit is needed. If the pull request also touches gate files, the guard (once on main) will ask for the label. -. Apply the label `gate-change-approved` (create it once, colour free) to a pull request that touches gate files, after its newest commit, when you have read the change. Not an agent. -. After the guard workflow is on main, confirm on a later pull request that `guard / check` appears under `actions/runs?head_sha=`, then add the profile entry above (a suite change that needs the label itself). +. Merge the pull request that adds the gate. The `gate-pr` job posts the status on it, so no ruleset edit is needed. If the pull request touches gate files or a profiled producer workflow, the gate asks for the label. +. Apply the label `gate-change-approved` (create it once, colour free) to a pull request that touches a protected path, after its newest commit, when you have read the change. Not an agent. Then wait for the next sweep, or re-run `gate-pr`. diff --git a/scripts/ci-gate-publish.sh b/scripts/ci-gate-publish.sh index 61aec56e..089f69fa 100644 --- a/scripts/ci-gate-publish.sh +++ b/scripts/ci-gate-publish.sh @@ -18,10 +18,13 @@ # CI_GATE_SLEEP test hook: the sleep command # GITHUB_STEP_SUMMARY, GITHUB_OUTPUT optional; `published=true` is written # once a verdict status was posted +# GUARD_PRS GUARD_EVENT_PRS which pull requests the tamper guard checks (step a. below) # # (The `pending` "re-run started" write for an in_progress event is the FIRST STEP of the # workflow, before any suite file is read; this script posts only verdicts.) # +# a. Once, before any round: the tamper guard for each open same-repository pull request headed by +# HEAD_SHA (scripts/ci-gate-tamper-guard.sh). Not approved: failure at once. Error: no verdict. # Order of work, each round (5 rounds, or the pull_request elapsed wait deadline): # b. Snapshot the workflow runs of the SHA, fingerprint them (id, status, conclusion, # run_attempt, updated_at of every run but the gate's own), read the jobs, run the verdict. @@ -117,6 +120,78 @@ write_summary() { # } >> "${GITHUB_STEP_SUMMARY:-/dev/null}" } +# a. Tamper guard, folded into this verdict (docs/CI-GATE.adoc, "Tamper guard"). For every OPEN, +# SAME-REPOSITORY pull request whose head is HEAD_SHA, run scripts/ci-gate-tamper-guard.sh with the +# profile's producer workflows as extra protected paths. A pull request that touches a protected path +# without the owner's approval makes the verdict `failure` at once, whatever the checks say. Any error +# of the guard (or of finding the pull requests) is "no verdict" (die). Which pull requests: +# GUARD_PRS set (even empty): these numbers, already listed open and same-repository by the +# caller (the sweep; gate-pr passes its own number). No lookup. +# GUARD_EVENT_PRS else, the workflow_run event's pull_requests (JSON): entries whose head.sha is +# HEAD_SHA and whose head and base repository ids agree, each confirmed open, +# same-repository and still at HEAD_SHA by GET pulls/. +# neither, or no entry left: GET commits//pulls, kept if open, same-repository, head = HEAD_SHA. +# The guard's per-pull-request calls (files, label events, permission, commits) are made only for a +# matched pull request; a SHA that heads no open pull request costs at most the one lookup. +GUARD="$SUITE/scripts/ci-gate-tamper-guard.sh" +[[ -f $GUARD ]] || die 'the tamper guard script is missing from the suite' +guard_prs=() +if [[ -n ${GUARD_PRS+x} ]]; then + for n in $GUARD_PRS; do + [[ $n =~ ^[1-9][0-9]{0,9}$ ]] || die 'GUARD_PRS holds something that is not a pull request number' + guard_prs+=("$n") + done +else + if [[ -n ${GUARD_EVENT_PRS:-} && $GUARD_EVENT_PRS != null ]]; then + hints=$(jq -r --arg sha "$HEAD_SHA" 'if type == "array" then .[] | select(type == "object" and .head.sha == $sha and .head.repo.id != null and .head.repo.id == .base.repo.id) | .number | tostring else error("not an array") end' <<< "$GUARD_EVENT_PRS") \ + || die 'the workflow_run pull request list is malformed' + for n in $hints; do + [[ $n =~ ^[1-9][0-9]{0,9}$ ]] || die 'the workflow_run pull request list has a malformed number' + pr=$(gh api "repos/$REPO/pulls/$n" --jq '[.state, .head.sha, (.head.repo.full_name // "")] | @tsv') \ + || die "could not read pull request #$n for the tamper guard" + IFS=$' ' read -r pstate psha prepo <<< "$pr" + [[ $pstate == open && $psha == "$HEAD_SHA" && $prepo == "$REPO" ]] && guard_prs+=("$n") + done + fi + if ((${#guard_prs[@]} == 0)); then + found=$(gh api --paginate "repos/$REPO/commits/$HEAD_SHA/pulls?per_page=100" --jq '.[] | [.number, .state, .head.sha, (.head.repo.full_name // "")] | @tsv') \ + || die 'could not list the pull requests of this commit for the tamper guard' + while IFS=$' ' read -r n pstate psha prepo; do + [[ -n $n ]] || continue + [[ $n =~ ^[1-9][0-9]{0,9}$ ]] || die 'a pull request of this commit has a malformed number' + [[ $pstate == open && $psha == "$HEAD_SHA" && $prepo == "$REPO" ]] && guard_prs+=("$n") + done <<< "$found" + fi +fi +if ((${#guard_prs[@]} > 0)); then + jq -r '.checks[].workflow' "$PROFILE" | LC_ALL=C sort -u > "$WORK/guard-protected.txt" \ + || die 'could not list the profile workflows for the tamper guard' + guard_touched=() + for n in $(printf '%s +' "${guard_prs[@]}" | sort -un); do + gout=$(env -u APPROVAL_LABEL REPO="$REPO" PR_NUMBER="$n" EXTRA_PROTECTED_FILE="$WORK/guard-protected.txt" bash "$GUARD" 2>&1) + grc=$? + printf '%s +' "$gout" | sed "s/^/tamper guard PR #$n: /" + ((grc == 0)) && continue + grep -qx 'guard-result=unapproved' <<< "$gout" \ + || die "tamper guard could not check PR #$n" + guard_touched+=("$(sed -n 's/^guard-touched=//p' <<< "$gout" | head -n 1)") + done + if ((${#guard_touched[@]} > 0)); then + state=failure + description="gate files changed without owner approval: $(printf '%s +' "${guard_touched[@]}" | tr ',' ' +' | LC_ALL=C sort -u | grep . | paste -sd, -)" + write_summary "$state" "$description" 0 + post "$state" "$description" || die 'could not publish the status' + finish_output + echo "$CONTEXT = $state: $(clip "$description")" + echo "::error::$CONTEXT failed: $description" + exit 1 + fi +fi + clock_now() { "${CI_GATE_CLOCK:-date}" +%s; } deadline=$(( $(clock_now) + WAIT_SECONDS )) wait_again() { diff --git a/scripts/ci-gate-sweep.sh b/scripts/ci-gate-sweep.sh index b36b3b08..3da7e37e 100644 --- a/scripts/ci-gate-sweep.sh +++ b/scripts/ci-gate-sweep.sh @@ -20,7 +20,10 @@ # 2. De-duplicates the head SHAs. Above the cap (100) it keeps the most recently updated and # prints a ::warning:: naming how many were skipped. The default branch head counts as the # most recently updated. It never skips silently. -# 3. Runs the publisher for each SHA, with no early in_progress pending. A failure on one SHA +# 3. Runs the publisher for each SHA, with no early in_progress pending. It passes the publisher +# GUARD_PRS: the open SAME-REPOSITORY pull requests headed by that SHA (from the listing above), so +# the publisher runs the tamper guard for exactly those, with no lookup of its own; a fork head and +# the default branch head (unless a pull request shares it) get none. A failure on one SHA # does not stop the others, except "rate limited, no verdict": the rest would meet the same # limit, so they are listed as not evaluated and the next sweep takes them. # 4. Writes a table (SHA, source, state, description) to the step summary and exits non-zero if @@ -48,6 +51,7 @@ TAB=$'\t' errors=0 rows="$WORK/rows.tsv"; : > "$rows" # shasourcestatedescription cand="$WORK/candidates.tsv"; : > "$cand" # updated_atshasource +guardprs="$WORK/guard-prs.tsv"; : > "$guardprs" # shanumber of each open same-repository pull request # 1. the default branch head, first: it sorts above every pull request branch=$(gh api "repos/$REPO" --jq .default_branch 2> /dev/null) || branch='' @@ -66,10 +70,12 @@ fi # open pull requests, every page if gh api --paginate "repos/$REPO/pulls?state=open&per_page=100" \ - --jq '.[] | [.updated_at, .head.sha, "PR #\(.number)"] | @tsv' > "$WORK/pulls.tsv" 2> "$WORK/pulls.err"; then - while IFS=$'\t' read -r upd sha src; do + --jq '.[] | [.updated_at, .head.sha, "PR #\(.number)", .number, (.head.repo.full_name // "")] | @tsv' > "$WORK/pulls.tsv" 2> "$WORK/pulls.err"; then + while IFS=$'\t' read -r upd sha src num hrepo; do if [[ $sha =~ ^[0-9a-f]{40}$ && -n $upd ]]; then printf '%s\t%s\t%s\n' "$upd" "$sha" "$src" >> "$cand" + # tamper guard: same-repository pull requests only (a fork head is not guarded; docs/CI-GATE.adoc) + if [[ $hrepo == "$REPO" && $num =~ ^[1-9][0-9]{0,9}$ ]]; then printf '%s\t%s\n' "$sha" "$num" >> "$guardprs"; fi else echo "::error::ci-gate-sweep: $src has an unusable head SHA or date; it was NOT evaluated" printf '%s\t%s\terror\tunusable head SHA\n' '-' "$src" >> "$rows" @@ -100,7 +106,8 @@ while IFS=$'\t' read -r _ sha src; do dir="$WORK/sha-$n"; mkdir -p "$dir" echo "::group::$CONTEXT for $sha ($src)" rc=0 - env -u GITHUB_OUTPUT HEAD_SHA="$sha" WORK="$dir/work" GITHUB_STEP_SUMMARY="$dir/summary.md" \ + prs=$(awk -F'\t' -v s="$sha" '$1 == s { print $2 }' "$guardprs" | sort -un | paste -sd' ' -) + env -u GITHUB_OUTPUT -u GUARD_EVENT_PRS GUARD_PRS="$prs" HEAD_SHA="$sha" WORK="$dir/work" GITHUB_STEP_SUMMARY="$dir/summary.md" \ SERVER_URL="$SERVER_URL" RUN_ID="$RUN_ID" WF_REPO="$WF_REPO" WF_SHA="$WF_SHA" \ bash "$PUBLISH" > "$dir/out.txt" 2>&1 || rc=$? cat "$dir/out.txt" diff --git a/scripts/ci-gate-tamper-guard.sh b/scripts/ci-gate-tamper-guard.sh index 1b1f2851..4d47057c 100755 --- a/scripts/ci-gate-tamper-guard.sh +++ b/scripts/ci-gate-tamper-guard.sh @@ -4,9 +4,17 @@ # ci-gate-tamper-guard.sh - fail a pull request that touches the gate's own files unless the owner # approved that change. Reads metadata through `gh` only; never checks out or runs pull request code. # +# Called per pull request by scripts/ci-gate-publish.sh (the gate's own verdict: docs/CI-GATE.adoc, +# "Tamper guard"), and by the deprecated pull_request_target reusable ci-gate-tamper-guard.yml. +# # Environment (all through env:, never interpolated into a script): # REPO PR_NUMBER what to inspect # APPROVAL_LABEL default gate-change-approved +# EXTRA_PROTECTED_FILE optional: a file of further protected paths, one EXACT path per line (no +# glob), each a plain file under .github/workflows (^\.github/workflows/ +# [A-Za-z0-9_.-]+\.ya?ml$, the profile's own workflow-path rule). The publisher +# writes the profile's producer workflows here. Blank lines are ignored; any +# other line, or an unreadable file, is an error (fail closed). # # Protected files (a rename counts through both its old and its new name): PROTECTED=( @@ -18,6 +26,7 @@ PROTECTED=( 'templates/ci-gate*.yml' 'profiles/ci-gate/*' ) +EXTRA=() # exact paths from EXTRA_PROTECTED_FILE # # Approval = the label is on the pull request NOW (its latest labeled/unlabeled event is `labeled`), # the actor of that labeled event holds `admin` on the repository (GET collaborators/{login}/permission, @@ -29,10 +38,24 @@ PROTECTED=( # THE LABEL: it is the owner's act (docs/CI-GATE.adoc, "Tamper guard"). # # Exit 0: no gate file touched, or approved. Exit 1: not approved, and EVERY error (fail closed). +# Stdout, for the publisher: a refusal that is a VERDICT (gate files touched, not approved) prints +# `guard-result=unapproved` and `guard-touched=`; an error (no verdict) prints +# neither, so the caller can tell "not approved" from "could not check". set -uo pipefail APPROVAL_LABEL=${APPROVAL_LABEL:-gate-change-approved} fail() { echo "::error::gate tamper guard: $1"; exit 1; } +deny() { echo "guard-result=unapproved"; echo "guard-touched=$list"; fail "$1"; } + +if [[ -n ${EXTRA_PROTECTED_FILE:-} ]]; then + [[ -f $EXTRA_PROTECTED_FILE && -r $EXTRA_PROTECTED_FILE ]] || fail 'EXTRA_PROTECTED_FILE is not a readable file' + while IFS= read -r x || [[ -n $x ]]; do + [[ -n $x ]] || continue + [[ $x =~ ^\.github/workflows/[A-Za-z0-9_.-]+\.ya?ml$ ]] \ + || fail 'EXTRA_PROTECTED_FILE has a line that is not a plain .github/workflows/*.yml path' + EXTRA+=("$x") + done < "$EXTRA_PROTECTED_FILE" +fi protected() { # -> 0 if it is a gate file local f=$1 p @@ -40,6 +63,9 @@ protected() { # -> 0 if it is a gate file # shellcheck disable=SC2053 [[ $f == $p ]] && return 0 done + for p in "${EXTRA[@]}"; do + [[ $f == "$p" ]] && return 0 + done return 1 } @@ -75,7 +101,7 @@ latest=$(jq -rs --arg l "$APPROVAL_LABEL" ' map(select(.label == $l)) | sort_by(.at) | if length == 0 then "" else last | if .event == "labeled" then [.at, .actor] | @tsv else "" end end' <<< "$events") \ || fail 'could not evaluate the label events' if [[ -z $latest ]]; then - fail "this pull request touches gate files ($list) and the label '$APPROVAL_LABEL' is not applied. Only the repository owner may apply it; agents must not." + deny "this pull request touches gate files ($list) and the label '$APPROVAL_LABEL' is not applied. Only the repository owner may apply it; agents must not." fi IFS=$'\t' read -r label_at actor <<< "$latest" [[ -n $label_at ]] || fail 'the label event has no time' @@ -83,11 +109,11 @@ IFS=$'\t' read -r label_at actor <<< "$latest" # The actor of the latest labeled event must hold admin. The login is validated before it is put into # a URL; a missing actor (a deleted account), a bot, an API error or an unexpected answer all refuse. [[ $actor =~ ^[A-Za-z0-9]([A-Za-z0-9-]{0,38})$ ]] \ - || fail "gate files are touched ($list); the actor of the latest '$APPROVAL_LABEL' event is missing or not a user login, so it cannot be shown to be an admin" + || deny "gate files are touched ($list); the actor of the latest '$APPROVAL_LABEL' event is missing or not a user login, so it cannot be shown to be an admin" perm=$(gh api "repos/$REPO/collaborators/$actor/permission" --jq '.permission') \ || fail "could not read the repository permission of '$actor'; no verdict" [[ $perm == admin ]] \ - || fail "gate files are touched ($list); '$APPROVAL_LABEL' was applied by '$actor' whose repository permission is '${perm:-none}', not admin. Only an admin's label counts." + || deny "gate files are touched ($list); '$APPROVAL_LABEL' was applied by '$actor' whose repository permission is '${perm:-none}', not admin. Only an admin's label counts." commits=$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/commits?per_page=100" --jq '.[] | .commit.committer.date') \ || fail 'could not read the pull request commits; no verdict' @@ -100,4 +126,4 @@ if (( applied > newest )); then echo "gate tamper guard: gate files touched ($list); '$APPROVAL_LABEL' applied by admin '$actor' after the newest commit; approved" exit 0 fi -fail "gate files are touched ($list) and '$APPROVAL_LABEL' was applied before the newest commit; the owner must re-apply it after every push." +deny "gate files are touched ($list) and '$APPROVAL_LABEL' was applied before the newest commit; the owner must re-apply it after every push." diff --git a/templates/ci-gate-caller.yml b/templates/ci-gate-caller.yml index e5c27e47..5b8abb3d 100644 --- a/templates/ci-gate-caller.yml +++ b/templates/ci-gate-caller.yml @@ -10,12 +10,15 @@ # (see rust-ci-caller.yml: `rust-ci / Cargo test`), which always contains # " / " and can never equal `CI/gate`. # -# It triggers on workflow_run, schedule and workflow_dispatch, all of which GitHub runs from the -# DEFAULT branch: a pull request cannot alter this file, its pin or its list. The consequence: -# the pull request that adds this caller can never receive `CI/gate` itself, and -# would be merged past the gate once (owner action) without the gate-pr job at the end. There is no -# pull_request start here except the gate-pr job at the end (docs/CI-GATE.adoc, "The pull_request start"), -# whose shape tests/ci-gate.sh asserts. +# workflow_run and schedule run from the DEFAULT branch: a pull request cannot alter this file, its pin +# or its list on those paths. workflow_dispatch runs the file of the ref it is started from, which can be +# any branch; the `gate` job therefore does nothing for a workflow_dispatch from a ref other than the +# default branch (its `if:`). That stops a mistaken manual run, not a branch that edits this file: anyone +# who can push can start a run of their own branch's copy. The consequence of the default-branch paths: +# the pull request that adds this caller can never receive `CI/gate` from them, and would be merged past +# the gate once (owner action) without the gate-pr job at the end. There is no pull_request start here +# except the gate-pr job at the end (docs/CI-GATE.adoc, "The pull_request start"), whose shape +# tests/ci-gate.sh asserts. # # `schedule` and `workflow_dispatch` run a SWEEP: the reusable lists the open pull requests and the # default branch head and re-evaluates each distinct head SHA with the same guarded publisher. A stale state @@ -28,6 +31,13 @@ # any active run makes the verdict pending, so a rerun replaces a stale success with pending, # approximating a native required check. `completed` then re-evaluates it (last-writer-wins; see docs/CI-GATE.adoc, "Residual limit"). # +# TAMPER GUARD: the gate's own verdict includes it. For an open same-repository pull request whose head +# is the evaluated commit, a change to a gate file or to a workflow named in the profile fails the +# status ("gate files changed without owner approval: ") until the OWNER applies the label +# `gate-change-approved` after the newest commit. AGENTS MUST NEVER APPLY THAT LABEL. Only the +# default-branch paths (workflow_run, schedule) are trusted; gate-pr runs the pull request's own copy of +# this file (docs/CI-GATE.adoc, "Tamper guard"). No separate pull_request_target guard is needed. +# # The required-check list is NOT in this repository: it lives in # proven-cicd-and-workflows/profiles/ci-gate//.json at the pinned # SHA below, selected by github.repository. A repository with no profile there @@ -37,10 +47,12 @@ # the account enforces sha_pinning_required. An A3 `estate-gate` replaces this # interim gate by changing ONE pin and ONE context (`with: context`) here. # -# ⚠ DE-ONBOARDED from actions.lock, deliberately, like the estate-audit and -# Rust CI callers: an onboarded cross-repo reusable startup-fails with zero -# jobs under sha_pinning_required. cicd-suite/scripts/deonboard-workflow.sh -# reverses a re-onboarding. +# actions.lock: list this file as an EMPTY file-level entry, +# '.github/workflows/ci-gate.yml': [] +# with no leaf record under it. GitHub's lockfile does not pin reusable-workflow calls: a leaf record +# for the `uses:` below fails `gh actions-lock` as "Unused lockfile entry", and no entry at all fails +# it as "not-pinned". This form is proven on trope-checker, echo-types, hermeneia and panic-attack +# (governance lockfile verify, `gh actions-lock --verify-local` coverage and CI integrity all pass). # # There is deliberately NO `concurrency:` block here: serialising per SHA would delay the # in_progress caller behind a running evaluation that then writes a stale success. The reusable's @@ -51,42 +63,50 @@ # few workflows, naming them (workflows: ["CI", "Lint"]) cuts the events; keep that list in step with # the profile (docs/CI-GATE.adoc, "API budget"). # +# Permissions: none at workflow level; each job grants exactly what the reusable asks for. # No `secrets:` line: the reusable consumes none. name: CI gate on: pull_request: - workflow_run: + workflow_run: # zizmor: ignore[dangerous-triggers] the gate never checks out or runs pull request code; it reads API metadata only workflows: ["**", "!CI gate"] types: [completed, in_progress] schedule: - cron: "7,22,37,52 * * * *" workflow_dispatch: {} -permissions: - statuses: write - actions: read - contents: read - pull-requests: read +permissions: {} jobs: gate: - if: github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.name != 'CI gate') + if: github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.name != 'CI gate') && (github.event_name != 'workflow_dispatch' || github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) + permissions: + statuses: write + actions: read + contents: read + pull-requests: read uses: hyperpolymath/proven-cicd-and-workflows/.github/workflows/ci-gate.yml@__CICD_SUITE_SHA__ # cicd-suite ci-gate with: context: "CI/gate" # timeout_minutes: 180 # how long a missing check keeps the gate pending - # The pull_request start. workflow_run, schedule and workflow_dispatch run only from the default - # branch, so without this job the pull request that adds or changes the gate never gets the status - # and a ruleset requiring it blocks that very pull request. This job runs from the pull request's own - # branch and posts the same verdict, waiting (bounded) for the checks named in the profile to report. - # Same-repository branches only: a fork's or Dependabot's pull_request token cannot write statuses, - # and those are covered by the workflow_run job. No trust decision uses github.actor. - # Because a pull request can edit this file, the Gate tamper guard (ci-gate-tamper-guard.yml, run from - # the default branch) fails a pull request that touches gate files unless the owner has approved it. + # The pull_request start. workflow_run and schedule run only from the default branch, so without this + # job the pull request that adds or changes the gate never gets the status and a ruleset requiring it + # blocks that very pull request. This job runs from the pull request's own branch and posts the same + # verdict, waiting (bounded) for the checks named in the profile to report. + # Same-repository branches only, and not Dependabot's: a fork's or Dependabot's pull_request token is + # read-only and cannot write statuses; the workflow_run job covers both. The Dependabot test only + # EXCLUDES a run (it can never grant anything), so it is not a trust decision; none uses github.actor. + # Because a pull request can edit this file, this path is PR-controlled: it runs the tamper guard for + # early feedback only. The trusted guard is the default-branch `gate` job above. gate-pr: - if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]' + permissions: + statuses: write + actions: read + contents: read + pull-requests: read uses: hyperpolymath/proven-cicd-and-workflows/.github/workflows/ci-gate.yml@__CICD_SUITE_SHA__ # cicd-suite ci-gate with: context: "CI/gate" diff --git a/templates/ci-gate-tamper-guard-caller.yml b/templates/ci-gate-tamper-guard-caller.yml index 74be948c..6137b935 100644 --- a/templates/ci-gate-tamper-guard-caller.yml +++ b/templates/ci-gate-tamper-guard-caller.yml @@ -1,4 +1,12 @@ # SPDX-License-Identifier: MPL-2.0 +# ⚠ DEPRECATED (2026-11-23). This guard has NEVER started: every run ends in startup_failure because +# the account Actions policy refuses its trigger with +# "Event 'pull_request_target' is not allowed to trigger Actions workflows." +# (rsr-template-repo 30/30, resource-algebra 50/50, this suite 30/30). The guard now runs INSIDE the +# gate's own verdict (ci-gate.yml -> scripts/ci-gate-publish.sh -> scripts/ci-gate-tamper-guard.sh; +# docs/CI-GATE.adoc, "Tamper guard"). Do not install it anywhere new. It is kept only while consumers +# still reference it; a later pass removes their pull_request_target caller, then this file. +# # Gate tamper guard - thin caller of the suite's reusable guard; copy to .github/workflows/ci-gate-tamper-guard.yml. pull_request_target runs this file from the # DEFAULT branch, so a pull request cannot edit it; the job never checks out or runs pull request code # (it reads the changed-file list through the API). The pin is a full SHA, never @main or a tag. diff --git a/tests/ci-gate-tamper-guard.sh b/tests/ci-gate-tamper-guard.sh index 35d14f38..b0ee377f 100644 --- a/tests/ci-gate-tamper-guard.sh +++ b/tests/ci-gate-tamper-guard.sh @@ -6,7 +6,6 @@ set -uo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" GUARD="$ROOT/scripts/ci-gate-tamper-guard.sh" WF="$ROOT/.github/workflows/ci-gate-tamper-guard.yml" -SELF="$ROOT/.github/workflows/ci-gate-tamper-guard-caller.yml" TPL="$ROOT/templates/ci-gate-tamper-guard-caller.yml" PASS=0; FAIL=0 ok() { printf ' ok %s\n' "$1"; PASS=$((PASS+1)); } @@ -141,9 +140,42 @@ reset; files .github/workflows/ci-gate.yml; events "labeled gate-change-approved chk "no commits listed: exit 1" "$RC" 1 chk "the guard never applies a label: it calls only read endpoints" "$(grep -c -- '-X \(POST\|PUT\|PATCH\|DELETE\)\|--method' "$GUARD")" 0 +echo "== extra protected paths: the profile's producer workflows (EXTRA_PROTECTED_FILE) ==" +printf '%s\n' .github/workflows/ci.yml '' .github/workflows/lint.yaml > "$WORK/extra.txt" +EXTRA_PROTECTED_FILE="$WORK/extra.txt" bash "$GUARD" --match .github/workflows/ci.yml > /dev/null && ok "--match: a listed producer workflow is protected" || bad "--match: a listed producer workflow is not protected" +EXTRA_PROTECTED_FILE="$WORK/extra.txt" bash "$GUARD" --match .github/workflows/lint.yaml > /dev/null && ok "--match: a listed .yaml producer is protected" || bad "--match: a listed .yaml producer is not protected" +EXTRA_PROTECTED_FILE="$WORK/extra.txt" bash "$GUARD" --match .github/workflows/ci.yml.bak .github/workflows/other.yml > /dev/null && bad "--match: an unlisted workflow is protected" || ok "--match: only exact listed paths (no prefix, no other workflow)" +bash "$GUARD" --match .github/workflows/ci.yml > /dev/null && bad "--match: a producer is protected without the list" || ok "--match: without the list a producer workflow is not a gate file" +EXTRA_PROTECTED_FILE="$WORK/extra.txt" bash "$GUARD" --match .github/workflows/ci-gate.yml > /dev/null && ok "--match: the globs still apply with a list" || bad "--match: the globs are lost with a list" +for badline in '.github/workflows/*.yml' 'src/x.yml' '.github/workflows/a/b.yml' '../.github/workflows/x.yml' '.github/workflows/x.yml ' '.github/workflows/x.sh'; do + printf '%s\n' "$badline" > "$WORK/badextra.txt" + OUT=$(EXTRA_PROTECTED_FILE="$WORK/badextra.txt" bash "$GUARD" --match .github/workflows/x.yml 2>&1); RC=$? + chk "a malformed list line '$badline' fails closed" "$RC/$(grep -c 'EXTRA_PROTECTED_FILE has a line' <<<"$OUT")" "1/1" +done +OUT=$(EXTRA_PROTECTED_FILE="$WORK/nope.txt" bash "$GUARD" --match x 2>&1); RC=$? +chk "a missing list file fails closed" "$RC/$(grep -c 'not a readable file' <<<"$OUT")" "1/1" +reset; files .github/workflows/ci.yml; run EXTRA_PROTECTED_FILE="$WORK/extra.txt" +chk "a PR touching a listed producer workflow, unlabelled: exit 1" "$RC" 1 +chk "that refusal is a verdict: guard-result and guard-touched lines" "$(grep -x 'guard-result=unapproved' <<<"$OUT")|$(grep '^guard-touched=' <<<"$OUT")" "guard-result=unapproved|guard-touched=.github/workflows/ci.yml" +reset; files .github/workflows/ci.yml; run +chk "the same PR without the list: exit 0 (the list is what widens the set)" "$RC" 0 +echo "== the result lines tell a verdict from an error ==" +reset; files scripts/ci-gate-publish.sh; events "$LBL dev"; run +chk "non-admin label: a verdict (guard-result=unapproved)" "$RC/$(grep -cx 'guard-result=unapproved' <<<"$OUT")" "1/1" +reset; files scripts/ci-gate-publish.sh; events "labeled gate-change-approved 2026-11-17T09:00:00Z boss"; run +chk "label before the newest commit: a verdict" "$RC/$(grep -cx 'guard-result=unapproved' <<<"$OUT")" "1/1" +reset; files scripts/ci-gate-publish.sh; events "$LBL none"; run +chk "no actor on the label event: a verdict" "$RC/$(grep -cx 'guard-result=unapproved' <<<"$OUT")" "1/1" +for k in files events perm commits; do + reset; files .github/workflows/ci-gate.yml; events "$LBL boss"; : > "$D/fail$k"; run + chk "API error ($k): exit 1 and NOT a verdict (no guard-result line)" "$RC/$(grep -c '^guard-result=' <<<"$OUT")" "1/0" +done +reset; files .github/workflows/ci-gate.yml; events "$LBL boss"; run +chk "approved: exit 0 and no guard-result line" "$RC/$(grep -c '^guard-result=' <<<"$OUT")" "0/0" + echo "== static guards ==" code() { grep -vE '^[[:space:]]*#' "$1"; } -for f in "$WF" "$SELF" "$TPL"; do +for f in "$WF" "$TPL"; do b=$(basename "$f") code "$f" | grep -qE 'actions/checkout|ref: *\$\{\{ *github\.(event\.pull_request\.head|head_ref)' && bad "$b checks out code" || ok "$b has no checkout" code "$f" | grep -qE 'github\.actor|actor\.login|sender\.login|user\.login' && bad "$b makes a decision on a forgeable actor field" || ok "$b has no actor-based trust decision" @@ -155,7 +187,7 @@ code "$WF" | grep -qE '^ pull-requests: read' && code "$WF" | grep -qE '^ ! grep -qE '^[[:space:]]*(- )?uses:' "$WF" && ok "the reusable uses no actions" || bad "the reusable has a uses: line" grep -q 'pull_request_target' <(sed -n '/Refuse anything but/,/Read the guard script/p' "$WF") && ok "the reusable refuses every event but pull_request_target" || bad "the reusable does not refuse other events" code "$WF" | grep -qE '^ check:' && code "$WF" | grep -qE '^ name: check$' && ok "the reusable job is check (the gate profile entry is 'guard / check')" || bad "the reusable job is not named check" -for f in "$SELF" "$TPL"; do +for f in "$TPL"; do b=$(basename "$f") code "$f" | grep -qE '^ pull_request_target:' && code "$f" | grep -qE '^ types: \[opened, reopened, synchronize, edited, labeled, unlabeled\]' && ok "$b: pull_request_target with all six types" || bad "$b: wrong trigger or types" code "$f" | grep -qE '^ pull-requests: read' && code "$f" | grep -qE '^ contents: read' && ! code "$f" | grep -qE '^ [a-z-]+: write' && ok "$b: read-only permissions" || bad "$b: permissions not minimal" @@ -176,11 +208,15 @@ refuse hyperpolymath/proven-cicd-and-workflows && ok "the reusable accepts the s refuse example/.github && ok "the reusable accepts a workflow repository named .github" || bad "the reusable rejects example/.github" for r in a/b/c /x a/ a/. a/.. "" notacoordinate; do refuse "$r" && bad "the reusable accepts the workflow repository '$r'" || ok "the reusable rejects the workflow repository '$r'"; done code "$TPL" | grep -qE 'uses: hyperpolymath/proven-cicd-and-workflows/\.github/workflows/ci-gate-tamper-guard\.yml@__CICD_SUITE_SHA__' && ok "the template pins the reusable at the placeholder" || bad "the template does not use the placeholder" -code "$SELF" | grep -qE '^ uses: \./\.github/workflows/ci-gate-tamper-guard\.yml$' && ok "the suite's caller uses the local reusable" || bad "the suite's caller does not use the local reusable" -for b in ci-gate-tamper-guard.yml ci-gate-tamper-guard-caller.yml; do - jq -e --arg p ".github/workflows/$b" 'any(.workflows[]; .path == $p)' "$ROOT/config/workflow-lock-scope.json" >/dev/null && ok "lock scope lists $b" || bad "lock scope lacks $b" +[ ! -e "$ROOT/.github/workflows/ci-gate-tamper-guard-caller.yml" ] && ok "the suite's own pull_request_target caller is removed (it never started)" || bad "the suite still has its pull_request_target guard caller" +jq -e 'any(.workflows[]; .path == ".github/workflows/ci-gate-tamper-guard.yml")' "$ROOT/config/workflow-lock-scope.json" >/dev/null && ok "lock scope still lists the deprecated reusable (consumers reference it)" || bad "lock scope lacks ci-gate-tamper-guard.yml" +! jq -e 'any(.workflows[]; .path == ".github/workflows/ci-gate-tamper-guard-caller.yml")' "$ROOT/config/workflow-lock-scope.json" >/dev/null && ok "lock scope no longer lists the removed caller" || bad "lock scope still lists the removed caller" +for f in "$WF" "$TPL"; do + b=$(basename "$f") + grep -q 'DEPRECATED' "$f" && grep -qF "Event 'pull_request_target' is not allowed to trigger Actions workflows." "$f" \ + && ok "$b is marked deprecated and quotes the policy error" || bad "$b is not marked deprecated with the policy error" done -for f in "$WF" "$SELF" "$TPL"; do +for f in "$WF" "$TPL"; do b=$(basename "$f") [ -z "$(awk ' function ind(s) { match(s, /^ */); return RLENGTH } @@ -196,7 +232,7 @@ echo "== the approval label name: one default, said the same everywhere ==" chk "the default is defined exactly once, in the script" "$(grep -c 'APPROVAL_LABEL:-' "$GUARD")" 1 DEFAULT_LABEL=$(sed -n 's/^APPROVAL_LABEL=\${APPROVAL_LABEL:-\([^}]*\)}$/\1/p' "$GUARD") chk "the script's default label" "$DEFAULT_LABEL" gate-change-approved -for f in "$WF" "$SELF" "$TPL" "$ROOT/templates/ci-gate-caller.yml" "$ROOT/.github/workflows/ci-gate-caller.yml" "$ROOT/docs/CI-GATE.adoc"; do +for f in "$WF" "$TPL" "$ROOT/templates/ci-gate-caller.yml" "$ROOT/.github/workflows/ci-gate-caller.yml" "$ROOT/docs/CI-GATE.adoc"; do b=$(basename "$f") others=$(grep -oE '[a-z]+(-[a-z]+)*-approved\b' "$f" | sort -u | grep -vxF "$DEFAULT_LABEL" || true) [ -z "$others" ] && ok "$b names no approval label but the default" || bad "$b names another approval label: $others" diff --git a/tests/ci-gate.sh b/tests/ci-gate.sh index 90a036e2..4dcc4fd5 100644 --- a/tests/ci-gate.sh +++ b/tests/ci-gate.sh @@ -240,7 +240,7 @@ echo "== publisher: fake gh, settle guard, status writes ==" PUBLISH="$ROOT/scripts/ci-gate-publish.sh" SUITE_DIR="$WORK/suite"; FAKEGH="$WORK/stub" mkdir -p "$SUITE_DIR/scripts" "$SUITE_DIR/profiles/ci-gate/example" "$FAKEGH/bin" -cp "$ROOT"/scripts/ci-gate-verdict.sh "$ROOT"/scripts/validate-ci-gate-profile.sh "$PUBLISH" "$SUITE_DIR/scripts/" +cp "$ROOT"/scripts/ci-gate-verdict.sh "$ROOT"/scripts/validate-ci-gate-profile.sh "$ROOT"/scripts/ci-gate-tamper-guard.sh "$PUBLISH" "$SUITE_DIR/scripts/" cp "$ROOT"/profiles/ci-gate/validate.jq "$ROOT"/profiles/ci-gate/select-runs.jq "$SUITE_DIR/profiles/ci-gate/" cp "$FX/profile.json" "$SUITE_DIR/profiles/ci-gate/example/repo.json" cat > "$FAKEGH/bin/gh" <<'FAKEGH_EOF' @@ -306,6 +306,31 @@ case $args in id=${args#*actions/runs/}; id=${id%%/*} echo "$id" >> "$D/jobs.calls" jq -c --argjson id "$id" '.[] | select(.run.id == $id) | del(.run)' "$R/jobs.json" ;; + # Tamper guard calls. G=$D/guard: prs.json (GET commits//pulls), pr..json (GET pulls/), + # files..json, events..json, commits..json, perms.json; fail. injects an error. + # Every guard call is logged to guard.calls (one kind per line). + *"/commits/"*"/pulls?per_page=100"*) + echo lookup >> "$D/guard.calls"; [[ ! -f $D/guard/fail.lookup ]] || { echo "gh: HTTP 500 (lookup)" >&2; exit 1; } + jq -r "$jqarg" "$D/guard/prs.json" 2>/dev/null || jq -r "$jqarg" <<< '[]' ;; + *"/pulls/"*"/files"*) + n=${args#*/pulls/}; n=${n%%/*}; echo "files $n" >> "$D/guard.calls" + [[ ! -f $D/guard/fail.files ]] || { echo "gh: HTTP 500 (files)" >&2; exit 1; } + jq -c "$jqarg" "$D/guard/files.$n.json" ;; + *"/issues/"*"/events"*) + n=${args#*/issues/}; n=${n%%/*}; echo "events $n" >> "$D/guard.calls" + [[ ! -f $D/guard/fail.events ]] || { echo "gh: HTTP 500 (events)" >&2; exit 1; } + jq -c "$jqarg" "$D/guard/events.$n.json" ;; + *"/collaborators/"*"/permission"*) + u=${args#*/collaborators/}; u=${u%%/*}; echo "perm $u" >> "$D/guard.calls" + p=$(jq -r --arg u "$u" '.[$u] // empty' "$D/guard/perms.json") && [[ -n $p ]] || { echo "gh: HTTP 404" >&2; exit 1; } + echo "$p" ;; + *"/pulls/"*"/commits"*) + n=${args#*/pulls/}; n=${n%%/*}; echo "commits $n" >> "$D/guard.calls" + jq -r "$jqarg" "$D/guard/commits.$n.json" ;; + *"/pulls/"[0-9]*" --jq"*) + n=${args#*/pulls/}; n=${n%% *}; echo "pr $n" >> "$D/guard.calls" + [[ ! -f $D/guard/fail.pr ]] || { echo "gh: HTTP 500 (pr)" >&2; exit 1; } + jq -r "$jqarg" "$D/guard/pr.$n.json" ;; *"/pulls?state=open"*) [[ ! -f $D/failpulls ]] || { echo "gh: HTTP 500 (pulls)" >&2; exit 1; } jq -r "$jqarg" "$D/pulls.json" ;; @@ -323,7 +348,7 @@ SHA=$(printf 'a%.0s' $(seq 40)) snap() { # -> runs.n.json jq -c "$2" "$FX/workflow-runs.json" > "$FAKEGH/runs.$1.json" } -pubreset() { rm -rf "$FAKEGH/by" "$FAKEGH/cursha" "$FAKEGH/pulls.json" "$FAKEGH/default_branch" "$FAKEGH/default_sha" "$FAKEGH/failpulls" "$FAKEGH/faildefault"; rm -f "$FAKEGH"/runs.*.json "$FAKEGH/prepost" "$FAKEGH"/fail.* "$FAKEGH"/failjobs "$FAKEGH"/failpost "$FAKEGH/posts.log" "$FAKEGH/runs.count" "$FAKEGH/status.log" "$FAKEGH/status.reads" "$FAKEGH/failstatus" "$FAKEGH/badstatus" "$FAKEGH/ratelimit" "$FAKEGH/attempts.log" "$FAKEGH/rl.sleeps" "$WORK/gho"; cp "$FX/jobs.json" "$FAKEGH/jobs.json"; } +pubreset() { rm -rf "$FAKEGH/guard" "$FAKEGH/guard.calls" "$FAKEGH/by" "$FAKEGH/cursha" "$FAKEGH/pulls.json" "$FAKEGH/default_branch" "$FAKEGH/default_sha" "$FAKEGH/failpulls" "$FAKEGH/faildefault"; rm -f "$FAKEGH"/runs.*.json "$FAKEGH/prepost" "$FAKEGH"/fail.* "$FAKEGH"/failjobs "$FAKEGH"/failpost "$FAKEGH/posts.log" "$FAKEGH/runs.count" "$FAKEGH/status.log" "$FAKEGH/status.reads" "$FAKEGH/failstatus" "$FAKEGH/badstatus" "$FAKEGH/ratelimit" "$FAKEGH/attempts.log" "$FAKEGH/rl.sleeps" "$WORK/gho"; cp "$FX/jobs.json" "$FAKEGH/jobs.json"; } publish() { # [VAR=value ...] -> RC, NPOSTS, POSTS (statedescription lines), CALLS (runs fetches) : > "$FAKEGH/jobs.calls" : > "$FAKEGH/posts.log"; rm -f "$FAKEGH/runs.count"; rm -rf "$WORK/pw" @@ -419,6 +444,77 @@ pubreset; snap 1 "$DONE"; publish HEAD_SHA=abc chk "a head SHA that is not 40 hex: exit 1, no POST" "$RC/$NPOSTS" "1/0" pubreset +echo "== tamper guard folded into the verdict (publisher) ==" +# g_pr [state]: an entry of GET commits//pulls and GET pulls/ +G="$FAKEGH/guard" +g_init() { rm -rf "$G" "$FAKEGH/guard.calls"; mkdir -p "$G"; echo '[]' > "$G/prs.json"; printf '{"boss":"admin","dev":"write"}' > "$G/perms.json"; } +g_pr() { + jq --argjson n "$1" --arg s "$2" --arg r "$3" --arg st "${4:-open}" '. + [{number: $n, state: $st, head: {sha: $s, repo: (if $r == "" then null else {full_name: $r} end)}}]' "$G/prs.json" > "$G/p.tmp" && mv "$G/p.tmp" "$G/prs.json" + jq -n --argjson n "$1" --arg s "$2" --arg r "$3" --arg st "${4:-open}" '{number: $n, state: $st, head: {sha: $s, repo: (if $r == "" then null else {full_name: $r} end)}}' > "$G/pr.$1.json" + echo '[]' > "$G/events.$1.json"; jq -n '[{commit: {committer: {date: "2026-11-17T10:00:00Z"}}}]' > "$G/commits.$1.json" +} +g_files() { local n=$1; shift; printf '%s\n' "$@" | jq -R '{filename: .}' | jq -s . > "$G/files.$n.json"; } +g_label() { jq -n --arg at "$2" --arg who "${3:-boss}" '[{event: "labeled", label: {name: "gate-change-approved"}, created_at: $at, actor: {login: $who}}]' > "$G/events.$1.json"; } +gcalls() { grep -c . "$FAKEGH/guard.calls" 2>/dev/null || echo 0; } +gkinds() { grep -v '^lookup$' "$FAKEGH/guard.calls" 2>/dev/null | cut -d' ' -f1 | sort -u | paste -sd, -; } +REPOK=example/repo +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 README.adoc .github/workflows/ci-gate.yml; publish +chk "unapproved PR touching a gate file: one failure POST, exit 1" "$(post_n 1 | cut -f1)/$NPOSTS/$RC" "failure/1/1" +chk "unapproved PR touching a gate file: the description names the path" "$(post_n 1 | cut -f2)" "gate files changed without owner approval: .github/workflows/ci-gate.yml" +chk "unapproved: decided before any workflow run was read" "$CALLS" 0 +chk "unapproved: published=true (a verdict, not an error)" "$(grep -c '^published=true$' "$WORK/gho")" 1 +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-quality.yml src/x.rs; publish +chk "unapproved PR touching a profiled producer workflow: failure naming it" "$(post_n 1 | cut -f1,2)/$RC" "$(printf 'failure\tgate files changed without owner approval: .github/workflows/ci-quality.yml')/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/other.yml src/x.rs; publish +chk "a workflow NOT named in the profile is not protected: normal verdict" "$(post_n 1 | cut -f1)/$RC" "success/0" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml .github/workflows/ci-build.yml; g_label 7 2026-11-17T11:00:00Z boss; publish +chk "approved PR (admin label after the newest commit): the normal verdict" "$(post_n 1 | cut -f1,2)/$NPOSTS/$RC" "$(printf 'success\tall 3 required checks passed')/1/0" +chk "approved PR: files, events, permission and commits were read" "$(gkinds)" "commits,events,files,perm" +pubreset; snap 1 "$DONE"; jq 'map(if .name == "Test" then .conclusion = "failure" else . end)' "$FX/jobs.json" > "$FAKEGH/jobs.json" +g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; g_label 7 2026-11-17T11:00:00Z boss; publish +chk "approved PR whose checks fail: the checks' failure stands" "$(post_n 1 | cut -f1)/$(post_n 1 | cut -f2 | grep -c 'Test (failure)')" "failure/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 scripts/ci-gate-publish.sh; g_label 7 2026-11-17T09:00:00Z boss; publish +chk "label applied before the newest commit: failure" "$(post_n 1 | cut -f1,2)/$RC" "$(printf 'failure\tgate files changed without owner approval: scripts/ci-gate-publish.sh')/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 scripts/ci-gate-publish.sh; g_label 7 2026-11-17T11:00:00Z dev; publish +chk "non-admin labeller: failure" "$(post_n 1 | cut -f1,2)/$RC" "$(printf 'failure\tgate files changed without owner approval: scripts/ci-gate-publish.sh')/1" +pubreset; snap 1 "$DONE"; g_init; publish +chk "a SHA with no open PR: the normal verdict" "$(post_n 1 | cut -f1)/$RC" "success/0" +chk "a SHA with no open PR: only the one lookup, no per-PR guard call" "$(cat "$FAKEGH/guard.calls")" lookup +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; publish GUARD_PRS= +chk "GUARD_PRS empty (the sweep found no PR): normal verdict and no guard API call at all" "$(post_n 1 | cut -f1)/$(gcalls)" "success/0" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" fork/repo; g_files 7 .github/workflows/ci-gate.yml; publish +chk "a fork PR is not matched: normal verdict, no per-PR guard call" "$(post_n 1 | cut -f1)/$(gkinds)" "success/" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK" closed; g_files 7 .github/workflows/ci-gate.yml; publish +chk "a closed PR is not matched" "$(post_n 1 | cut -f1)/$(gkinds)" "success/" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$(printf 'b%.0s' $(seq 40))" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; publish +chk "a PR whose head is another SHA is not matched" "$(post_n 1 | cut -f1)/$(gkinds)" "success/" +for k in files events; do + pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; : > "$G/fail.$k"; publish + chk "guard API error ($k): failure, no verdict, exit 1" "$(post_n 1 | cut -f1)/$RC/$(grep -c 'tamper guard could not check PR #7; NO VERDICT' <<<"$PUBOUT")" "failure/1/1" +done +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; g_label 7 2026-11-17T11:00:00Z ghost; publish +chk "guard API error (permission 404): failure, no verdict" "$(post_n 1 | cut -f1)/$RC/$(grep -c 'tamper guard could not check PR #7' <<<"$PUBOUT")" "failure/1/1" +pubreset; snap 1 "$DONE"; g_init; : > "$G/fail.lookup"; publish +chk "PR lookup API error: failure, no verdict" "$(post_n 1 | cut -f1)/$RC/$(grep -c 'could not list the pull requests of this commit' <<<"$PUBOUT")" "failure/1/1" +pubreset; snap 1 "$DONE"; g_init; rm -f "$SUITE_DIR/scripts/ci-gate-tamper-guard.sh"; publish +chk "guard script missing from the suite: failure, no verdict" "$(post_n 1 | cut -f1)/$RC" "failure/1" +cp "$ROOT/scripts/ci-gate-tamper-guard.sh" "$SUITE_DIR/scripts/" +pubreset; snap 1 "$DONE"; g_init; publish GUARD_PRS='7 x' +chk "GUARD_PRS with a non-number: failure, no verdict" "$(post_n 1 | cut -f1)/$RC" "failure/1" +echo "-- workflow_run: the event's pull_requests, confirmed by GET pulls/ --" +EVPR() { jq -nc --arg s "$1" --argjson hid "${2:-1}" '[{number: 7, head: {sha: $s, repo: {id: $hid}}, base: {repo: {id: 1}}}]'; } +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; publish GUARD_EVENT_PRS="$(EVPR "$SHA")" +chk "event names the PR: guarded, failure" "$(post_n 1 | cut -f1)/$RC" "failure/1" +chk "event names the PR: confirmed with GET pulls/7, no commits//pulls lookup" "$(grep -c '^pr 7$' "$FAKEGH/guard.calls")/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "1/0" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; publish GUARD_EVENT_PRS="$(EVPR "$SHA" 2)" +chk "event entry from another repository (fork ids): not taken from the event, the lookup still finds the same-repo PR" "$(post_n 1 | cut -f1)/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "failure/1" +pubreset; snap 1 "$DONE"; g_init; publish GUARD_EVENT_PRS='[]' +chk "event has no pull requests (a push): falls back to the lookup" "$(post_n 1 | cut -f1)/$(cat "$FAKEGH/guard.calls")" "success/lookup" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 .github/workflows/ci-gate.yml; : > "$G/fail.pr"; publish GUARD_EVENT_PRS="$(EVPR "$SHA")" +chk "GET pulls/ error: failure, no verdict" "$(post_n 1 | cut -f1)/$RC/$(grep -c 'could not read pull request #7' <<<"$PUBOUT")" "failure/1/1" +pubreset; snap 1 "$DONE"; g_init; publish GUARD_EVENT_PRS='{"x":1}' +chk "a malformed event list: failure, no verdict" "$(post_n 1 | cut -f1)/$RC" "failure/1" +pubreset; g_init echo "== pull_request wait loop: WAIT_SECONDS, POLL_SECONDS ==" NOQ='map(select(.name != "CI quality"))' # CI quality produces the required jobs Lint and Test cat > "$FAKEGH/bin/clock" <<'CLOCK' @@ -881,6 +977,23 @@ sweep CI_GATE_SLEEP="$RL/sleep" CI_GATE_CLOCK="$RL/clock" chk "control: rate limited once and recovered: all 3 heads written, exit 0" "$(grep -c . "$FAKEGH/posts.log")/$RC/$(grep -c 'not evaluated: rate limited' "$WORK/gss")" "3/0/0" pubreset +echo "-- the sweep runs the tamper guard for the same-repository pull requests it lists --" +set_pulls_repo() { # " " ... -> open pull requests with a head repository + local t num idx hr + for t in "$@"; do read -r num idx hr <<<"$t"; jq -nc --argjson n "$num" --arg s "$(sha_n "$idx")" --arg r "$hr" '{number: $n, updated_at: "2026-11-17T10:00:00Z", head: {sha: $s, repo: {full_name: $r}}}'; done | jq -s . > "$FAKEGH/pulls.json" +} +pubreset; g_init; set_default 22; set_pulls_repo "7 20 example/repo" "8 21 fork/repo" +for i in 20 21 22; do sweep_sha "$i" "$DONE"; done +g_pr 7 "$(sha_n 20)" example/repo; g_pr 8 "$(sha_n 21)" fork/repo; g_files 7 .github/workflows/ci-gate.yml; g_files 8 .github/workflows/ci-gate.yml +sweep +chk "sweep: the unapproved same-repo PR head is failure, naming the gate file" "$(last_for 20)/$(grep -P "\t$(sha_n 20)$" "$FAKEGH/posts.log" | cut -f2)" "failure/gate files changed without owner approval: .github/workflows/ci-gate.yml" +chk "sweep: the fork PR head is not guarded (success) and the default branch head is success" "$(last_for 21) $(last_for 22)" "success success" +chk "sweep: guard calls only for PR #7, and no commits//pulls lookup at all" "$(cut -d' ' -f2 "$FAKEGH/guard.calls" | sort -u | paste -sd, -)/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "7/0" +chk "sweep: the failure row is in the table and the sweep exits 1" "$(grep -c "| PR #7 | failure | gate files changed without owner approval" "$WORK/gss")/$RC" "1/1" +g_label 7 2026-11-17T11:00:00Z boss; : > "$FAKEGH/posts.log"; : > "$FAKEGH/guard.calls" +sweep +chk "sweep after the owner's label: the PR head becomes success, exit 0" "$(last_for 20)/$RC" "success/0" +pubreset; g_init echo "== repository coordinate: a leading dot is a name; traversal and malformed ones are not ==" step_script() { # -> the step's run: block, de-indented awk -v name="$2" ' @@ -1076,13 +1189,36 @@ for spec in 0:0 30:0 50:0 51:1 60:1 999999999999999999999999:1; do done # Template: workflow_run main path; pull_request only as the permanent gate-pr job (pr_start_ok). tpl_code() { grep -vE '^[[:space:]]*#' "$1"; } +# Caller shape shared by the template and the suite's caller (caller_shape