From afe61e80aae47af4df64842225e7cc2e5130341f Mon Sep 17 00:00:00 2001 From: Timothy Date: Sat, 29 Aug 2026 23:02:24 +0200 Subject: [PATCH] fix(845): the verdict writer checks that the gate will honour what it just posted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `.gitea/workflows/review-verdict.yml` inherits an existing `review-verdict/h10=success` only from a status whose `.creator.login` is on its `H10_REVIEWERS` allow-list (#742). `scripts/post-review-verdict.sh` writes those verdicts with whatever account owns `ETV_GITEA_TOKEN`/`ETV_GITEA_BASICAUTH` and never asked whose it was. The two values were coupled with nothing asserting the coupling, and the failure mode was the silent one: the status really is written, the tool really does report success, and then the next `pull_request_target` event re-derives it and posts over it. And again. The PR deadlocks and the only diagnostic is a `::warning::` inside a workflow run nobody is reading. The script now READS THE STATUS BACK after posting it, identifies its own write by state and description, and refuses — before the comment, so the surviving half-state is the documented `ask` one — unless the recorded creator is on the allow-list. Measured after the write rather than probed before it: a pre-flight `GET /user` tests what the credential claims to be, this tests what Gitea recorded as the author of this status, which is the value the gate reads. It also needs no scope beyond the repo access the POST already required. The allow-list is not restated. `scripts/lib/h10-reviewers.sh` derives it from the workflow's own literal, so there is ONE declaration rather than two held together by a parity test — the shape `testing.guard-derives-population-from-source` records six failed rounds against. It is a parse rather than a shared declaration both sides source, and that is not a preference: the gate runs against a checkout of the PR's BASE sha, so a PR whose base predates a new `scripts/lib/` file would not have it, and a missing `source` under `set -euo pipefail` kills the job — which posts no `review-verdict/h10` at all and blocks every merge to `main` including the PR that would repair it, with no admin override (#743). A fallback list for that case reintroduces the second copy. So the derivation runs on the side that can fail safely and the gate's body is untouched. Fail-closed on every branch of the derivation: 0 or >1 anchored assignments, an entry that is not a plain login, an empty list, or an unreadable file all refuse BEFORE any network call. The membership query answers member / not-a-member / cannot-tell as three distinct codes rather than two, so a caller cannot fold "cannot tell" into either. The safety DIRECTION is unchanged and the commit does not claim otherwise: a non-allow-listed verdict was always a stall, never a fail-open. What changes is where the signal lands — at the terminal that made the mistake, instead of one PR event later. Residual, stated rather than fixed: the check runs after the POST, so a refused verdict leaves a non-inheritable status standing with no comment beside it. That is the `ask` half-state `release.verdict-writes-status-before-comment` already designates as the safe one, and the gate re-derives it on the next PR event. A second corrective write is the sticky-sentinel mechanism #849 is separately designing; inventing a parallel one here would be two mechanisms for one invariant. `scripts/post-review-verdict.sh` moves BEHAVIOUR-ONLY -> MUTATION in the guard inventory, which the manifest's own UNDECLARED note called "the most valuable upgrade on this list". The declared clause is in the GATE, not the script: rewriting `H10_REVIEWERS` while the posting account stays fixed reddens the accept path only if the writer reads the list live AND the comparison gates the outcome. Disarming the comparison instead would prove the second and say nothing about the first, which is the half that was missing. Verification: full `scripts/tests` suite green (1239 passed, 2 skipped); the declared mutation executes and reddens its named proof with the declared diagnostic; four clauses disarmed by hand and each confirmed to redden its own test. fixes #845 Decisions-Edit: yes Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019zUmJZHhVP7kXg5DV237TW --- CLAUDE.md | 2 +- docs/ci-cd.md | 25 +- docs/decisions/README.md | 2 +- .../records/ci/exemption-provenance.md | 57 ++-- docs/guard-inventory.md | 4 +- docs/remote-state-inventory.md | 3 +- scripts/lib/h10-reviewers.sh | 189 ++++++++++++++ scripts/post-review-verdict.sh | 94 ++++++- scripts/tests/mutation_manifest.py | 19 +- scripts/tests/test_post_review_verdict.py | 247 ++++++++++++++++++ .../tests/test_review_verdict_vocabulary.py | 8 + 11 files changed, 616 insertions(+), 34 deletions(-) create mode 100644 scripts/lib/h10-reviewers.sh diff --git a/CLAUDE.md b/CLAUDE.md index bc8ae1f44..866b68140 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -83,7 +83,7 @@ main in) and re-run the local gate whenever the fetch shows movement. Every task that closes a Gitea issue MUST complete ALL of these before it is considered done. Use `/done ` to run through this automatically. **Merge-consent is derived from state, not asserted (`## Done-when` convention — ersatztv#303 H6 + H10).** Any issue whose PR will merge to `main` should carry a `## Done-when` section in its **issue body** — a checklist of completion criteria (always include an "adversarial review passed" box; add per-issue criteria like tests-green, docs-updated, live-E2E). Two hooks derive merge-consent from it so a premature merge is blocked *by construction*, not by memory: -- `pretooluse-merge-consent.sh` (Claude PreToolUse on the Gitea merge tool) — **auto-grants** a merge (emits `permissionDecision: allow`, so **no** redundant mechanical prompt fires) only when the PR's CI is green **and** every `## Done-when` box on the linked issue (`fixes #N`) is ticked **and** a `Review-verdict:` comment references the PR's *current head sha* (**H10**); **denies** on an unticked box, red CI, or a stale/negative review verdict; **asks** (falls back to a human prompt) when it can't derive state (no linked issue, no `## Done-when` section, no `Review-verdict:` comment yet, no creds, Gitea down). On the auto-grant (satisfied) path the derived state **is** the consent — do not also ask conversationally to merge; a separate human confirmation is warranted only when the gate **asks** (ersatztv#314). **The H10 review-verdict convention**: after an adversarial/Codex review of a PR (or its latest fix commit), run **`scripts/post-review-verdict.sh [note]`** — it posts both the `Review-verdict: … @ ` comment and the sha-bound `review-verdict/h10` commit status, proving the *latest* commit was reviewed rather than a stale earlier diff (ersatztv#242). Do not hand-write the comment: the **status** is the required check branch protection enforces, and a comment alone leaves it absent. **The credential you post with must be an account on `H10_REVIEWERS` in `.gitea/workflows/review-verdict.yml`** (`timothy` today) — since ersatztv#742 the gate inherits an existing `success` only from an allow-listed creator (an existing `failure` is left alone on a weaker attributability test, so an attributable rejection VISIBLE AT THE FIRST READ is not re-derived into a green — a rejection landing later, inside a run's own write window, is a separate and still-open route, ersatztv#849), so a verdict posted with any other account is written, reported as success by the script, and then silently re-derived on the next PR event (ersatztv#845). +- `pretooluse-merge-consent.sh` (Claude PreToolUse on the Gitea merge tool) — **auto-grants** a merge (emits `permissionDecision: allow`, so **no** redundant mechanical prompt fires) only when the PR's CI is green **and** every `## Done-when` box on the linked issue (`fixes #N`) is ticked **and** a `Review-verdict:` comment references the PR's *current head sha* (**H10**); **denies** on an unticked box, red CI, or a stale/negative review verdict; **asks** (falls back to a human prompt) when it can't derive state (no linked issue, no `## Done-when` section, no `Review-verdict:` comment yet, no creds, Gitea down). On the auto-grant (satisfied) path the derived state **is** the consent — do not also ask conversationally to merge; a separate human confirmation is warranted only when the gate **asks** (ersatztv#314). **The H10 review-verdict convention**: after an adversarial/Codex review of a PR (or its latest fix commit), run **`scripts/post-review-verdict.sh [note]`** — it posts both the `Review-verdict: … @ ` comment and the sha-bound `review-verdict/h10` commit status, proving the *latest* commit was reviewed rather than a stale earlier diff (ersatztv#242). Do not hand-write the comment: the **status** is the required check branch protection enforces, and a comment alone leaves it absent. **The credential you post with must be an account on `H10_REVIEWERS` in `.gitea/workflows/review-verdict.yml`** (`timothy` today) — since ersatztv#742 the gate inherits an existing `success` only from an allow-listed creator (an existing `failure` is left alone on a weaker attributability test, so an attributable rejection VISIBLE AT THE FIRST READ is not re-derived into a green — a rejection landing later, inside a run's own write window, is a separate and still-open route, ersatztv#849), and since ersatztv#845 the script ENFORCES that coupling rather than assuming it: it reads its own status back and refuses, before writing the verdict comment, unless the recorded `.creator.login` is on that allow-list — so a verdict posted with any other account fails loudly at your terminal instead of being written, reported as success, and then silently re-derived on the next PR event. The allow-list is derived from the workflow by `scripts/lib/h10-reviewers.sh`; it is never restated. - **The gate is enforced server-side, per sha (ersatztv#622).** `review-verdict/h10` is a required status check on `main`. Because a commit status belongs to one sha, a commit pushed *after* an auto-merge is scheduled clears it and blocks the merge — closing the hole where `merge_when_checks_succeed` froze consent at scheduling time and Gitea later merged an unreviewed head. Renovate-authored and docs-only PRs are auto-passed by `.gitea/workflows/review-verdict.yml`, **except** when they touch `.claude/`, `.codex/`, `.gitea/`, `.husky/`, `scripts/` or `docker/ci/`. See `docs/ci-cd.md` → Review-verdict gate. - `.husky/pre-push` → `prepush-donewhen.sh` — a fail-open backstop that blocks a direct `git push origin main` whose commits `fix #N` an issue with unticked boxes. **Since ersatztv#743 that push can no longer happen at all** (see below), so this hook is now belt-and-braces for a path the server refuses. diff --git a/docs/ci-cd.md b/docs/ci-cd.md index 1bce581f5..f9429a157 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -1612,12 +1612,25 @@ account to `H10_REVIEWERS` in `.gitea/workflows/review-verdict.yml`. (A separate annotation carrying the same three values was tried and withdrawn: its only delta was a severity whose rendering could not be probed, and it needed a guard of its own to stop contradicting the line above it.) `post-review-verdict.sh` posts -with whatever account owns `ETV_GITEA_TOKEN`/`ETV_GITEA_BASICAUTH` and does **not** check that it is an -allow-listed one (ersatztv#845). A changed writer credential does not fail loudly — it reports success, -and each *subsequent* PR event re-derives the status: to `pending` on a PR that needs a verdict, or to -an exemption **`success`** on a docs-only or Renovate-manifest one, which is the quieter and worse -half. A verdict posted after the last event stands until the next one, so the symptom is a PR that -keeps losing its verdict rather than an immediate refusal. +with whatever account owns `ETV_GITEA_TOKEN`/`ETV_GITEA_BASICAUTH`, and since ersatztv#845 it +**checks that it is an allow-listed one** — at the terminal that made the mistake, not one PR event +later. It reads the status back after posting, identifies its own write by state and description, and +refuses **before writing the comment** unless `.creator.login` is a member; a `creator: null` +(Actions-token) status gets its own message, since there is no account to name. The allow-list is +DERIVED from the `H10_REVIEWERS` literal in `review-verdict.yml` by `scripts/lib/h10-reviewers.sh`, +not restated beside it, so there is one declaration rather than two plus a parity test. + +What that changes is the *diagnostic*, not the safety direction: a non-allow-listed verdict was +always a stall, never a fail-open. Before, a changed writer credential reported success and each +*subsequent* PR event re-derived the status — to `pending` on a PR that needs a verdict, or to an +exemption **`success`** on a docs-only or Renovate-manifest one, which is the quieter and worse +half — so the symptom was a PR that kept losing its verdict rather than an immediate refusal. Now it +is an immediate refusal naming the account and the allow-list. **The residual, stated:** the check +runs after the POST, so a refused verdict leaves a non-inheritable status standing on the head with +no comment beside it. That is the `ask` half-state `release.verdict-writes-status-before-comment` +already designates as the safe one, and the gate re-derives the status itself on the next PR event; +it is deliberately not repaired here, because a second corrective write is the sticky-sentinel +mechanism ersatztv#849 is separately designing. This remains a *provenance* check, not an authentication one — an **allow-listed** collaborator's own write-scoped token can still POST a verdict they did not form, branch protection binds the context diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 5feb5f1a4..a4cad78f5 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -46,7 +46,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera | `ci.decisions-lifecycle-flake` | When `decisions lifecycle` is the **only** red job, do not investigate and do not create a new run to clear it — no rebase, no `--amend`, no no-op push; the operator reruns that single job from the Gitea UI. | 2026-07-21 | [link](records/ci/decisions-lifecycle-flake.md) | | `ci.docs-only-detect-shallow-safe` | The docs-only detect script must diff against `FETCH_HEAD` (always resolves after `git fetch`, even shallow) using a two-dot tree diff — not `origin/` with three-dot — because a `fetch-depth: 1` shallow clone has no remote-tracking ref and no merge-base, which silently fails the original detect into `docs_only=false` (full matrix, no functional error). A CI-behavior change must be verified by measuring the effect (job durations), not just a green check. | 2026-07-17 | [link](records/ci/docs-only-detect-shallow-safe.md) | | `ci.docs-only-skip-steps` | A docs-only change must still run every required job (`test`, `migrations`) so their commit-status contexts always report; each heavy job runs `scripts/ci-detect-docs-only.sh` first and gates its real STEPS on `if: steps.detect.outputs.docs_only != 'true'`, never `if:`-skips the whole job (an `if:`-skipped job reports `skipped`, not `success`, which branch protection may never unblock on). Detection biases toward running more on any doubt. | 2026-07-17 | [link](records/ci/docs-only-skip-steps.md) | -| `ci.exemption-provenance` | The three inputs the exemption decision rests on must each be bound to something the judged PR cannot mutate. (1) BASE — `scripts/pr-changed-files.sh` takes the expected base BRANCH as a REQUIRED 5th argument and re-reads it before and after paging, because `/pulls/{n}/files` diffs against the PR's live base and retargeting moves the answer without moving the head sha; the workflow passes `github.event.pull_request.base.ref` from the `pull_request_target` payload, which a retarget cannot rewrite. (2) BOT EXEMPTION — an author match is necessary but never sufficient: `pull_request.user.login` is the PR's immutable CREATOR while its head is not, so the exemption additionally requires EVERY changed path to be a dependency manifest (`Directory.Packages.props` or `.config/dotnet-tools.json`, and ONLY those — the npm manifests are excluded because `package.json` `scripts` are executed by CI). (3) INHERITED SUCCESS — the never-overwrite short-circuit fires for a `success` only when it is POSITIVELY identified as an APPROVED REVIEWER's verdict for THIS base, meaning a `.creator.login` that is a member of the workflow's `H10_REVIEWERS` allow-list (an existing `failure` takes the weaker ATTRIBUTABLE test and needs no membership, because inheriting a rejection can only withhold an exemption while re-deriving one can turn it green on an exempt PR) — non-null was too weak, since any account's credential satisfies it and `RENOVATE_TOKEN` is one that cannot be scoped down (#742) — AND a `Review-verdict:` description AND, when that description records a base (`(base: …)`, `release.verdict-status-check`), a base matching the PR's — tested by requiring the description to END with the exact literal `(base: )` and to contain exactly ONE such marker, never by extracting a value (see below); a present-but-different base is rejected, an absent one is not, since verdicts predating that convention carry none; every other shape, including any unrecognised one, is re-derived rather than trusted. The bot and docs-only exemptions are evaluated as INDEPENDENT predicates and the decision made afterwards, never as an `elif` chain. `edited` is in the workflow's `types:` so a retarget reclassifies — which gives DETECTION, not atomicity: status writes are not serialized, so a stale run can still post over a fresher one. That residual is now FENCED rather than merely tracked (NARROWED, not resolved — a retarget between the fence's final count and the POST still leaves a PERMANENT forged green, #849) — the job refuses to write at all if the PR's timeline retarget COUNT moved while it was classifying (`ci.verdict-write-retarget-fence`, #706) — leaving TWO windows, not one: the sub-round-trip window that no API without compare-and-set can close, AND the post-final-count/pre-POST window, which is not sub-round-trip and yields a PERMANENT green because the successor can consume the `edited` event and exit before the stale run posts last (#849). The PROTECTED path list additionally covers `CLAUDE.md` and `AGENTS.md` (#751) — they are not prose but the documents DEFINING the completion protocol, the merge-consent convention and the H10 rule, so protecting `.claude/` while the file specifying what it enforces stayed docs-only-exempt was the same self-exemption one directory over; driving the real classify body with a lone `CLAUDE.md` change produced an exemption `success`. `README.md` is deliberately not listed. It also covers `.codex/` (#711), which mirrors `.claude/hooks/` byte for byte including the merge-consent hook — latent while that directory is untracked, live the moment it is tracked; the list stays ENUMERATIVE rather than derived, because a derived rule would have to be evaluated against the very file list being classified. Reading the CURRENT status for input (3) must tolerate `statuses: null`: `GET /commits/{sha}/status` serialises a nil slice as `null`, not `[]`, on a head with no statuses yet, and an `array`-only gate made `read_existing_verdict` `exit 1` and post nothing at all (#751, `ci.workflow-run-body-no-expressions`) — `null` is accepted only when `total_count` is 0, so a body that merely lost its array is still refused. Path predicates are evaluated by COUNTING with `grep -c`, never `\| grep -q` (SIGPIPE inversion) and never a here-string (temp-space failure) — see `ci.grep-q-pipefail-inversion`. | 2026-07-29 | [link](records/ci/exemption-provenance.md) | +| `ci.exemption-provenance` | The three inputs the exemption decision rests on must each be bound to something the judged PR cannot mutate. (1) BASE — `scripts/pr-changed-files.sh` takes the expected base BRANCH as a REQUIRED 5th argument and re-reads it before and after paging, because `/pulls/{n}/files` diffs against the PR's live base and retargeting moves the answer without moving the head sha; the workflow passes `github.event.pull_request.base.ref` from the `pull_request_target` payload, which a retarget cannot rewrite. (2) BOT EXEMPTION — an author match is necessary but never sufficient: `pull_request.user.login` is the PR's immutable CREATOR while its head is not, so the exemption additionally requires EVERY changed path to be a dependency manifest (`Directory.Packages.props` or `.config/dotnet-tools.json`, and ONLY those — the npm manifests are excluded because `package.json` `scripts` are executed by CI). (3) INHERITED SUCCESS — the never-overwrite short-circuit fires for a `success` only when it is POSITIVELY identified as an APPROVED REVIEWER's verdict for THIS base, meaning a `.creator.login` that is a member of the workflow's `H10_REVIEWERS` allow-list (an existing `failure` takes the weaker ATTRIBUTABLE test and needs no membership, because inheriting a rejection can only withhold an exemption while re-deriving one can turn it green on an exempt PR) — non-null was too weak, since any account's credential satisfies it and `RENOVATE_TOKEN` is one that cannot be scoped down (#742) — AND a `Review-verdict:` description AND, when that description records a base (`(base: …)`, `release.verdict-status-check`), a base matching the PR's — tested by requiring the description to END with the exact literal `(base: )` and to contain exactly ONE such marker, never by extracting a value (see below); a present-but-different base is rejected, an absent one is not, since verdicts predating that convention carry none; every other shape, including any unrecognised one, is re-derived rather than trusted. The bot and docs-only exemptions are evaluated as INDEPENDENT predicates and the decision made afterwards, never as an `elif` chain. `edited` is in the workflow's `types:` so a retarget reclassifies — which gives DETECTION, not atomicity: status writes are not serialized, so a stale run can still post over a fresher one. That residual is now FENCED rather than merely tracked (NARROWED, not resolved — a retarget between the fence's final count and the POST still leaves a PERMANENT forged green, #849) — the job refuses to write at all if the PR's timeline retarget COUNT moved while it was classifying (`ci.verdict-write-retarget-fence`, #706) — leaving TWO windows, not one: the sub-round-trip window that no API without compare-and-set can close, AND the post-final-count/pre-POST window, which is not sub-round-trip and yields a PERMANENT green because the successor can consume the `edited` event and exit before the stale run posts last (#849). The PROTECTED path list additionally covers `CLAUDE.md` and `AGENTS.md` (#751) — they are not prose but the documents DEFINING the completion protocol, the merge-consent convention and the H10 rule, so protecting `.claude/` while the file specifying what it enforces stayed docs-only-exempt was the same self-exemption one directory over; driving the real classify body with a lone `CLAUDE.md` change produced an exemption `success`. `README.md` is deliberately not listed. It also covers `.codex/` (#711), which mirrors `.claude/hooks/` byte for byte including the merge-consent hook — latent while that directory is untracked, live the moment it is tracked; the list stays ENUMERATIVE rather than derived, because a derived rule would have to be evaluated against the very file list being classified. Reading the CURRENT status for input (3) must tolerate `statuses: null`: `GET /commits/{sha}/status` serialises a nil slice as `null`, not `[]`, on a head with no statuses yet, and an `array`-only gate made `read_existing_verdict` `exit 1` and post nothing at all (#751, `ci.workflow-run-body-no-expressions`) — `null` is accepted only when `total_count` is 0, so a body that merely lost its array is still refused. Path predicates are evaluated by COUNTING with `grep -c`, never `\| grep -q` (SIGPIPE inversion) and never a here-string (temp-space failure) — see `ci.grep-q-pipefail-inversion`. The WRITER is bound to the same allow-list rather than trusted to match it (#845): `scripts/post-review-verdict.sh` reads its own status back, identifies that write by state and description, and refuses before writing the comment unless `.creator.login` is a member — so a writer credential that is not a reviewer fails at the terminal that made the mistake instead of stalling the PR one event later. The list is DERIVED from the literal in this workflow by `scripts/lib/h10-reviewers.sh`, never restated: one declaration, not two plus a parity test. | 2026-07-29 | [link](records/ci/exemption-provenance.md) | | `ci.fetch-depth-never-grafts-a-complete-clone` | Any `git fetch` in CI tooling passes `--depth` only when `git rev-parse --is-shallow-repository` already answers `true`, and passes none on any other answer including an unreadable one. `git fetch --depth=N` GRAFTS a complete clone shallow: it writes `.git/shallow` and cuts history at N even though every object is already present, so a depth chosen for one consumer silently breaks every other consumer that checks out `fetch-depth: 0`. A shared script whose consumers disagree on checkout depth must ask the repository rather than assume. And whatever the fetch feeds — a version, a diff, a base revision — must be ASSERTED rather than defaulted: a fallback that cannot fail converts the graft into a plausible wrong answer that never reddens. | 2026-08-29 | [link](records/ci/fetch-depth-never-grafts-a-complete-clone.md) | | `ci.format-gate-folder-mode` | The blocking `format` CI job (and matching pre-commit hook) runs `dotnet format whitespace . --folder --include ` instead of loading the full MSBuild/Roslyn solution, cutting the gate from ~480s to ~0.5s with unchanged whitespace/charset coverage. | 2026-07-19 | [link](records/ci/format-gate-folder-mode.md) | | `ci.functional-e2e-harness` | The `functional-e2e` CI job boots the PR's own code from source via `dotnet run` (`scripts/e2e-local.sh`) and runs deterministic assertions (`scripts/e2e-functional.sh`) as an advisory (non-blocking) job, not a `build` dependency or required check. Originally curl-only; since #445 the same job carries a second, headless-browser step for the contracts curl cannot express — see `ci.ui-e2e-harness`. | 2026-07-16 | [link](records/ci/functional-e2e-harness.md) | diff --git a/docs/decisions/records/ci/exemption-provenance.md b/docs/decisions/records/ci/exemption-provenance.md index c63afbc18..516f65bc1 100644 --- a/docs/decisions/records/ci/exemption-provenance.md +++ b/docs/decisions/records/ci/exemption-provenance.md @@ -5,9 +5,9 @@ status: active since: '2026-07-29' supersedes: none superseded-by: none -rule: 'The three inputs the exemption decision rests on must each be bound to something the judged PR cannot mutate. (1) BASE — `scripts/pr-changed-files.sh` takes the expected base BRANCH as a REQUIRED 5th argument and re-reads it before and after paging, because `/pulls/{n}/files` diffs against the PR''s live base and retargeting moves the answer without moving the head sha; the workflow passes `github.event.pull_request.base.ref` from the `pull_request_target` payload, which a retarget cannot rewrite. (2) BOT EXEMPTION — an author match is necessary but never sufficient: `pull_request.user.login` is the PR''s immutable CREATOR while its head is not, so the exemption additionally requires EVERY changed path to be a dependency manifest (`Directory.Packages.props` or `.config/dotnet-tools.json`, and ONLY those — the npm manifests are excluded because `package.json` `scripts` are executed by CI). (3) INHERITED SUCCESS — the never-overwrite short-circuit fires for a `success` only when it is POSITIVELY identified as an APPROVED REVIEWER''s verdict for THIS base, meaning a `.creator.login` that is a member of the workflow''s `H10_REVIEWERS` allow-list (an existing `failure` takes the weaker ATTRIBUTABLE test and needs no membership, because inheriting a rejection can only withhold an exemption while re-deriving one can turn it green on an exempt PR) — non-null was too weak, since any account''s credential satisfies it and `RENOVATE_TOKEN` is one that cannot be scoped down (#742) — AND a `Review-verdict:` description AND, when that description records a base (`(base: …)`, `release.verdict-status-check`), a base matching the PR''s — tested by requiring the description to END with the exact literal `(base: )` and to contain exactly ONE such marker, never by extracting a value (see below); a present-but-different base is rejected, an absent one is not, since verdicts predating that convention carry none; every other shape, including any unrecognised one, is re-derived rather than trusted. The bot and docs-only exemptions are evaluated as INDEPENDENT predicates and the decision made afterwards, never as an `elif` chain. `edited` is in the workflow''s `types:` so a retarget reclassifies — which gives DETECTION, not atomicity: status writes are not serialized, so a stale run can still post over a fresher one. That residual is now FENCED rather than merely tracked (NARROWED, not resolved — a retarget between the fence''s final count and the POST still leaves a PERMANENT forged green, #849) — the job refuses to write at all if the PR''s timeline retarget COUNT moved while it was classifying (`ci.verdict-write-retarget-fence`, #706) — leaving TWO windows, not one: the sub-round-trip window that no API without compare-and-set can close, AND the post-final-count/pre-POST window, which is not sub-round-trip and yields a PERMANENT green because the successor can consume the `edited` event and exit before the stale run posts last (#849). The PROTECTED path list additionally covers `CLAUDE.md` and `AGENTS.md` (#751) — they are not prose but the documents DEFINING the completion protocol, the merge-consent convention and the H10 rule, so protecting `.claude/` while the file specifying what it enforces stayed docs-only-exempt was the same self-exemption one directory over; driving the real classify body with a lone `CLAUDE.md` change produced an exemption `success`. `README.md` is deliberately not listed. It also covers `.codex/` (#711), which mirrors `.claude/hooks/` byte for byte including the merge-consent hook — latent while that directory is untracked, live the moment it is tracked; the list stays ENUMERATIVE rather than derived, because a derived rule would have to be evaluated against the very file list being classified. Reading the CURRENT status for input (3) must tolerate `statuses: null`: `GET /commits/{sha}/status` serialises a nil slice as `null`, not `[]`, on a head with no statuses yet, and an `array`-only gate made `read_existing_verdict` `exit 1` and post nothing at all (#751, `ci.workflow-run-body-no-expressions`) — `null` is accepted only when `total_count` is 0, so a body that merely lost its array is still refused. Path predicates are evaluated by COUNTING with `grep -c`, never `| grep -q` (SIGPIPE inversion) and never a here-string (temp-space failure) — see `ci.grep-q-pipefail-inversion`.' -signals: 'verdict inherited from a bot token, RENOVATE_TOKEN posts a review verdict, who may post an h10 verdict, H10_REVIEWERS allow-list, forged review-verdict exemption, retarget race against the docs-only classifier, PR base changed mid-run, hijacked Renovate branch, bot exemption on a code change, machine-written success inherited as a verdict, status creator null vs user, never overwrite a human verdict, exemption chain skips docs-only for bots, why is my Renovate PR asking for a verdict, base ref binding on pr-changed-files.sh · paths: `.gitea/workflows/review-verdict.yml`, `scripts/pr-changed-files.sh`, `.claude/hooks/pretooluse-merge-consent.sh`, `scripts/tests/test_pr_changed_files.py` · issues: #849, #845, #742, #698, #697, #672, #663, #649, #632' -mechanics: '`scripts/pr-changed-files.sh ` (5 args; a 4-arg call exits 2); workflow env `BASE_REF: ${{ github.event.pull_request.base.ref }}`; `BOT_MANIFESTS` anchored allow-list; `H10_REVIEWERS="timothy"` declared as a literal in the classify body (a repo `vars:` entry or secret is settable without a PR); membership by exact POSIX `[ = ]` comparison over word-split entries, never an UNQUOTED right-hand side — `[[ $rv == $ex_creator ]]` makes it a pattern, while a quoted RHS under `[[ ]]` is literal (probed, bash 5.3); POSIX `[ = ]` cannot glob at all, which is why it is used and never `grep -xF` (an API-supplied creator containing a newline reads as several patterns); `read_existing_verdict` sets `ex_attributable` (creator non-null AND `^Review-verdict:` AND base OK) and derives `ex_human` from it by membership; the INHERITANCE short-circuit reads `ex_human`, the LAST-MOMENT RE-READ reads `ex_attributable` plus a change against the state/creator/description triple snapshotted at the first read, and the post-write raced `jq` stays broad on `creator != null`; `types: [opened, reopened, synchronize, ready_for_review, edited]`' +rule: 'The three inputs the exemption decision rests on must each be bound to something the judged PR cannot mutate. (1) BASE — `scripts/pr-changed-files.sh` takes the expected base BRANCH as a REQUIRED 5th argument and re-reads it before and after paging, because `/pulls/{n}/files` diffs against the PR''s live base and retargeting moves the answer without moving the head sha; the workflow passes `github.event.pull_request.base.ref` from the `pull_request_target` payload, which a retarget cannot rewrite. (2) BOT EXEMPTION — an author match is necessary but never sufficient: `pull_request.user.login` is the PR''s immutable CREATOR while its head is not, so the exemption additionally requires EVERY changed path to be a dependency manifest (`Directory.Packages.props` or `.config/dotnet-tools.json`, and ONLY those — the npm manifests are excluded because `package.json` `scripts` are executed by CI). (3) INHERITED SUCCESS — the never-overwrite short-circuit fires for a `success` only when it is POSITIVELY identified as an APPROVED REVIEWER''s verdict for THIS base, meaning a `.creator.login` that is a member of the workflow''s `H10_REVIEWERS` allow-list (an existing `failure` takes the weaker ATTRIBUTABLE test and needs no membership, because inheriting a rejection can only withhold an exemption while re-deriving one can turn it green on an exempt PR) — non-null was too weak, since any account''s credential satisfies it and `RENOVATE_TOKEN` is one that cannot be scoped down (#742) — AND a `Review-verdict:` description AND, when that description records a base (`(base: …)`, `release.verdict-status-check`), a base matching the PR''s — tested by requiring the description to END with the exact literal `(base: )` and to contain exactly ONE such marker, never by extracting a value (see below); a present-but-different base is rejected, an absent one is not, since verdicts predating that convention carry none; every other shape, including any unrecognised one, is re-derived rather than trusted. The bot and docs-only exemptions are evaluated as INDEPENDENT predicates and the decision made afterwards, never as an `elif` chain. `edited` is in the workflow''s `types:` so a retarget reclassifies — which gives DETECTION, not atomicity: status writes are not serialized, so a stale run can still post over a fresher one. That residual is now FENCED rather than merely tracked (NARROWED, not resolved — a retarget between the fence''s final count and the POST still leaves a PERMANENT forged green, #849) — the job refuses to write at all if the PR''s timeline retarget COUNT moved while it was classifying (`ci.verdict-write-retarget-fence`, #706) — leaving TWO windows, not one: the sub-round-trip window that no API without compare-and-set can close, AND the post-final-count/pre-POST window, which is not sub-round-trip and yields a PERMANENT green because the successor can consume the `edited` event and exit before the stale run posts last (#849). The PROTECTED path list additionally covers `CLAUDE.md` and `AGENTS.md` (#751) — they are not prose but the documents DEFINING the completion protocol, the merge-consent convention and the H10 rule, so protecting `.claude/` while the file specifying what it enforces stayed docs-only-exempt was the same self-exemption one directory over; driving the real classify body with a lone `CLAUDE.md` change produced an exemption `success`. `README.md` is deliberately not listed. It also covers `.codex/` (#711), which mirrors `.claude/hooks/` byte for byte including the merge-consent hook — latent while that directory is untracked, live the moment it is tracked; the list stays ENUMERATIVE rather than derived, because a derived rule would have to be evaluated against the very file list being classified. Reading the CURRENT status for input (3) must tolerate `statuses: null`: `GET /commits/{sha}/status` serialises a nil slice as `null`, not `[]`, on a head with no statuses yet, and an `array`-only gate made `read_existing_verdict` `exit 1` and post nothing at all (#751, `ci.workflow-run-body-no-expressions`) — `null` is accepted only when `total_count` is 0, so a body that merely lost its array is still refused. Path predicates are evaluated by COUNTING with `grep -c`, never `| grep -q` (SIGPIPE inversion) and never a here-string (temp-space failure) — see `ci.grep-q-pipefail-inversion`. The WRITER is bound to the same allow-list rather than trusted to match it (#845): `scripts/post-review-verdict.sh` reads its own status back, identifies that write by state and description, and refuses before writing the comment unless `.creator.login` is a member — so a writer credential that is not a reviewer fails at the terminal that made the mistake instead of stalling the PR one event later. The list is DERIVED from the literal in this workflow by `scripts/lib/h10-reviewers.sh`, never restated: one declaration, not two plus a parity test.' +signals: 'verdict inherited from a bot token, RENOVATE_TOKEN posts a review verdict, who may post an h10 verdict, H10_REVIEWERS allow-list, forged review-verdict exemption, retarget race against the docs-only classifier, PR base changed mid-run, hijacked Renovate branch, bot exemption on a code change, machine-written success inherited as a verdict, status creator null vs user, never overwrite a human verdict, exemption chain skips docs-only for bots, why is my Renovate PR asking for a verdict, base ref binding on pr-changed-files.sh · paths: `.gitea/workflows/review-verdict.yml`, `scripts/pr-changed-files.sh`, `.claude/hooks/pretooluse-merge-consent.sh`, `scripts/tests/test_pr_changed_files.py`, `scripts/post-review-verdict.sh`, `scripts/lib/h10-reviewers.sh` · issues: #849, #845, #742, #698, #697, #672, #663, #649, #632' +mechanics: '`scripts/pr-changed-files.sh ` (5 args; a 4-arg call exits 2); workflow env `BASE_REF: ${{ github.event.pull_request.base.ref }}`; `BOT_MANIFESTS` anchored allow-list; `H10_REVIEWERS="timothy"` declared as a literal in the classify body (a repo `vars:` entry or secret is settable without a PR); `scripts/lib/h10-reviewers.sh` derives that same literal for the write side by an anchored single-assignment parse and refuses on 0 or >1 matches, on a non-plain-login entry, or on an empty list; membership by exact POSIX `[ = ]` comparison over word-split entries, never an UNQUOTED right-hand side — `[[ $rv == $ex_creator ]]` makes it a pattern, while a quoted RHS under `[[ ]]` is literal (probed, bash 5.3); POSIX `[ = ]` cannot glob at all, which is why it is used and never `grep -xF` (an API-supplied creator containing a newline reads as several patterns); `read_existing_verdict` sets `ex_attributable` (creator non-null AND `^Review-verdict:` AND base OK) and derives `ex_human` from it by membership; the INHERITANCE short-circuit reads `ex_human`, the LAST-MOMENT RE-READ reads `ex_attributable` plus a change against the state/creator/description triple snapshotted at the first read, and the post-write raced `jq` stays broad on `creator != null`; `types: [opened, reopened, synchronize, ready_for_review, edited]`' --- `ci.gate-trigger-base-resolved` stopped a PR supplying the gate's own *definition*. This closes the @@ -219,22 +219,41 @@ verified when a mark exists, a sticky sentinel when it does not, and a CHAINED t real output into run N+1. Two lines inside a provenance change was the wrong size for it — the attempt is recorded because the next reader will otherwise re-attempt it the same way. -**A coupling this record does NOT assert, tracked as #845 instead.** `post-review-verdict.sh` posts with -whatever account owns `ETV_GITEA_TOKEN`/`ETV_GITEA_BASICAUTH` and never checks whose it is. If that -ever stops being an allow-listed account, every verdict silently stops being inheritable and each -later event re-derives it — to `pending` on a PR that needs a verdict, or to an exemption `success` on -a docs-only or Renovate-manifest one, which is the quieter and worse half. Either way the verdict is -gone, and the only diagnostic is a line in a job log. -Correct today — verified live 2026-08-26, reproduce with `GET /api/v1/user` (login `timothy`) and -`GET /api/v1/admin/users?limit=50` (exactly `renovate`, `timothy`) — but nothing keeps it correct -(#845). The job DOES name the creator and the allow-list whenever it declines to inherit — but in the -WORKFLOW RUN, while the mistake is made at the terminal running `post-review-verdict.sh`, which -reports success either way. That gap is what #845 is about, and it is why a louder annotation was not -the answer: an earlier draft added a `::warning::` alongside that line, and it was withdrawn after -producing three defects in three rounds (a message that contradicted itself for an allow-listed -creator, an unescaped API value interpolated into a workflow command, and a test asserting its absence -on a path that exits two guards earlier and so could never fail). The signal has to reach the WRITER, -not be repeated more loudly to the reader. +**The writer/gate coupling, ASSERTED at the writer since #845.** `post-review-verdict.sh` posts with +whatever account owns `ETV_GITEA_TOKEN`/`ETV_GITEA_BASICAUTH`. It used to never ask whose that was, and +the two values are coupled: the day the writer credential stops being an allow-listed account, every +verdict silently stops being inheritable and each later event re-derives it — to `pending` on a PR that +needs a verdict, or to an exemption `success` on a docs-only or Renovate-manifest one, which is the +quieter and worse half. Either way the verdict is gone. It now READS THE STATUS BACK after posting it, +identifies its own write by state and description, and refuses — before the comment, so the surviving +half-state is the `ask` one — unless `.creator.login` is on the allow-list. A `creator: null` +(Actions-token) status is refused with its own message, because there is no account to name and "add +them to the allow-list" would be the wrong advice. + +The allow-list is not restated on the writer side. `scripts/lib/h10-reviewers.sh` DERIVES it from the +`H10_REVIEWERS` literal in this workflow, so there is one declaration rather than two held together by +a parity test — the shape `testing.guard-derives-population-from-source` records six failed rounds +against. It is a parse rather than a shared declaration both sides source, because the gate runs +against a checkout of the PR BASE sha: a PR whose base predates such a file would not have it, and a +missing `source` under `set -euo pipefail` kills the job, which posts no `review-verdict/h10` at all +and blocks every merge including the repair (`block_admin_merge_override: true`). A fallback list for +that case would reintroduce the second copy. So the derivation runs on the side that can fail safely +and the body of this workflow is untouched. The parse admits exactly one anchored assignment or +refuses; `test_pr_changed_files.py::test_the_H10_REVIEWERS_list_is_glob_free_and_non_empty` reads the +same literal with the same anchors, so a shape change reddens CI on the PR that makes it. + +The allow-list was `timothy` and the instance held exactly `renovate` and `timothy` when this was +measured on 2026-08-26 (`GET /api/v1/user`, `GET /api/v1/admin/users?limit=50`). That measurement is +no longer what keeps the coupling correct, which is the point of the change. + +**Why the signal had to reach the WRITER.** The job already names the creator and the allow-list +whenever it declines to inherit — but in the WORKFLOW RUN, while the mistake is made at the terminal +running `post-review-verdict.sh`, which reported success either way. An earlier draft tried to fix +that by shouting louder at the reader: a `::warning::` alongside that line, withdrawn after producing +three defects in three rounds (a message that contradicted itself for an allow-listed creator, an +unescaped API value interpolated into a workflow command, and a test asserting its absence on a path +that exits two guards earlier and so could never fail). Recorded so it is not re-attempted: more +volume in the run was never the missing piece. **What #742 does NOT close, restated because the allow-list invites the wrong reading.** An allow-listed collaborator's own write-scoped token can still POST a verdict nobody formed. Branch diff --git a/docs/guard-inventory.md b/docs/guard-inventory.md index f626d90aa..85abde7c7 100644 --- a/docs/guard-inventory.md +++ b/docs/guard-inventory.md @@ -227,7 +227,7 @@ recorded as unexamined rather than as cleared. | `scripts/e2e-ui.sh` | nothing (drives the Playwright flows) | TOOLING | NONE | — | | `scripts/hook-fire-log.sh` | nothing (records that each hook fired, and reports it) | TOOLING | NONE | — | | `scripts/jq-preflight.sh` | the `script-tests` job, on a jq version change | GUARD | BEHAVIOUR-ONLY | `test_jq_preflight.py::test_below_the_floor_is_LOUD` | -| `scripts/post-review-verdict.sh` | nothing (writes the verdict status) | GUARD | BEHAVIOUR-ONLY | `test_post_review_verdict.py::test_never_retargets_the_verdict_at_the_new_head` | +| `scripts/post-review-verdict.sh` | a verdict the gate will not inherit being reported as posted | GUARD | MUTATION | `test_post_review_verdict.py::test_a_verdict_posted_by_an_ALLOWLISTED_account_is_accepted` | | `scripts/pr-changed-files.sh` | the verdict exemption, on an incomplete enumeration | GUARD | BEHAVIOUR-ONLY | `test_pr_changed_files.py::test_a_SHORT_page_does_not_end_the_enumeration` | | `scripts/prove-fix.sh` | the `prove-fix` job, on a commit whose `Proves:` trailer names a test that passes without the fix | GUARD | MUTATION | `test_prove_fix.py::test_MUTATION_disarming_the_UNPROVEN_clause_reddens_the_refusal_test` | | `scripts/update-openapi.sh` | nothing (regenerates the spec) | TOOLING | NONE | — | @@ -375,7 +375,7 @@ clause-provable and the entry is regraded. ## What the numbers say -45 guards, 6 tooling scripts, 23 proof files. **24 guards carry a mutation proof; 6 are +45 guards, 6 tooling scripts, 23 proof files. **25 guards carry a mutation proof; 5 are behaviour-only; 15 have none.** These figures are asserted against the table by `test_the_summary_counts_match_the_table`, because a hand-maintained summary of a table is a second copy of it — the duplication family this change argues against, and one that has already drifted diff --git a/docs/remote-state-inventory.md b/docs/remote-state-inventory.md index 00cd13728..137a843e7 100644 --- a/docs/remote-state-inventory.md +++ b/docs/remote-state-inventory.md @@ -96,7 +96,7 @@ classifications differ; otherwise the strictest applies and the Note names the e | Site | Class | Note | |---|---|---| -| `scripts/post-review-verdict.sh` — commit-status write | `PINNED` | Re-reads the PR and compares **both** `.head.sha` and `.base.ref` immediately before the POST, and `die`s (exit 1, no status written) on a mismatch **or on a field it cannot read**. That last clause is load-bearing: guarding both comparisons with `[ -n "$x" ] &&` alone makes a well-formed 2xx body that merely omits the field a no-op, and the status is posted having confirmed nothing. Regression-tested against the real predecessor (#778), since the redundant-looking `-z` arm alone mutates green. Closes #706 and #632 for this path by read-compare-refuse, not by CAS: Gitea's status API offers no conditional write. Residual closed on the write ORDER since #792: the status is written first and the comment second, so a refusal can no longer leave a verdict comment with no status behind it — the only reachable half-state is a status with no comment, which the merge hook resolves as `ask` (`release.verdict-writes-status-before-comment`). | +| `scripts/post-review-verdict.sh` — commit-status write | `PINNED` | Re-reads the PR and compares **both** `.head.sha` and `.base.ref` immediately before the POST, and `die`s (exit 1, no status written) on a mismatch **or on a field it cannot read**. That last clause is load-bearing: guarding both comparisons with `[ -n "$x" ] &&` alone makes a well-formed 2xx body that merely omits the field a no-op, and the status is posted having confirmed nothing. Regression-tested against the real predecessor (#778), since the redundant-looking `-z` arm alone mutates green. Closes #706 and #632 for this path by read-compare-refuse, not by CAS: Gitea's status API offers no conditional write. Residual closed on the write ORDER since #792: the status is written first and the comment second, so a refusal can no longer leave a verdict comment with no status behind it — the only reachable half-state is a status with no comment, which the merge hook resolves as `ask` (`release.verdict-writes-status-before-comment`). Since #845 the status is also READ BACK after the POST and refused unless it is the write just made AND its `.creator.login` is on the allow-list derived from the gate — the same read-compare-refuse shape, applied to WHOSE verdict it is rather than to which commit it covers. That read is check-then-act too and is graded with this row rather than separately: it can only withhold this tool's success report, never authorize anything, and the residual it leaves — a non-inheritable status standing with no comment beside it — is the `ask` half-state above. | | `scripts/pr-changed-files.sh` — paged file enumeration | `UNSAFE-KNOWN` | #707's fix: `.base.ref`, `.base.sha` and `.head.sha` are captured before paging and re-checked after, and any *observed* movement fails the whole enumeration closed rather than emitting a short list. But before-and-after equality is **ABA-vulnerable** — a `main → scratch → main` retarget during paging can return the same ref and, if nothing merged meanwhile, the same base sha, while the pages in between were diffed against the scratch base. The script's own comment says it narrows rather than erases — "any movement fails" would be stronger than the code. Accepted here because the enumerator cannot close it alone, but be exact about what the caller-side fence does and does not cover: `ci.verdict-write-retarget-fence` counts `change_target_branch` events, so it catches the BASE alias and **nothing else**. A HEAD alias — a force-push `H1 -> H2 -> H1` during pagination — leaves the final `.head.sha` comparison equal while the middle pages were enumerated against `H2`, and NOTHING inside this script can see it. **Fenced at the enforced caller since #803** (2026-08-28): the same timeline walk now also counts `pull_push`, so a head that moved at all during classification withholds the write — subject to that walk's own terminator, which is defeatable by a page of filtered rows (**#870**, pre-existing and equally affecting the base axis). The grade stays `UNSAFE-KNOWN` for the SCRIPT, because the script's own guarantee is unchanged and one-way — a caller that does not run the fence inherits the alias. Enumeration bound to an immutable tree remains unavailable: re-probed at 1.27.1 on 2026-08-28, `compare/{base}...{head}` still returns no `files` key. | | `scripts/select-queue.sh` — issue list, then per-issue `/dependencies` | `UNSAFE-KNOWN` | The open-issue list (labels, milestone, priority) is snapshotted once; per-candidate dependency reads happen seconds later and never re-read the issue's own labels, so an issue claimed `in-progress` in that gap still appears on the shortlist. Accepted: the script authorizes **no write**. The real gate is the four-way claim check in `process.parallel-session-claim`, which runs after selection and re-reads live state by construction. Tightening this would move a check that must be adversarial into a tool that is advisory. | | `scripts/ci-detect-already-validated.sh` — prior-head combined status | `UNSAFE-KNOWN` | Reads the PR head's status and emits `skip=true`, with nothing re-checking before the consuming job runs. Accepted and narrow: the skip elides only **re-running** test/migrations on a tree already validated; the `build` job still builds and pushes unconditionally, so no image ever ships from unvalidated source. | @@ -111,6 +111,7 @@ classifications differ; otherwise the strictest applies and the Note names the e | `scripts/ci-detect-docs-only.sh` — `git fetch origin "$base"`, then diffs the fetched tip against HEAD to emit `docs_only`, which gates whether the required test/migrations jobs run their real steps | `UNSAFE-KNOWN` | Read-then-act with no re-check between the fetch and the emitted value, and the decision genuinely gates required CI work. Accepted because the script is deliberately asymmetric: every ambiguous, undeterminable or shallow-checkout case resolves to `docs_only=false` (run everything), and only an exact unanimous all-docs diff yields `true` — so a stale or racing base read can at worst cause an unnecessary full run, never a skipped one (#416). | | `scripts/refresh-shared-checkout.sh` — `git fetch origin main`, then `git merge --ff-only origin/main` and a conditional `npm ci` | `UNSAFE-KNOWN` | Fetch-then-act with no re-check between the fetch and the merge. Accepted because every action is self-refusing or reversible: `--ff-only` fails harmlessly rather than diverging if the ref moved on, the script refuses outright when the tree is not clean `main` or is ahead or mid-rebase, and this is a developer-convenience checkout rather than a release or merge-authorization path — a stale read costs one extra fetch next run, never lost work. | | `scripts/lib/review-verdict-vocabulary.sh` | `N/A` | Reads nothing at all — a sourced declaration of the H10 verdict word list plus pure functions over it; it makes no call, local or remote. Listed because it is in this inventory's scope (`scripts/**/*.sh`), not because it has a remote-state shape. | +| `scripts/lib/h10-reviewers.sh` | `N/A` | Reads no live remote state — it derives the gate's `H10_REVIEWERS` allow-list by parsing one anchored assignment out of the LOCAL `.gitea/workflows/review-verdict.yml`, and makes no call of its own. The read-then-act it feeds belongs to its caller's row above: `post-review-verdict.sh` compares the derived list against a creator it reads back from the server. Deliberately no env-var override of the file it reads — an env var choosing which tree answers a security question is an unsound input (#858). | | `scripts/check-review-verdict.sh` | `N/A` | Reads no live remote state itself — classifies a comments JSON payload supplied on stdin; the fetch belongs to the caller's row. | | `scripts/check-required-contexts.sh` | `N/A` | Reads no live remote state itself — classifies a `branch_protections` payload supplied on stdin; the fetch belongs to the caller's row (`.claude/hooks/pretooluse-merge-consent.sh` — guard-scope freshness). | | `scripts/lib/branch-rule-classifier.jq` | `N/A` | Reads nothing at all — a jq program over a `branch_protections` payload its caller supplies, resolving which protection rule governs a branch. Loaded by both `pretooluse-merge-consent.sh` and `check-required-contexts.sh`; every fetch belongs to those callers' rows. | diff --git a/scripts/lib/h10-reviewers.sh b/scripts/lib/h10-reviewers.sh new file mode 100644 index 000000000..9b7a9dec5 --- /dev/null +++ b/scripts/lib/h10-reviewers.sh @@ -0,0 +1,189 @@ +# shellcheck shell=bash +# h10-reviewers.sh — WHOSE verdicts the H10 gate will inherit, DERIVED from the gate itself +# (ersatztv#845). +# +# SOURCED, NEVER EXECUTED. It defines pure functions over one file and takes no action of its own, +# so it is deliberately not executable and carries no shebang. +# +# WHY THIS FILE EXISTS. `.gitea/workflows/review-verdict.yml` inherits an existing +# `review-verdict/h10=success` only when the status's `.creator.login` is a member of its +# `H10_REVIEWERS` allow-list (ersatztv#742). `scripts/post-review-verdict.sh` is the tool that WRITES +# those verdicts, with whatever account owns `ETV_GITEA_TOKEN` / `ETV_GITEA_BASICAUTH`. The two +# values are coupled and nothing asserted the coupling: the day the writer credential stops being an +# allow-listed account — a service token, a second machine, a renamed account, a bot minted for +# automation — every verdict is still WRITTEN, the tool still reports success, and the gate silently +# re-derives it on the next PR event. A repo-wide merge stall whose only diagnostic was a +# `::warning::` in a workflow run nobody reads. +# +# THERE IS NO SECOND COPY OF THE LIST HERE, on purpose. The workflow literal is the ONE declaration +# and this file DERIVES from it, the way `review-verdict-vocabulary.sh` made one word list serve both +# the read and the write side (ersatztv#788). A hand-copied allow-list held together by a parity test +# is the shape that record spent six rounds failing to converge on. +# +# WHY A PARSE RATHER THAN A SHARED DECLARATION BOTH SIDES SOURCE. That would be the better shape and +# it is not available. The gate runs under `pull_request_target` against a checkout of the PR BASE +# sha, so a PR whose base predates the introduction of a new `scripts/lib/` file would not have it — +# the same condition the `jq preflight` step already handles by skipping. Under `set -euo pipefail` a +# missing source is a dead job, and a dead job posts no `review-verdict/h10` at all, which blocks +# EVERY merge to `main` including the PR that would repair it (`block_admin_merge_override: true`, +# ersatztv#743). Writing a fallback list for that case reintroduces the second copy. So the +# derivation runs on the side that can fail safely — this one — and the gate body is untouched. +# +# WHAT THE PARSE IS ALLOWED TO BE. Exactly one anchored assignment line, or a refusal. That is not a +# shell parser and does not try to be: `testing.guard-derives-population-from-source` records why a +# regex over shell source does not converge when the target is an open-ended construct. The target +# here is closed — `test_pr_changed_files.py::test_the_H10_REVIEWERS_list_is_glob_free_and_non_empty` +# reads the same literal with the same anchors and already fails the suite if the workflow stops +# declaring it as a single double-quoted assignment, so a shape change reddens CI on the PR that +# makes it rather than going stale here. +# +# SNAPSHOT BOUNDARY, stated because it is a real limit and not a defect: this reads the workflow in +# the LOCAL checkout, while the gate that actually runs is the one at `origin/main` (base-resolved). +# On a branch that edits `H10_REVIEWERS` the two differ until it merges. That is the correct +# approximation — the alternative is a live remote read on the merge-consent write path — and CI +# holds them consistent, because `.gitea/` cannot ride a docs-only exemption. +# +# NO ENVIRONMENT VARIABLE SELECTS THE SOURCE FILE. The path is derived from this file own location, +# and a caller may pass one explicitly; there is deliberately no `ETV_*_WORKFLOW` override, because +# an env var that chooses which tree answers a security question is an unsound input (ersatztv#858 +# is the same shape one file over). + +# --- The default source: the shipped gate definition. -------------------------------------------- +# Resolved relative to THIS FILE, never to the caller cwd — `post-review-verdict.sh` is run from +# whatever directory an operator happens to be in. +ETV_H10_REVIEWERS_WORKFLOW='' +if _etv_h10_root=$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." 2>/dev/null && pwd); then + ETV_H10_REVIEWERS_WORKFLOW="$_etv_h10_root/.gitea/workflows/review-verdict.yml" +fi +unset _etv_h10_root + +# --- The validation sentinel. -------------------------------------------------------------------- +# Reset to 0 HERE, at load time, for the two reasons `review-verdict-vocabulary.sh` sets out at +# length: it defeats an inherited `ETV_H10_REVIEWERS_OK=1` from the environment, and it makes +# "derived successfully" a DATA dependency the query function can require rather than a control-flow +# gate a caller is trusted to have taken. Under `set -u` an unbound-variable error inside a function +# aborts the function but not the script, and in the `if ! f` form NEITHER branch is then taken — +# execution simply continues past the gate. A data dependency cannot be skipped that way. +ETV_H10_REVIEWERS_OK=0 +ETV_H10_REVIEWERS='' + +# --- The split idiom, stated once. --------------------------------------------------------------- +# Both functions below turn the space-separated list into the positional parameters with PATHNAME +# EXPANSION OFF, then restore `-f` to whatever the caller had. It is written out at each site rather +# than factored into a helper because a helper cannot set its caller positional parameters, and +# returning the words through a string would reintroduce a split — of a value that may contain a +# newline — at the other end. +# +# Getting this wrong is the documented fail-open, not a style point: `for x in $list` and +# `$(printf %s "$list")` both glob, so a `*` entry expands to the FILENAMES around it, and any of +# those matching the plain-login class below would validate cleanly and enter the allow-list as a +# real reviewer. That is the defect `review-verdict-vocabulary.sh` records against its own word list, +# reached one file over through the allow-list. + +# --- The derivation. ----------------------------------------------------------------------------- +# Sets `ETV_H10_REVIEWERS` and the sentinel. Returns 0 when the allow-list is usable, 1 otherwise +# (message on stderr). It never exits: the consumer decides its own exit semantics. +# +# $1 — the workflow file to read; defaults to the shipped one resolved above. +etv_h10_reviewers_load() { + local src="${1:-${ETV_H10_REVIEWERS_WORKFLOW:-}}" + local count value entry n=0 glob_was_off=0 + + ETV_H10_REVIEWERS_OK=0 + ETV_H10_REVIEWERS='' + + if [ -z "$src" ]; then + printf 'h10 reviewers: could not resolve the gate definition from the location of this library, and no path was passed\n' >&2 + return 1 + fi + if [ ! -r "$src" ]; then + printf 'h10 reviewers: %s is missing or unreadable, so who the gate accepts cannot be derived\n' "$src" >&2 + return 1 + fi + + # COUNT the anchored assignments, never `grep -q`. Two separate reasons, both recorded because each + # has cost this repo a round: `grep -q` closes the pipe early and inverts under `pipefail` on large + # input (`ci.grep-q-pipefail-inversion`), and — the reason that matters here — a boolean cannot + # tell ONE assignment from TWO. The shell runs the LAST assignment executed, so a second or + # conditional one would leave this deriving a value the gate does not use. `grep -c` reads a FILE + # argument, so there is no pipe to invert in the first place. + count=$(grep -cE '^[[:space:]]*H10_REVIEWERS="[^"]*"[[:space:]]*$' "$src") || count=0 + if [ "$count" != 1 ]; then + printf 'h10 reviewers: %s carries %s anchored H10_REVIEWERS assignments, not exactly 1 — refusing to guess which one the gate runs with\n' "$src" "$count" >&2 + return 1 + fi + + value=$(sed -n 's/^[[:space:]]*H10_REVIEWERS="\([^"]*\)"[[:space:]]*$/\1/p' "$src") || value='' + + # Validate every entry against the same character class the workflow own lint enforces. It is not + # cosmetic on either side: the gate membership loop word-splits the list UNQUOTED, so `*`, `?` or + # `[` there would be matched against the runner cwd and could silently change who the gate accepts. + case "$-" in *f*) glob_was_off=1 ;; esac + set -f + # shellcheck disable=SC2086 # deliberate word-split of the space-separated list, globbing off + set -- $value + [ "$glob_was_off" = 1 ] || set +f + for entry in "$@"; do + case "$entry" in + *[!A-Za-z0-9._-]*) + printf 'h10 reviewers: %s is not a plain login; * ? and [ are glob metacharacters in the membership loop of the gate\n' "$entry" >&2 + return 1 + ;; + esac + n=$((n + 1)) + done + + # Emptiness is checked on the SPLIT COUNT, not on the raw string. A value of " " is non-empty as + # a string and splits to nothing, and an emptied list is not a harmless default: the gate loop + # `for rv in ""` iterates zero times, so every verdict from every account would stop being + # inherited and `pending` would be re-posted over real human verdicts forever. + if [ "$n" -eq 0 ]; then + printf 'h10 reviewers: %s declares an EMPTY H10_REVIEWERS — no verdict from any account could be inherited\n' "$src" >&2 + return 1 + fi + + ETV_H10_REVIEWERS="$value" + # The ONLY assignment to 1 in this file, and it is the last statement of the successful path. Any + # earlier `return 1`, and any abort part-way through, leaves the sentinel at 0. + ETV_H10_REVIEWERS_OK=1 + return 0 +} + +# --- Derived view: is this login one whose verdict the gate would inherit? ----------------------- +# THREE outcomes, deliberately, because two would conflate them: 0 = a member, 1 = NOT a member, +# 2 = CANNOT ANSWER (the derivation never ran, or failed). A caller that treats "cannot answer" as +# "not a member" turns a broken checkout into a refusal, which is survivable; one that treats it as +# "member" turns it into a silent pass, which is the failure this file exists to prevent. Both are +# wrong to guess at, so the third code makes the caller say which it meant. +etv_h10_reviewers_contains() { + local login="${1:-}" entry glob_was_off=0 + + if [ "${ETV_H10_REVIEWERS_OK:-0}" != 1 ]; then + printf 'h10 reviewers: the allow-list was never derived (call etv_h10_reviewers_load first)\n' >&2 + return 2 + fi + + case "$-" in *f*) glob_was_off=1 ;; esac + set -f + # shellcheck disable=SC2086 # deliberate word-split of the space-separated list, globbing off + set -- $ETV_H10_REVIEWERS + [ "$glob_was_off" = 1 ] || set +f + + for entry in "$@"; do + # POSIX `[ = ]`, exactly as the gate compares. Never `[[ $entry == $login ]]` — an unquoted + # right-hand side under `[[ ]]` is a PATTERN, not a literal — and never `grep -xF`, because an + # API-supplied creator containing a newline would read as several patterns. + if [ "$entry" = "$login" ]; then + return 0 + fi + done + return 1 +} + +# --- Reached-the-end marker. --------------------------------------------------------------------- +# A top-level `exit` in a SOURCED file terminates the sourcing script where it stands, so no check +# placed after the `source` can ever run. The consumer therefore sources this file in a SUBSHELL +# first and requires the marker below on stdout; a file that exits early never prints it. Defining a +# function is not enough (a truncated file can define every function and still stop short), so this +# is the LAST line and it must stay last. +etv_h10_reviewers_loaded() { printf 'etv-h10-reviewers-loaded\n'; } diff --git a/scripts/post-review-verdict.sh b/scripts/post-review-verdict.sh index 2a7070ad3..79755d72c 100755 --- a/scripts/post-review-verdict.sh +++ b/scripts/post-review-verdict.sh @@ -106,6 +106,32 @@ case "$verdict_class" in *) die "the shared vocabulary classified '$verdict' as '$verdict_class', which is neither positive nor negative — refusing to guess a commit-status state" ;; esac +# --- WHOSE verdict the gate will inherit (ersatztv#845). ---------------------------------------- +# Loaded HERE: after the arguments validate, so a bare `post-review-verdict.sh` still prints its +# usage, and before the first network call, so a checkout that cannot answer the question refuses +# without having touched the server. +# +# The list is NOT declared here. `.gitea/workflows/review-verdict.yml` owns it and this derives from +# that file; see `scripts/lib/h10-reviewers.sh` for why the derivation is a parse rather than a +# declaration both sides source. Fails CLOSED on every branch, exactly like the vocabulary above: a +# writer that cannot find out whether its own verdicts are inheritable must not post one and report +# success, because that combination is the ersatztv#845 stall itself. +H10_REVIEWERS_LIB="$_here/lib/h10-reviewers.sh" +[ -r "$H10_REVIEWERS_LIB" ] \ + || die "the reviewer allow-list derivation is missing or unreadable at $H10_REVIEWERS_LIB — no status was written" +# Probe-source in a subshell and require the end-of-file marker before trusting the file, for the +# same reason the vocabulary does: a top-level `exit` in a sourced library terminates THIS script at +# the `source` line, having posted neither a status nor a comment, with exit 0. +# shellcheck source=lib/h10-reviewers.sh +h10_probe=$( . "$H10_REVIEWERS_LIB" >/dev/null 2>&1 && etv_h10_reviewers_loaded 2>/dev/null ) || h10_probe='' +[ "$h10_probe" = 'etv-h10-reviewers-loaded' ] \ + || die "the reviewer allow-list derivation at $H10_REVIEWERS_LIB did not load to completion (syntax error, truncated, or it exits at top level) — no status was written" +# shellcheck source=lib/h10-reviewers.sh +. "$H10_REVIEWERS_LIB" \ + || die "the reviewer allow-list derivation at $H10_REVIEWERS_LIB could not be sourced — no status was written" +etv_h10_reviewers_load \ + || die "could not derive the gate's H10_REVIEWERS allow-list (see above) — no status was written. Until it can be read, this tool cannot tell whether the verdict it posts would be honoured or silently re-derived." + base_url="${ETV_GITEA_URL:-http://192.168.1.95:3000}/api/v1" repo_slug="${ETV_GITEA_REPO:-timothy/ersatztv}" owner="${repo_slug%%/*}" @@ -211,14 +237,80 @@ fi # `scripts/check-review-verdict.sh`, whose grammar had three false-opens in its history; nothing # parses the description today, so this adds a field without reopening that surface. The hook reads # it back and compares (ersatztv#632). +# Held in a variable rather than inlined, because the read-back below identifies OUR write by it. +status_desc="Review-verdict: $verdict @ $short (base: $base_ref)" status_payload=$(jq -n \ --arg s "$state" --arg c "$STATUS_CONTEXT" --arg u "$pr_url" \ - --arg d "Review-verdict: $verdict @ $short (base: $base_ref)" \ + --arg d "$status_desc" \ '{state:$s, context:$c, description:$d, target_url:$u}') api_post "repos/$owner/$repo/statuses/$sha" "$status_payload" >/dev/null \ || die "failed to post the '$STATUS_CONTEXT' commit status on $short" printf 'posted status: %s = %s on %s\n' "$STATUS_CONTEXT" "$state" "$short" +# --- Is the verdict we just wrote one the GATE would honour? (ersatztv#845) --------------------- +# The gate inherits an existing `review-verdict/h10=success` only from a status whose +# `.creator.login` is on its `H10_REVIEWERS` allow-list (ersatztv#742). This script posts with +# whatever account owns the credential in the environment and used to never ask whose it was, so the +# two coupled values could drift apart with no diagnostic anywhere: the status really is written, +# this tool really did report success, and then the next `pull_request_target` event re-derives it +# and posts `pending` over it. Again on the next event. The PR deadlocks and the only trace is a +# `::warning::` inside a workflow run nobody is reading. +# +# MEASURED AFTER THE WRITE, NOT BEFORE IT. A pre-flight `GET /user` would test what the credential +# CLAIMS to be; this tests what Gitea actually recorded as the author of this status, which is the +# value the gate reads. It also needs no scope beyond the repo access the POST already required — +# a `/user` probe would add a read:user dependency that a narrowly-scoped but perfectly valid +# reviewer token might not carry, turning a hardening step into a new way to block every verdict. +# +# THE RESIDUAL, stated: on refusal a non-inheritable status is left standing on the head, because +# the check runs after the POST. That is the half-state `release.verdict-writes-status-before-comment` +# already designates as the safe one — a status with no comment leaves the merge hook at condition +# (c) with nothing to classify, which is an `ask`, not a grant — and the gate re-derives the status +# itself on the next PR event. It is not repaired here on purpose: a second corrective write is the +# sticky-sentinel mechanism ersatztv#849 is separately designing, and inventing a parallel one on +# this path would be two mechanisms for one invariant. +status_readback=$(api_get "repos/$owner/$repo/commits/$sha/status") \ + || die "the '$STATUS_CONTEXT' status was posted on $short, but it could not be read back to confirm the gate will honour it — no comment was written. Re-run once Gitea is reachable." +# `.statuses` serialises as `null` rather than `[]` on a head with no statuses (ersatztv#751), so +# the array TYPE is tested rather than assumed; a body that merely lost its array yields no entry +# and is refused below, exactly like one that carries no verdict. +readback_entry=$(printf '%s' "$status_readback" | jq -c --arg c "$STATUS_CONTEXT" \ + 'if (.statuses | type) == "array" then ((.statuses | map(select(.context == $c)))[0] // null) else null end') \ + || die "the '$STATUS_CONTEXT' status was posted on $short, but the read-back body could not be parsed — no comment was written." +if [ -z "$readback_entry" ] || [ "$readback_entry" = "null" ]; then + die "the '$STATUS_CONTEXT' status was posted on $short but is not present when read back, so it is UNPROVEN that the verdict landed — no comment was written. Re-run and check the PR's checks." +fi +readback_state=$(printf '%s' "$readback_entry" | jq -r '.state // ""') +readback_desc=$(printf '%s' "$readback_entry" | jq -r '.description // ""') +readback_creator=$(printf '%s' "$readback_entry" | jq -r '.creator.login // ""') +# Identify OUR write before judging its author. `/commits/{sha}/status` returns the LATEST status per +# context, so a run of the gate that overwrote ours between the POST and this read would otherwise +# have its own author judged here — an Actions-token write carries `creator: null` and would be +# reported as a wrong credential, which is a false and very confusing accusation. +if [ "$readback_state" != "$state" ] || [ "$readback_desc" != "$status_desc" ]; then + die "the '$STATUS_CONTEXT' status standing on $short is not the one just written (state '$readback_state', description '$readback_desc') — something overwrote it, so this verdict is not in force. No comment was written. Re-review the current head and run this again." +fi +if [ -z "$readback_creator" ]; then + die "the '$STATUS_CONTEXT' status on $short reads back with no creator, which is how a status posted by an ACTIONS token appears. The gate never inherits one of those as a reviewer verdict (ersatztv#742), so this verdict would be silently re-derived. No comment was written. Post it with a reviewer's own credential." +fi +# Explicit capture rather than `if ! etv_h10_reviewers_contains ...`, so the THIRD outcome cannot be +# folded into the second. The function answers 0 member / 1 not-a-member / 2 cannot-tell, and an +# abort inside it lands here as a non-zero code rather than skipping both arms of an `if !`. +set +e +etv_h10_reviewers_contains "$readback_creator" +h10_membership=$? +set -e +case "$h10_membership" in + 0) ;; + 1) + die "the '$STATUS_CONTEXT' status on $short was posted by '$readback_creator', which is NOT on the gate's H10_REVIEWERS allow-list ('$ETV_H10_REVIEWERS'). The status is written but the gate will not inherit it: the next PR event re-derives it and posts over it, and the PR deadlocks with no visible cause. No comment was written. Either post with an allow-listed reviewer's credential, or add '$readback_creator' to H10_REVIEWERS in .gitea/workflows/review-verdict.yml." + ;; + *) + die "could not determine whether '$readback_creator' is on the gate's H10_REVIEWERS allow-list (membership check returned $h10_membership). Refusing to report a verdict as posted when it is unknown whether the gate will honour it. No comment was written." + ;; +esac +printf 'verdict author: %s (on the gate allow-list: %s)\n' "$readback_creator" "$ETV_H10_REVIEWERS" + # --- The comment (human-readable artifact + the hook's condition-(c) input). -------------------- # Written LAST, after the gating status exists (ersatztv#792). The verdict line MUST start the line: # the hook anchors its parser to line-start precisely so a comment that merely QUOTES the template diff --git a/scripts/tests/mutation_manifest.py b/scripts/tests/mutation_manifest.py index 3e6796d07..d09fde233 100644 --- a/scripts/tests/mutation_manifest.py +++ b/scripts/tests/mutation_manifest.py @@ -387,6 +387,22 @@ MUTATIONS: tuple[Mutation, ...] = ( "#807's silent weight reset live again. The row is named in full rather than by the bare " "disposition line, which occurs three times and would identify none of them.", ), + Mutation( + guard="scripts/post-review-verdict.sh", + target=".gitea/workflows/review-verdict.yml", + clause='H10_REVIEWERS="timothy"', + replacement='H10_REVIEWERS="somebody-who-is-not-a-reviewer"', + proof="test_post_review_verdict.py::test_a_verdict_posted_by_an_ALLOWLISTED_account_is_accepted", + granularity=CLAUSE, + expect="the verdict writer REFUSED an allow-listed account", + why="THE COUPLING, NOT THE COMPARISON. The guard is the writer; the clause lives in the GATE, " + "because what ersatztv#845 is about is the two drifting apart. Mutating the gate's own " + "allow-list while the posting account stays fixed reddens the accept path only if BOTH hold: " + "the writer reads the list LIVE from the workflow (a hand-copied list would not move), and " + "the membership comparison actually gates the outcome (a no-op comparison would not care " + "that it moved). Disarming the comparison inside the script instead would prove the second " + "and say nothing about the first, which is the half that was missing.", + ), ) @@ -477,9 +493,6 @@ UNDECLARED: dict[str, str] = { "harness's.", "scripts/jq-preflight.sh": "BEHAVIOUR-ONLY. Its named test drives the real script below the " "version floor; no clause has been disarmed to show the floor comparison is what refuses.", - "scripts/post-review-verdict.sh": "BEHAVIOUR-ONLY, and the most valuable upgrade on this list: " - "it writes the required `review-verdict/h10` status. Its re-read-and-compare has several arms " - "and naming one as THE clause needs the judgement #790 declines to make blind.", "scripts/pr-changed-files.sh": "BEHAVIOUR-ONLY. Its named test feeds a short page to the real " "enumeration; the pagination clause has not been disarmed.", "scripts/tests/test_ci_release_path_scan_job.py": "A GUARD that is a test, so the mutation would " diff --git a/scripts/tests/test_post_review_verdict.py b/scripts/tests/test_post_review_verdict.py index c90ee94a9..14b90d2f6 100644 --- a/scripts/tests/test_post_review_verdict.py +++ b/scripts/tests/test_post_review_verdict.py @@ -24,6 +24,8 @@ from __future__ import annotations import json import os +import re +import shutil import subprocess from pathlib import Path @@ -87,6 +89,36 @@ if "/pulls/" in url and not url.endswith("/files"): print(json.dumps(body)) sys.exit(0) +# GET /repos///commits//status -> the COMBINED status (latest per context). +# It REPLAYS the status that was actually POSTed, so the script's identify-our-own-write comparison +# is satisfied by construction and tests only have to vary the one field under test: the CREATOR +# Gitea recorded (ersatztv#845). `status_body` overrides the whole response for the shapes a replay +# cannot express — an overwrite, a `statuses: null` body, a malformed one. +if "/commits/" in url and url.split("?")[0].endswith("/status"): + if (state / "status_fail").exists(): + sys.exit(22) + raw = state / "status_body" + if raw.exists(): + print(raw.read_text()) + sys.exit(0) + entry = None + log = state / "posts.jsonl" + if log.exists(): + for line in log.read_text().splitlines(): + if not line.strip(): + continue + post = json.loads(line) + if "/statuses/" in post["url"]: + entry = dict(post["payload"]) # last write wins, as the combined endpoint does + if entry is None: + print(json.dumps({"total_count": 0, "statuses": None})) + sys.exit(0) + who = (state / "status_creator").read_text().strip() if (state / "status_creator").exists() else "timothy" + # 'NULL' is how a status POSTed by an ACTIONS token reads back — the case the gate re-derives. + entry["creator"] = None if who == "NULL" else {"login": who} + print(json.dumps({"total_count": 1, "statuses": [entry]})) + sys.exit(0) + print("{}") ''' @@ -133,6 +165,19 @@ def gitea(tmp_path): """Base branch per PR GET. 'MISSING' omits `.base` from the response entirely.""" (state / "pr_bases").write_text(" ".join(refs)) + def set_status_creator(self, login): + """Who Gitea records as the author of the read-back status. 'NULL' models an Actions + token, whose statuses carry `creator: null` (ersatztv#742/#845).""" + (state / "status_creator").write_text(login) + + def fail_status_readback(self): + """Make the combined-status GET fail, as curl -f does on a 4xx/5xx.""" + (state / "status_fail").write_text("1") + + def set_status_body(self, body): + """Replace the whole combined-status response with this literal JSON text.""" + (state / "status_body").write_text(body) + def run(self, *args): return subprocess.run( ["bash", str(SCRIPT), *args], @@ -530,3 +575,205 @@ def test_a_failed_COMMENT_after_a_written_status_is_still_an_error(gitea): assert gitea.comments() == [] assert "COMMENT could not be posted" in result.stderr assert "ask" in result.stderr.lower(), "it must say what the gate will do, not just that a call failed" + + +# ================================================================================================== +# Is the verdict this tool writes one the GATE will actually inherit? (ersatztv#845) +# ================================================================================================== +# +# `.gitea/workflows/review-verdict.yml` inherits an existing `review-verdict/h10=success` only from a +# status whose `.creator.login` is on its `H10_REVIEWERS` allow-list (ersatztv#742). This script +# posts with whatever account owns the credential in the environment. Those two values were coupled +# with nothing asserting the coupling, and the failure was silent in the worst way: the status is +# written, THIS TOOL REPORTS SUCCESS, and the next PR event re-derives it and posts over it. Forever. +# +# The account below is written as the literal `timothy` on purpose, and it is the same deliberate +# hardcode `test_pr_changed_files.py::test_the_allowlisted_reviewer_in_the_TESTS_is_the_one_the_ +# WORKFLOW_ships` exists to pin. Deriving it here would make these tests vacuous: the mutation proof +# works precisely BECAUSE changing the workflow literal moves the allow-list out from under a fixed +# creator. Derive both and they would move together and nothing would ever redden. +ALLOWLISTED = "timothy" +OFF_LIST = "renovate" + + +def test_a_verdict_posted_by_an_ALLOWLISTED_account_is_accepted(gitea): + """The accept path — and the mutation proof for the whole derivation. + + This is the test `mutation_manifest.py` reddens by rewriting `H10_REVIEWERS` in the SHIPPED + workflow. That single mutation proves two things at once, which is why it is the declared one: + the script must be reading the allow-list LIVE from the gate (a hand-copied list would not + move), and the membership comparison must actually gate the outcome (a no-op comparison would + not care that the list moved). + """ + gitea.set_status_creator(ALLOWLISTED) + result = gitea.run("42", "MERGEABLE") + + assert result.returncode == 0, f"the verdict writer REFUSED an allow-listed account: {result.stderr}" + assert len(gitea.statuses()) == 1 + assert len(gitea.comments()) == 1, "an accepted verdict must still post its comment" + + +def test_a_verdict_posted_by_an_account_OFF_the_allowlist_is_refused_before_the_comment(gitea): + """The whole point of ersatztv#845: this used to report success and deadlock the PR later.""" + gitea.set_status_creator(OFF_LIST) + result = gitea.run("42", "MERGEABLE") + + assert result.returncode != 0, "a verdict the gate will not inherit must not report success" + assert "H10_REVIEWERS" in result.stderr, ( + "the diagnostic must name the allow-list, because the repair is to edit it or to re-post " + "with another credential — an operator cannot act on 'refused'" + ) + assert OFF_LIST in result.stderr, "the diagnostic must name the account that actually posted" + assert gitea.comments() == [], ( + "the refusal must land BEFORE the comment: a verdict comment with no honoured status is the " + "half-state ersatztv#792 removed, and it reads to a human as consent that was never granted" + ) + # Stated rather than fixed. The status IS written by the time the author can be measured, and it + # is left standing deliberately — see the residual note in the script. + assert len(gitea.statuses()) == 1 + + +def test_a_status_that_reads_back_with_NO_creator_is_refused(gitea): + """`creator: null` is how a status POSTed by an ACTIONS token appears, and the gate never + inherits one of those as a reviewer verdict. Distinct from the off-list case: there is no + account to name, so 'add them to the allow-list' would be the wrong advice.""" + gitea.set_status_creator("NULL") + result = gitea.run("42", "MERGEABLE") + + assert result.returncode != 0 + assert "ACTIONS token" in result.stderr + assert gitea.comments() == [] + + +def test_a_status_OVERWRITTEN_between_the_write_and_the_read_is_not_blamed_on_its_author(gitea): + """`/commits/{sha}/status` returns the LATEST status per context. If the gate overwrote ours + between the POST and the read-back, judging THAT status's author would accuse the wrong party — + and an Actions write carries no creator, so it would surface as a credential problem that does + not exist. Identify our own write first, then judge it.""" + gitea.set_status_body( + json.dumps( + { + "total_count": 1, + "statuses": [ + { + "context": "review-verdict/h10", + "state": "pending", + "description": "Awaiting review verdict", + "creator": None, + } + ], + } + ) + ) + result = gitea.run("42", "MERGEABLE") + + assert result.returncode != 0 + assert "overwrote it" in result.stderr + assert "ACTIONS token" not in result.stderr, ( + "an overwritten status must not be reported as a wrong-credential problem" + ) + assert gitea.comments() == [] + + +def test_an_unreadable_readback_refuses_rather_than_reporting_the_verdict_posted(gitea): + """UNKNOWN must fail. A read that cannot be performed leaves it unproven that the verdict is in + force, and reporting success on unproven is exactly the ersatztv#845 shape.""" + gitea.fail_status_readback() + result = gitea.run("42", "MERGEABLE") + + assert result.returncode != 0 + assert gitea.comments() == [] + + +def test_a_readback_whose_statuses_array_is_NULL_is_refused(gitea): + """Gitea serialises a nil slice as `null`, not `[]` (ersatztv#751). The script tests the array + TYPE rather than assuming one; a body that merely lost its array must refuse, not be read as + 'no verdict, carry on'.""" + gitea.set_status_body(json.dumps({"total_count": 0, "statuses": None})) + result = gitea.run("42", "MERGEABLE") + + assert result.returncode != 0 + assert gitea.comments() == [] + + +# --- The allow-list is DERIVED from the gate, not restated beside it. ---------------------------- + + +def _sandbox(tmp_path, reviewers): + """A throwaway tree carrying the real `scripts/` and the real gate workflow, with the workflow's + `H10_REVIEWERS` literal rewritten. Returns a runner over the SANDBOX copy of the script. + + The whole `scripts/` directory is copied rather than the three files in play, because the script + resolves both of its libraries relative to `${BASH_SOURCE[0]}` — copying selectively would leave + it sourcing the real repo's copies and the rewrite would prove nothing. + """ + root = tmp_path / "sandbox" + shutil.copytree(REPO_ROOT / "scripts", root / "scripts") + workflow = root / ".gitea" / "workflows" / "review-verdict.yml" + workflow.parent.mkdir(parents=True) + source = (REPO_ROOT / ".gitea" / "workflows" / "review-verdict.yml").read_text() + rewritten, n = re.subn( + r'^(\s*)H10_REVIEWERS="[^"]*"$', + lambda m: f'{m.group(1)}H10_REVIEWERS="{reviewers}"', + source, + flags=re.MULTILINE, + ) + assert n == 1, f"expected exactly one H10_REVIEWERS assignment to rewrite, substituted {n}" + workflow.write_text(rewritten) + return root / "scripts" / "post-review-verdict.sh" + + +def test_the_allowlist_MOVES_when_the_workflow_moves(gitea, tmp_path): + """The single-declaration property, measured end to end rather than argued. + + Rewrite the gate's own literal to an account this repo does not have, drive the REAL script, and + the accounts swap roles: the one the shipped workflow accepts is refused, and the invented one is + accepted. A copy of the list living beside the script could not produce that. + """ + invented = "not-a-real-account" + script = _sandbox(tmp_path, invented) + + def run_with(creator): + gitea.set_status_creator(creator) + (gitea.state / "posts.jsonl").unlink(missing_ok=True) + (gitea.state / "pr_get_count").unlink(missing_ok=True) + return subprocess.run( + ["bash", str(script), "42", "MERGEABLE"], + env=gitea.env, + capture_output=True, + text=True, + ) + + accepted = run_with(invented) + assert accepted.returncode == 0, f"the rewritten allow-list was not the one used: {accepted.stderr}" + + refused = run_with(ALLOWLISTED) + assert refused.returncode != 0, ( + f"{ALLOWLISTED} was accepted against a workflow that no longer lists them, so the script is " + "not deriving the allow-list from the gate" + ) + assert invented in refused.stderr + + +def test_a_workflow_whose_allowlist_cannot_be_DERIVED_refuses_before_any_write(gitea, tmp_path): + """Fail-closed, and early. Two assignments means the shell would run the last one executed, so + which value the gate uses is unknowable from here — and a writer that cannot tell whether its + verdict is inheritable must not post one. Nothing is written at all, so there is no half-state + to clean up. + """ + script = _sandbox(tmp_path, ALLOWLISTED) + text = script.parent.parent.joinpath(".gitea/workflows/review-verdict.yml") + body = text.read_text() + marker = f'H10_REVIEWERS="{ALLOWLISTED}"' + assert body.count(marker) == 1 + text.write_text(body.replace(marker, f'{marker}\n H10_REVIEWERS="someone-else"')) + + result = subprocess.run( + ["bash", str(script), "42", "MERGEABLE"], + env=gitea.env, + capture_output=True, + text=True, + ) + assert result.returncode != 0 + assert gitea.statuses() == [], "a derivation it cannot trust must refuse before writing anything" + assert gitea.comments() == [] diff --git a/scripts/tests/test_review_verdict_vocabulary.py b/scripts/tests/test_review_verdict_vocabulary.py index 8c05b562e..731cfe598 100644 --- a/scripts/tests/test_review_verdict_vocabulary.py +++ b/scripts/tests/test_review_verdict_vocabulary.py @@ -52,6 +52,14 @@ class Sandbox: def __init__(self, root: Path): self.scripts = root / "scripts" shutil.copytree(REPO_ROOT / "scripts", self.scripts) + # The gate workflow comes too. `post-review-verdict.sh` derives the H10 reviewer allow-list + # from it (ersatztv#845), resolving it relative to its own location — so a sandbox holding + # only `scripts/` would leave the writer unable to answer whether its verdict is inheritable, + # and every write-side assertion below would fail for a reason that has nothing to do with + # the vocabulary under test. + workflow = root / ".gitea" / "workflows" / "review-verdict.yml" + workflow.parent.mkdir(parents=True) + shutil.copy2(REPO_ROOT / ".gitea" / "workflows" / "review-verdict.yml", workflow) self.vocabulary = self.scripts / "lib" / "review-verdict-vocabulary.sh" self.reader = self.scripts / "check-review-verdict.sh" self.writer = self.scripts / "post-review-verdict.sh"