diff --git a/.github/workflows/ci-gate-caller.yml b/.github/workflows/ci-gate-caller.yml index 444a8bab..9cf56da5 100644 --- a/.github/workflows/ci-gate-caller.yml +++ b/.github/workflows/ci-gate-caller.yml @@ -4,15 +4,23 @@ # ./.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 pull request +# (a fork's included) 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 @@ -27,29 +35,36 @@ on: - 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 6457fbfd..0ef17b66 100644 --- a/.github/workflows/ci-gate.yml +++ b/.github/workflows/ci-gate.yml @@ -27,6 +27,15 @@ # 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 pull request into the repository, FORKS INCLUDED, whose head is the +# evaluated SHA (workflow_run: the event's pull_requests, else a fork run's head branch, 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 +54,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) @@ -300,6 +310,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%%/*}" @@ -314,6 +325,10 @@ 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) }} + WORKFLOW_RUN_HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }} + WORKFLOW_RUN_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} # 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 @@ -321,10 +336,16 @@ 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; for a fork's run (which names none) the head + # repository and branch; else the publisher looks them up by commit. + GUARD_EVENT_PRS="$WORKFLOW_RUN_PRS" GUARD_HEAD_REPO="$WORKFLOW_RUN_HEAD_REPO" GUARD_HEAD_BRANCH="$WORKFLOW_RUN_HEAD_BRANCH" \ + 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 9bc31af7..163846d8 100644 --- a/config/workflow-lock-scope.json +++ b/config/workflow-lock-scope.json @@ -34,12 +34,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 db362ca4..bf22fd0f 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`). @@ -91,7 +92,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). @@ -100,6 +101,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 guarded too ("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. @@ -109,9 +114,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 @@ -119,7 +124,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. @@ -128,20 +133,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 pull request into this repository (base = the repository), from one of its branches or from a FORK, 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 UNION of (1) the pull requests in `github.event.workflow_run.pull_requests` whose `head.sha` is the commit; (2) for a fork's run, whose list is empty, when the run's `head_repository` is not the repository, `GET pulls?state=open&head=:` (both validated; passed as query fields, never spliced into the URL); (3) always, `GET commits/{sha}/pulls`, kept if open, into the repository and headed by that commit. Candidates from (1) and (2) are confirmed open, into the repository and still at that head with `GET pulls/{n}`. The status is per commit and several pull requests can share one head (two branches at one commit, one branch into two bases), so every one of them is guarded, not only the one the event names; +* `schedule` / `workflow_dispatch` (the sweep): every pull request the sweep already listed for that head, forks included (its listing is complete, so no extra lookup); +* `pull_request` (`gate-pr`): its own number, together with `GET commits/{sha}/pulls` as above, so this path guards the same set as the trusted ones. -*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; every `workflow_run` and `gate-pr` evaluation costs the commit lookup (and a fork run the branch lookup); a sweep costs nothing extra. 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. GitHub records no new event when a label that is already on the pull request is added again, so to renew approval the owner REMOVES the label and then applies it again. 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"). + +*Forks are guarded.* A fork's `pull_request` workflows run the FORK's workflow files, so a fork could otherwise rewrite a profiled producer into a no-op job with the same name and have the default-branch gate publish `success`. The guard's calls (changed files, label events, the labeller's permission, commits) are all endpoints of the base repository's pull request, so they work the same for a fork. A fork never runs `gate-pr` (its token cannot write statuses), so it is judged only by the trusted default-branch paths. + +*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, remove any `guard / check` entry (workflow `.github/workflows/ci-gate-tamper-guard.yml`) from the repository's profile in the suite, since it would read `never reported` once the caller is gone (no shipped profile lists it today; `tests/ci-gate.sh` keeps it that way), 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. After a later push, remove the label and apply it again (re-adding a label that is still on the pull request records no new event). 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..f87f355e 100644 --- a/scripts/ci-gate-publish.sh +++ b/scripts/ci-gate-publish.sh @@ -18,10 +18,14 @@ # 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_NO_LOOKUP GUARD_EVENT_PRS GUARD_HEAD_REPO GUARD_HEAD_BRANCH which pull requests the +# tamper guard checks: the union of all sources (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 pull request into REPO (fork or not) 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 +121,101 @@ write_summary() { # } >> "${GITHUB_STEP_SUMMARY:-/dev/null}" } +# a. Tamper guard, folded into this verdict (docs/CI-GATE.adoc, "Tamper guard"). For EVERY open pull +# request into this repository (base = REPO) whose head is HEAD_SHA, from a branch of this repository +# or from a FORK, run scripts/ci-gate-tamper-guard.sh with the profile's producer workflows as extra +# protected paths. The status is per commit, and several pull requests can share one head (two +# branches at one commit, or one branch into two bases), so the guard covers all of them: the set is +# the UNION of every source below, de-duplicated. 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 any lookup is "no verdict" (die). Sources: +# GUARD_PRS numbers the caller already knows are open with base REPO at HEAD_SHA (the sweep's +# listing; gate-pr's own number). Taken as they are. +# GUARD_NO_LOOKUP=1 the caller listed EVERY open pull request of the repository (the sweep): no +# lookup. Otherwise all of the following are added: +# GUARD_EVENT_PRS the workflow_run event's pull_requests (JSON; empty for a fork's run) whose +# head.sha is HEAD_SHA, each confirmed with GET pulls/ (open, base REPO, head SHA). +# GUARD_HEAD_REPO GUARD_HEAD_BRANCH when the run's head repository is not REPO (a fork): +# GET pulls?state=open&head=:, each confirmed the same way. +# always: GET commits//pulls, kept if open, base REPO and head HEAD_SHA. +# The guard's per-pull-request calls (files, label events, permission, commits) are base-repository +# endpoints and are made only for a matched pull request. +GUARD="$SUITE/scripts/ci-gate-tamper-guard.sh" +[[ -f $GUARD ]] || die 'the tamper guard script is missing from the suite' +guard_prs=() +pr_num_ok() { [[ $1 =~ ^[1-9][0-9]{0,9}$ ]]; } +confirm_pr() { # : append it to guard_prs if it is open, into REPO, and headed by HEAD_SHA + local pr pstate psha pbase + pr=$(gh api "repos/$REPO/pulls/$1" --jq '[.state, .head.sha, (.base.repo.full_name // "")] | @tsv') \ + || die "could not read pull request #$1 for the tamper guard" + IFS=$'\t' read -r pstate psha pbase <<< "$pr" + # a malformed answer is no evidence that the pull request is not ours: no verdict + [[ $pstate =~ ^(open|closed)$ && $psha =~ ^[0-9a-f]{40}$ ]] || die "pull request #$1 answered no usable state or head for the tamper guard" + if [[ $pstate == open && $psha == "$HEAD_SHA" && $pbase == "$REPO" ]]; then guard_prs+=("$1"); fi + return 0 +} +for n in ${GUARD_PRS:-}; do + pr_num_ok "$n" || die 'GUARD_PRS holds something that is not a pull request number' + guard_prs+=("$n") +done +if [[ ${GUARD_NO_LOOKUP:-} != 1 ]]; then + 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) | .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 + pr_num_ok "$n" || die 'the workflow_run pull request list has a malformed number' + confirm_pr "$n" + done + fi + if [[ -n ${GUARD_HEAD_REPO:-} && $GUARD_HEAD_REPO != "$REPO" ]]; then + # a fork's run: workflow_run.pull_requests is empty, so ask for open pull requests from its branch + [[ $GUARD_HEAD_REPO =~ ^[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9_.-]+$ ]] \ + || die 'the workflow_run head repository is not an owner/name coordinate' + [[ -n ${GUARD_HEAD_BRANCH:-} && ${#GUARD_HEAD_BRANCH} -le 255 && $GUARD_HEAD_BRANCH != *[[:cntrl:]]* ]] \ + || die 'the workflow_run head branch is empty, too long or has control characters' + found=$(gh api -X GET --paginate "repos/$REPO/pulls" -f state=open -f per_page=100 \ + -f head="${GUARD_HEAD_REPO%%/*}:$GUARD_HEAD_BRANCH" --jq '.[] | .number') \ + || die 'could not list the pull requests of the fork branch for the tamper guard' + for n in $found; do + pr_num_ok "$n" || die 'a fork pull request has a malformed number' + confirm_pr "$n" + done + fi + found=$(gh api --paginate "repos/$REPO/commits/$HEAD_SHA/pulls?per_page=100" --jq '.[] | [.number, .state, .head.sha, (.base.repo.full_name // "")] | @tsv') \ + || die 'could not list the pull requests of this commit for the tamper guard' + while IFS=$'\t' read -r n pstate psha pbase; do + [[ -n $n ]] || continue + pr_num_ok "$n" || die 'a pull request of this commit has a malformed number' + [[ $pstate =~ ^(open|closed)$ && $psha =~ ^[0-9a-f]{40}$ ]] || die "pull request #$n of this commit has no usable state or head" + if [[ $pstate == open && $psha == "$HEAD_SHA" && $pbase == "$REPO" ]]; then guard_prs+=("$n"); fi + done <<< "$found" +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\n' "${guard_prs[@]}" | sort -un); do + : > "$WORK/guard-result.txt" || die 'could not prepare the tamper guard result file' + gout=$(env -u APPROVAL_LABEL REPO="$REPO" PR_NUMBER="$n" EXTRA_PROTECTED_FILE="$WORK/guard-protected.txt" \ + GUARD_RESULT_FILE="$WORK/guard-result.txt" bash "$GUARD" 2>&1) + grc=$? + printf '%s\n' "$gout" | sed "s/^/tamper guard PR #$n: /" + ((grc == 0)) && continue + [[ -s $WORK/guard-result.txt ]] || die "tamper guard could not check PR #$n" + mapfile -t -O "${#guard_touched[@]}" guard_touched < "$WORK/guard-result.txt" + done + if ((${#guard_touched[@]} > 0)); then + state=failure + description="gate files changed without owner approval: $(printf '%s\n' "${guard_touched[@]}" | 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..08040187 100644 --- a/scripts/ci-gate-sweep.sh +++ b/scripts/ci-gate-sweep.sh @@ -20,7 +20,12 @@ # 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: EVERY open pull request headed by that SHA (from the listing above, forks included; +# several pull requests can share one head), with GUARD_NO_LOOKUP=1 ONLY when the listing completed +# (every page, every row usable); otherwise the publisher also runs its own commit lookup, +# so the publisher runs the tamper guard for exactly those, with no lookup of its own; the default +# branch head (unless a pull request shares it) gets 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 +53,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 pull request (forks included) # 1. the default branch head, first: it sorts above every pull request branch=$(gh api "repos/$REPO" --jq .default_branch 2> /dev/null) || branch='' @@ -64,14 +70,26 @@ else errors=$((errors + 1)) fi -# open pull requests, every page +# open pull requests, every page. listing_complete=1 only when every page was read and every row was +# usable: only then may the publisher skip its own commit lookup (GUARD_NO_LOOKUP=1). The tamper guard is +# skipped only on POSITIVE evidence that no pull request shares a SHA, never because a listing failed. +listing_complete=0 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] | @tsv' > "$WORK/pulls.tsv" 2> "$WORK/pulls.err"; then + listing_complete=1 + while IFS=$'\t' read -r upd sha src num; do if [[ $sha =~ ^[0-9a-f]{40}$ && -n $upd ]]; then printf '%s\t%s\t%s\n' "$upd" "$sha" "$src" >> "$cand" + # tamper guard: every open pull request into REPO, fork or not (docs/CI-GATE.adoc, "Tamper guard") + if [[ $num =~ ^[1-9][0-9]{0,9}$ ]]; then + printf '%s\t%s\n' "$sha" "$num" >> "$guardprs" + else + echo "::warning::ci-gate-sweep: $src has no usable number; the publisher looks the pull requests up itself" + listing_complete=0 + fi else echo "::error::ci-gate-sweep: $src has an unusable head SHA or date; it was NOT evaluated" + listing_complete=0 # its head is unknown, so it may share a SHA that is evaluated printf '%s\t%s\terror\tunusable head SHA\n' '-' "$src" >> "$rows" errors=$((errors + 1)) fi @@ -100,7 +118,10 @@ 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' ' -) + # an incomplete listing: the publisher also runs its own commit lookup (fail closed) + nolookup=0; ((listing_complete == 1)) && nolookup=1 + env -u GITHUB_OUTPUT -u GUARD_EVENT_PRS -u GUARD_HEAD_REPO -u GUARD_HEAD_BRANCH GUARD_NO_LOOKUP="$nolookup" 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..fe87bf9f 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,30 @@ 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). +# GUARD_RESULT_FILE (optional, for the publisher): a refusal that is a VERDICT (gate files touched, not +# approved) writes the touched paths there, one per line; an error (no verdict) writes nothing, so the +# caller can tell "not approved" (exit 1, file non-empty) from "could not check" (exit 1, file empty). +# A file, not stdout: the paths come from the API, and stdout also carries them in messages. set -uo pipefail APPROVAL_LABEL=${APPROVAL_LABEL:-gate-change-approved} fail() { echo "::error::gate tamper guard: $1"; exit 1; } +deny() { # a verdict: not approved + if [[ -n ${GUARD_RESULT_FILE:-} ]]; then + printf '%s\n' "${touched[@]}" | LC_ALL=C sort -u > "$GUARD_RESULT_FILE" || { : > "$GUARD_RESULT_FILE"; fail 'could not write GUARD_RESULT_FILE; no verdict'; } + fi + 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 +69,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 +107,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 +115,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 +132,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 remove and re-apply it after every push (re-adding a label still on the pull request records no new event)." diff --git a/templates/ci-gate-caller.yml b/templates/ci-gate-caller.yml index e5c27e47..529d8e07 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 pull request into this repository (a fork's +# included) 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..44e7296f 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,50 @@ 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 +RF="$WORK/result.txt" +rf() { : > "$RF"; run GUARD_RESULT_FILE="$RF" "$@"; } # -> RC, OUT; the result file is $RF +reset; files .github/workflows/ci.yml README.adoc; rf EXTRA_PROTECTED_FILE="$WORK/extra.txt" +chk "that refusal is a verdict: the touched path is in GUARD_RESULT_FILE" "$RC/$(paste -sd, "$RF")" "1/.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 "== GUARD_RESULT_FILE tells a verdict from an error ==" +reset; files scripts/ci-gate-publish.sh; events "$LBL dev"; rf +chk "non-admin label: a verdict (result file names the path)" "$RC/$(cat "$RF")" "1/scripts/ci-gate-publish.sh" +reset; files scripts/ci-gate-publish.sh; events "labeled gate-change-approved 2026-11-17T09:00:00Z boss"; rf +chk "label before the newest commit: a verdict" "$RC/$(cat "$RF")" "1/scripts/ci-gate-publish.sh" +reset; files scripts/ci-gate-publish.sh; events "$LBL none"; rf +chk "no actor on the label event: a verdict" "$RC/$(cat "$RF")" "1/scripts/ci-gate-publish.sh" +reset; files scripts/ci-gate-publish.sh .github/workflows/ci-gate.yml; rf +chk "no label: a verdict naming every touched path, sorted" "$RC/$(paste -sd, "$RF")" "1/.github/workflows/ci-gate.yml,scripts/ci-gate-publish.sh" +for k in files events perm commits; do + reset; files .github/workflows/ci-gate.yml; events "$LBL boss"; : > "$D/fail$k"; rf + chk "API error ($k): exit 1 and NOT a verdict (result file empty)" "$RC/$(wc -c < "$RF")" "1/0" +done +reset; files .github/workflows/ci-gate.yml; events "$LBL boss"; rf +chk "approved: exit 0, result file empty" "$RC/$(wc -c < "$RF")" "0/0" +printf '%s\n' '[{"filename":"scripts/ci-gate-x.sh\nguard-touched=forged"}]' > "$D/files.json"; events; rf +chk "a filename with a newline cannot forge a protected path: only real protected lines are listed" "$RC/$(paste -sd, "$RF")" "1/scripts/ci-gate-x.sh" +chk "the guard prints no guard-result or guard-touched protocol line on stdout any more" "$(grep -c '^guard-\(result\|touched\)=' <<<"$OUT")" 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 +195,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 +216,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 +240,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 f7a6c3f4..a5a538f0 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,36 @@ 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). + *"/pulls -f state=open"*) + h=${args#*-f head=}; h=${h%% --jq*}; echo "headlookup $h" >> "$D/guard.calls" + [[ ! -f $D/guard/fail.headlookup ]] || { echo "gh: HTTP 500 (head lookup)" >&2; exit 1; } + jq -r "$jqarg" "$D/guard/headprs.json" 2>/dev/null || jq -r "$jqarg" <<< '[]' ;; + *"/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; } + # no files..json: a pull request that changes nothing the guard protects (the sweep's plain PRs) + if [[ -f $D/guard/files.$n.json ]]; then jq -c "$jqarg" "$D/guard/files.$n.json"; else jq -c "$jqarg" <<< '[{"filename":"README.adoc"}]'; fi ;; + *"/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 +353,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 +449,122 @@ 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] [base repo]: 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}" --arg b "${5:-example/repo}" '. + [{number: $n, state: $st, head: {sha: $s, repo: (if $r == "" then null else {full_name: $r} end)}, base: {repo: {full_name: $b}}}]' "$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}" --arg b "${5:-example/repo}" '{number: $n, state: $st, head: {sha: $s, repo: (if $r == "" then null else {full_name: $r} end)}, base: {repo: {full_name: $b}}}' > "$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= GUARD_NO_LOOKUP=1 +chk "GUARD_NO_LOOKUP=1 with 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-quality.yml; publish +chk "a fork PR touching a profiled producer workflow, unapproved: guarded, failure" "$(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" fork/repo; g_files 7 src/x.rs README.adoc; publish +chk "a fork PR with no protected change: the normal verdict" "$(post_n 1 | cut -f1)/$RC/$(gkinds)" "success/0/files" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "" ; g_files 7 .github/workflows/ci-gate.yml; publish +chk "a PR whose head repository was deleted (head.repo null) is still guarded" "$(post_n 1 | cut -f1)/$RC" "failure/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK" open other/base; g_files 7 .github/workflows/ci-gate.yml; publish +chk "a PR into ANOTHER base repository is not matched" "$(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" '[{number: 7, head: {sha: $s, repo: {id: 1}}, 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, AND the commit lookup still runs (union); PR 7 guarded once" "$(grep -c '^pr 7$' "$FAKEGH/guard.calls")/$(grep -c '^lookup$' "$FAKEGH/guard.calls")/$(grep -c '^files 7$' "$FAKEGH/guard.calls")" "1/1/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK" open other/base; g_files 7 .github/workflows/ci-gate.yml; publish GUARD_EVENT_PRS="$(EVPR "$SHA")" +chk "event entry whose PR has another base: GET pulls/7 rejects it, the lookup finds nothing, normal verdict" "$(post_n 1 | cut -f1)/$(grep -c '^lookup$' "$FAKEGH/guard.calls")/$(gkinds)" "success/1/pr" +echo "-- several open PRs at ONE head SHA: the guard covers the union, not just the hinted one --" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_pr 9 "$SHA" "$REPOK"; g_files 7 src/x.rs; g_files 9 .github/workflows/ci-gate.yml +publish GUARD_EVENT_PRS="$(EVPR "$SHA")" +chk "event hints clean PR #7, PR #9 at the same SHA touches a gate file unapproved: failure" "$(post_n 1 | cut -f1,2)/$RC" "$(printf 'failure\tgate files changed without owner approval: .github/workflows/ci-gate.yml')/1" +chk "both PRs were guarded (files read for #7 and #9)" "$(grep -c '^files 7$' "$FAKEGH/guard.calls")$(grep -c '^files 9$' "$FAKEGH/guard.calls")" 11 +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_pr 9 "$SHA" "$REPOK"; g_files 7 src/x.rs; g_files 9 .github/workflows/ci-gate.yml +publish GUARD_PRS=7 +chk "gate-pr (GUARD_PRS=its own clean #7) still finds #9 through the commit lookup: failure" "$(post_n 1 | cut -f1)/$RC" "failure/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; g_files 7 src/x.rs; : > "$G/fail.lookup"; publish GUARD_EVENT_PRS="$(EVPR "$SHA")" +chk "commit lookup API error even when the event hints a PR: 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; g_pr 7 "$SHA" "$REPOK"; g_pr 9 "$SHA" "$REPOK"; g_files 7 src/x.rs; g_files 9 README.adoc +publish GUARD_EVENT_PRS="$(EVPR "$SHA")" +chk "two clean PRs at one SHA: the normal verdict" "$(post_n 1 | cut -f1)/$RC" "success/0" +echo "-- a malformed lookup answer is no evidence that no PR matches: no verdict --" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" "$REPOK"; echo '{"number":7}' > "$G/pr.7.json"; publish GUARD_EVENT_PRS="$(EVPR "$SHA")" +chk "GET pulls/ answers no state or head: failure, no verdict" "$(post_n 1 | cut -f1)/$RC/$(grep -c 'answered no usable state or head' <<<"$PUBOUT")" "failure/1/1" +pubreset; snap 1 "$DONE"; g_init; echo '[{"number":7,"state":null,"head":{"sha":null},"base":{"repo":{"full_name":"example/repo"}}}]' > "$G/prs.json"; publish +chk "commit lookup row with no state or head: failure, no verdict" "$(post_n 1 | cut -f1)/$RC/$(grep -c 'has no usable state or head' <<<"$PUBOUT")" "failure/1/1" +echo "-- workflow_run from a FORK: pull_requests is empty, so the fork branch is looked up --" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" fork/repo; g_files 7 .github/workflows/ci-build.yml; echo '[{"number":7}]' > "$G/headprs.json" +publish GUARD_EVENT_PRS='[]' GUARD_HEAD_REPO=fork/repo GUARD_HEAD_BRANCH='feat/x' +chk "fork run, unapproved producer change: failure naming it" "$(post_n 1 | cut -f1,2)/$RC" "$(printf 'failure\tgate files changed without owner approval: .github/workflows/ci-build.yml')/1" +chk "fork run: looked up open PRs from fork:feat/x, confirmed #7, and the commit lookup too (union)" "$(grep -c '^headlookup fork:feat/x$' "$FAKEGH/guard.calls")/$(grep -c '^pr 7$' "$FAKEGH/guard.calls")/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "1/1/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" fork/repo; g_files 7 src/x.rs; echo '[{"number":7}]' > "$G/headprs.json" +publish GUARD_EVENT_PRS='[]' GUARD_HEAD_REPO=fork/repo GUARD_HEAD_BRANCH=feat +chk "fork run, no protected change: the normal verdict" "$(post_n 1 | cut -f1)/$RC" "success/0" +pubreset; snap 1 "$DONE"; g_init; : > "$G/fail.headlookup"; publish GUARD_EVENT_PRS='[]' GUARD_HEAD_REPO=fork/repo GUARD_HEAD_BRANCH=feat +chk "fork lookup API error: failure, no verdict" "$(post_n 1 | cut -f1)/$RC/$(grep -c 'could not list the pull requests of the fork branch' <<<"$PUBOUT")" "failure/1/1" +pubreset; snap 1 "$DONE"; g_init; g_pr 7 "$SHA" fork/repo; g_files 7 .github/workflows/ci-gate.yml +publish GUARD_EVENT_PRS='[]' GUARD_HEAD_REPO=fork/repo GUARD_HEAD_BRANCH=feat +chk "fork branch lookup finds nothing: commits//pulls still finds the fork PR, failure" "$(post_n 1 | cut -f1)/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "failure/1" +for hr in 'a/b/c' '../x' 'fork/repo?x'; do + pubreset; snap 1 "$DONE"; g_init; publish GUARD_EVENT_PRS='[]' GUARD_HEAD_REPO="$hr" GUARD_HEAD_BRANCH=feat + chk "malformed fork head repository '$hr': failure, no verdict, no lookup" "$(post_n 1 | cut -f1)/$RC/$(gcalls)" "failure/1/0" +done +pubreset; snap 1 "$DONE"; g_init; publish GUARD_EVENT_PRS='[]' GUARD_HEAD_REPO=fork/repo GUARD_HEAD_BRANCH="$(printf 'a\nb')" +chk "a fork head branch with a control character: failure, no verdict" "$(post_n 1 | cut -f1)/$RC" "failure/1" +pubreset; snap 1 "$DONE"; g_init; publish GUARD_EVENT_PRS='[]' GUARD_HEAD_REPO="$REPOK" GUARD_HEAD_BRANCH=main +chk "a same-repository run with no PR: no fork lookup, one commit lookup" "$(post_n 1 | cut -f1)/$(cat "$FAKEGH/guard.calls")" "success/lookup" +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 +1027,52 @@ 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 every pull request it lists, forks included --" +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 unapproved FORK PR head is failure too, and the default branch head is success" "$(last_for 21) $(last_for 22)" "failure success" +chk "sweep: guard calls for PR #7 and fork PR #8, and no lookup at all" "$(cut -d' ' -f2 "$FAKEGH/guard.calls" | sort -u | paste -sd, -)/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "7,8/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 on #7 only: #7 success, fork #8 still failure, exit 1" "$(last_for 20)/$(grep -c '| PR #8 | failure | gate files changed' "$WORK/gss")/$RC" "success/1/1" +g_label 8 2026-11-17T11:00:00Z boss; : > "$FAKEGH/posts.log" +sweep +chk "sweep after the owner's label on the fork PR too: both success, exit 0" "$(last_for 21)/$(grep -c '| PR #[78] | success |' "$WORK/gss")/$RC" "success/2/0" +pubreset; g_init +echo "-- the sweep: two open PRs at one head SHA are both guarded --" +pubreset; g_init; set_default 31; set_pulls_repo "7 30 example/repo" "9 30 example/repo" +for i in 30 31; do sweep_sha "$i" "$DONE"; done +g_pr 7 "$(sha_n 30)" example/repo; g_pr 9 "$(sha_n 30)" example/repo; g_files 7 src/x.rs; g_files 9 .github/workflows/ci-gate.yml +sweep +chk "sweep: shared head, clean #7 and unapproved #9: failure naming the gate file" "$(last_for 30)/$(grep -P "\t$(sha_n 30)$" "$FAKEGH/posts.log" | cut -f2)" "failure/gate files changed without owner approval: .github/workflows/ci-gate.yml" +chk "sweep: both #7 and #9 guarded, no lookup" "$(grep -c '^files 7$' "$FAKEGH/guard.calls")$(grep -c '^files 9$' "$FAKEGH/guard.calls")/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "11/0" +pubreset; g_init +echo "-- the sweep skips the publisher's own lookup ONLY when its PR listing is complete --" +pubreset; g_init; set_default 40; set_pulls; sweep_sha 40 "$DONE" +g_pr 7 "$(sha_n 40)" example/repo; g_files 7 .github/workflows/ci-gate.yml; touch "$FAKEGH/failpulls" +sweep +chk "PR listing fails, an unapproved PR shares the default branch head: failure via the commit lookup, not success" "$(last_for 40)/$RC" "failure/1" +chk "PR listing fails: the publisher ran its own commit lookup" "$(grep -c '^lookup$' "$FAKEGH/guard.calls")" 1 +pubreset; g_init; set_default 40; set_pulls; sweep_sha 40 "$DONE"; touch "$FAKEGH/failpulls" +sweep +chk "PR listing fails, no PR at that head: the normal verdict through the lookup (the sweep still exits 1 for the listing)" "$(last_for 40)/$(cat "$FAKEGH/guard.calls")/$RC" "success/lookup/1" +pubreset; g_init; set_default 40; set_pulls; sweep_sha 40 "$DONE" +sweep +chk "PR listing complete, no PR at that head: no lookup at all" "$(last_for 40)/$(gcalls)/$RC" "success/0/0" +pubreset; g_init; set_default 40; sweep_sha 40 "$DONE" +jq -n --arg s "$(sha_n 40)" '[{number: "x", updated_at: "2026-11-17T10:00:00Z", head: {sha: $s}}]' > "$FAKEGH/pulls.json" +g_pr 7 "$(sha_n 40)" example/repo; g_files 7 .github/workflows/ci-gate.yml +sweep +chk "a listed PR without a usable number: the publisher looks up itself and finds the unapproved PR" "$(last_for 40)/$(grep -c '^lookup$' "$FAKEGH/guard.calls")" "failure/1" +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" ' @@ -1034,6 +1226,10 @@ w "$(p "$A" | sed 's/}$/,"repository":"other\/repo"}/')"; v_bad "$WORK/p.json" e v_bad "$WORK/absent.json" example/repo "an absent file" echo "== shipped profiles ==" +# The retired pull_request_target guard never starts, so a profile entry for it would read `never +# reported` forever (docs/CI-GATE.adoc, "The retired pull_request_target guard"). +RETIRED=$(for f in "$ROOT"/profiles/ci-gate/*/*.json; do jq -r --arg f "$f" '.checks[] | select(.workflow | test("ci-gate-tamper-guard")) | $f' "$f"; done) +[ -z "$RETIRED" ] && ok "no shipped profile requires the retired guard / check" || bad "a shipped profile requires the retired guard: $RETIRED" shopt -s nullglob dotglob # a repository named .github has the profile .github.json n=0 for f in "$ROOT"/profiles/ci-gate/*/*.json; do @@ -1122,13 +1318,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