diff --git a/.claude/build-process.md b/.claude/build-process.md index 03e798b7..7c23f187 100644 --- a/.claude/build-process.md +++ b/.claude/build-process.md @@ -59,7 +59,9 @@ the backport, so it reaches `main` with the release-prep forward-port. **Patch release** (e.g. `v1.11.2`): once its fixes are backported, a `release-prep/1.11.2` PR to `release/1.11` bumps `package.json#version`, dates the `## v1.11.2` heading in `CHANGELOG.md` and settles that section's wording. -When it has merged and the Test run on the release-branch push is green, tag the branch: +When it has merged and the Test run on the release-branch push is green, tag the branch. The build +refuses a tag whose commit has no green Test run (*Pre-flight gates* below), so a tag pushed early +fails in `resolve`; once Test has passed, re-run that job. ``` git fetch origin && git tag v1.11.2 origin/release/1.11 && git push origin v1.11.2 @@ -153,6 +155,20 @@ backported fix's entry goes while a patch is pending is in *Branches & releases* 3. the top `## v` heading in `CHANGELOG.md` matches the tag (forces a release note into the same commit). +**Green tests** (tag pushes and `staging` dispatches; `dev` builds are exempt). A tag push and a +dispatch run no tests: `test.yml` runs on pull requests and on pushes to `main` and `release/**`. So +the `resolve` job looks the result up before the build job, and its environment approval, can start: +`scripts/ci/require-green-tests.mjs` reads the `test.yml` runs for the commit being built and +passes only when the latest `push` or `workflow_dispatch` run completed with success. A +`pull_request` run does not count, since it tests the merge into the base and not the commit. No +run, a run still going, and a failed or cancelled run each stop the build with their own message. +A re-run counts through its current result, so a flaked run is recovered with *Re-run failed jobs* +on the Test run and then on `resolve`; a commit with no run gets one with +`gh workflow run test.yml --ref `. There is no input that skips the gate. +`test/unit/require-green-tests.test.js` pins the decision and +`test/invariants/release-workflow-hardening.test.js` the wiring. Like every check in the workflow +file it guards against a mistake, not against whoever can push the ref (*Release integrity*). + **Release integrity.** The workflow file runs from the ref being built, so whoever can push a ref can edit any check written in it; the boundary sits outside the repo files: - **Environments.** The build job runs in `release` (prod; deployable only from `v*` tags) or `beta` @@ -166,8 +182,9 @@ can edit any check written in it; the boundary sits outside the repo files: before its upload is recovered with *Re-run failed jobs* (never *Re-run all jobs*); anything else ships as the next version. The signed MSIX is a new key under `win32-x64/signed/`, so the lock allows it — once. -- **Least privilege.** The workflow token is `contents: read`, checkouts do not persist it, and - expression values reach shell scripts only through `env:`. +- **Least privilege.** The workflow token is `contents: read`; the `resolve` job adds + `actions: read` for the test-result lookup and the build job does not. Checkouts do not persist + the token, and expression values reach shell scripts only through `env:`. - **Pinned inputs.** Every action is pinned to a commit SHA with its version in a trailing comment; Renovate's `helpers:pinGitHubActionDigestsToSemver` keeps both current. Build inputs fetched over the network go through `scripts/build/lib/fetch-verified.sh`, which refuses a file whose SHA-256 diff --git a/.github/workflows/build-electron.yml b/.github/workflows/build-electron.yml index 9f008cab..2c9dd951 100644 --- a/.github/workflows/build-electron.yml +++ b/.github/workflows/build-electron.yml @@ -40,6 +40,11 @@ permissions: jobs: resolve: runs-on: ubuntu-latest + # Job permissions replace the workflow's: this job alone may also read workflow runs, + # for the test-result lookup below. + permissions: + contents: read + actions: read outputs: channel: ${{ steps.ch.outputs.channel }} version: ${{ steps.ver.outputs.version }} @@ -145,6 +150,13 @@ jobs: exit 1 fi echo "CHANGELOG.md top entry agrees with tag: v$TAG_V" + - name: Require a green Test run for this commit + # A tag push and a dispatch run no tests, so the result is looked up for the commit being + # built. Every channel but dev is held to it, and there is no input that skips it. + if: steps.ch.outputs.channel != 'dev' + env: + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/ci/require-green-tests.mjs - id: matrix env: FILTER: ${{ inputs.platform || 'all' }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 26ecaf29..2e2fe4c9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -4,6 +4,8 @@ on: pull_request: push: branches: [main, 'release/**'] + # A release build needs a passing run on its commit; a commit that has none gets one here. + workflow_dispatch: jobs: # Tier 1 pure units + raw holepunch mechanics. Fast; has never flaked. diff --git a/scripts/ci/require-green-tests.mjs b/scripts/ci/require-green-tests.mjs new file mode 100644 index 00000000..d3508f68 --- /dev/null +++ b/scripts/ci/require-green-tests.mjs @@ -0,0 +1,110 @@ +// A release build refuses a commit whose tests did not pass. A tag push and a build dispatch start +// no test run of their own, so the build looks the result up: for every required workflow, the +// latest run on the commit being built must have completed with success. +// +// The decision is pure (GitHub API JSON in, verdict out); the CLI at the bottom does the fetching. + +// Workflow files whose result a release needs, as named under .github/workflows/. +export const REQUIRED_WORKFLOWS = Object.freeze(['test.yml']) + +// Only these runs test the commit itself. A pull_request run carries the PR head's SHA but tests +// its merge into the base, which is a different tree. +const COUNTED_EVENTS = Object.freeze(['push', 'workflow_dispatch']) + +export const TEST_STATE = Object.freeze({ + GREEN: 'green', + MISSING: 'missing', + RUNNING: 'running', + FAILED: 'failed', +}) + +// The run that decides is the one created last. A re-run keeps its run's id and creation time and +// replaces its status and conclusion, so it decides through its current attempt. `head_sha` is +// compared here as well as in the query: a response that ignored the filter must not pass a commit. +export function decidingRun(sha, runs) { + const counted = runs.filter((run) => run.head_sha === sha && COUNTED_EVENTS.includes(run.event)) + counted.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at) || b.id - a.id) + return counted[0] ?? null +} + +function workflowResult(sha, workflow, runs) { + const run = decidingRun(sha, runs) + if (!run) return { workflow, state: TEST_STATE.MISSING, run: null } + if (run.status !== 'completed') return { workflow, state: TEST_STATE.RUNNING, run } + return { workflow, state: run.conclusion === 'success' ? TEST_STATE.GREEN : TEST_STATE.FAILED, run } +} + +// `runsByWorkflow` maps a workflow file to the `workflow_runs` array of its runs for `sha`. A +// required workflow absent from the map has no run. +export function releaseTestVerdict(sha, runsByWorkflow, required = REQUIRED_WORKFLOWS) { + const results = required.map((workflow) => workflowResult(sha, workflow, runsByWorkflow[workflow] ?? [])) + return { ok: results.every((result) => result.state === TEST_STATE.GREEN), sha, results } +} + +// One line per required workflow. `ref` is the branch or tag being built, named so the hint for a +// missing run is a command that can be pasted. +export function describeResult(result, { sha, ref }) { + const { workflow, state, run } = result + const commit = sha.slice(0, 8) + switch (state) { + case TEST_STATE.GREEN: + return `${workflow} passed for commit ${commit}: ${run.html_url}` + case TEST_STATE.MISSING: + return `${workflow} has no run for commit ${commit}. Start one with ` + + `"gh workflow run ${workflow} --ref ${ref}", wait for it to pass, then re-run this job.` + case TEST_STATE.RUNNING: + return `${workflow} is still running for commit ${commit} (${run.status}): ${run.html_url} ` + + 'Wait for it to finish, then re-run this job.' + default: + return `${workflow} did not pass for commit ${commit} (${run.conclusion}): ${run.html_url} ` + + 'Re-run its failed jobs until it passes, then re-run this job.' + } +} + +async function fetchRuns({ apiUrl, repository, token, workflow, sha }) { + const url = `${apiUrl}/repos/${repository}/actions/workflows/${workflow}/runs?head_sha=${sha}&per_page=100` + const response = await fetch(url, { + headers: { + Accept: 'application/vnd.github+json', + Authorization: `Bearer ${token}`, + 'X-GitHub-Api-Version': '2022-11-28', + }, + }) + if (!response.ok) throw new Error(`${workflow}: the run lookup answered ${response.status} ${response.statusText}`) + const body = await response.json() + if (!Array.isArray(body.workflow_runs)) throw new Error(`${workflow}: the run lookup returned no workflow_runs`) + // A page that does not hold every run cannot name the latest one. + if (body.total_count > body.workflow_runs.length) { + throw new Error(`${workflow}: ${body.total_count} runs for one commit do not fit one page`) + } + return body.workflow_runs +} + +async function main() { + const { GITHUB_TOKEN: token, GITHUB_REPOSITORY: repository, GITHUB_SHA: sha, GITHUB_REF_NAME: ref } = process.env + const apiUrl = process.env.GITHUB_API_URL || 'https://api.github.com' + const missing = Object.entries({ GITHUB_TOKEN: token, GITHUB_REPOSITORY: repository, GITHUB_SHA: sha, GITHUB_REF_NAME: ref }) + .filter(([, value]) => !value).map(([name]) => name) + if (missing.length > 0) throw new Error(`missing from the environment: ${missing.join(', ')}`) + + const runsByWorkflow = {} + for (const workflow of REQUIRED_WORKFLOWS) { + runsByWorkflow[workflow] = await fetchRuns({ apiUrl, repository, token, workflow, sha }) + } + const verdict = releaseTestVerdict(sha, runsByWorkflow) + for (const result of verdict.results) { + const line = describeResult(result, { sha, ref }) + console.log(result.state === TEST_STATE.GREEN ? line : `::error::${line}`) + } + if (!verdict.ok) process.exit(1) +} + +if (process.argv[1] && process.argv[1].endsWith('require-green-tests.mjs')) { + try { + await main() + } catch (err) { + // A lookup that could not be made is not a pass. + console.log(`::error::The test result for this commit could not be read: ${err.message}`) + process.exit(1) + } +} diff --git a/test/invariants/release-workflow-hardening.test.js b/test/invariants/release-workflow-hardening.test.js index 2ae86fe6..71dba04b 100644 --- a/test/invariants/release-workflow-hardening.test.js +++ b/test/invariants/release-workflow-hardening.test.js @@ -3,6 +3,7 @@ import { readFileSync, readdirSync, statSync } from 'fs' import path from 'path' import { fileURLToPath } from 'url' import { parse } from 'yaml' +import { REQUIRED_WORKFLOWS } from '../../scripts/ci/require-green-tests.mjs' const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..') const RELEASE_WORKFLOW = path.join(ROOT, '.github/workflows/build-electron.yml') @@ -52,6 +53,42 @@ test('a tag build checks the tag format and that the tag sits on its release bra t.ok(order.indexOf('Verify tag format and release branch') < order.indexOf('ver'), 'the gate runs before the tag is read as a version') }) +test('a prod or staging build is refused before the build job unless the commit has a green test run', (t) => { + const gate = stepNamed('Require a green Test run for this commit') + t.ok(gate, 'the gate exists') + t.is(gate?.job, 'resolve') + t.is(gate?.if, "steps.ch.outputs.channel != 'dev'", 'only a dev build is exempt, and no input skips it') + t.is(gate?.run, 'node scripts/ci/require-green-tests.mjs') + t.alike(gate?.env, { GITHUB_TOKEN: '${{ github.token }}' }) + t.absent(gate?.['continue-on-error'], 'a refusal fails the job') + + const order = stepOrder('resolve') + const checkout = workflow.jobs.resolve.steps.findIndex((step) => step.uses?.startsWith('actions/checkout@')) + t.ok(checkout >= 0 && checkout < order.indexOf('Require a green Test run for this commit'), 'the script is checked out first') + t.ok(order.indexOf('ch') < order.indexOf('Require a green Test run for this commit'), 'the channel is known first') + + const needs = [workflow.jobs.build.needs].flat() + t.ok(needs.includes('resolve'), 'the build job, and its environment approval, wait for resolve') + t.alike(Object.keys(workflow.on.workflow_dispatch.inputs).sort(), ['channel', 'platform'], 'no override input') + + t.alike(workflow.jobs.resolve.permissions, { contents: 'read', actions: 'read' }, 'resolve may read workflow runs') + const others = Object.entries(workflow.jobs).filter(([name, job]) => name !== 'resolve' && job.permissions) + t.alike(others.map(([name]) => name), [], 'no other job changes the token') +}) + +// A commit can only pass the gate if each required workflow runs where release commits land, and a +// commit left without a run can be given one. +test('every workflow a release requires runs on trunk and release pushes and can be dispatched', (t) => { + t.ok(REQUIRED_WORKFLOWS.length > 0) + for (const file of REQUIRED_WORKFLOWS) { + const required = parse(readFileSync(path.join(ROOT, '.github/workflows', file), 'utf8')) + t.alike(required.on.push?.branches, ['main', 'release/**'], `${file} runs on pushes to main and release branches`) + t.absent(required.on.push?.paths || required.on.push?.['paths-ignore'], `${file} skips no push by path`) + t.ok('workflow_dispatch' in required.on, `${file} can be dispatched`) + t.absent(required.concurrency, `${file} never cancels a run for a newer one`) + } +}) + test('REGRESSION (MIR-56: no expression is pasted into a release shell script)', (t) => { const pasted = steps .filter((step) => step.run && /\$\{\{/.test(step.run)) diff --git a/test/unit/require-green-tests.test.js b/test/unit/require-green-tests.test.js new file mode 100644 index 00000000..79548b69 --- /dev/null +++ b/test/unit/require-green-tests.test.js @@ -0,0 +1,144 @@ +import test from 'brittle' +import { + REQUIRED_WORKFLOWS, TEST_STATE, decidingRun, releaseTestVerdict, describeResult, +} from '../../scripts/ci/require-green-tests.mjs' + +const SHA = '6be9f3e8000e11e6332d7938e2fab750573de47b' +const OTHER_SHA = '114c2103aa0e11e6332d7938e2fab750573de47b' + +// The fields of a `workflow_runs` entry the decision reads, as +// GET /repos/{owner}/{repo}/actions/workflows/test.yml/runs?head_sha= returns them. +const RECORDED_RUN = Object.freeze({ + id: 45474097313, + name: 'Test', + path: '.github/workflows/test.yml', + head_branch: 'release/1.14', + head_sha: SHA, + event: 'push', + status: 'completed', + conclusion: 'success', + run_attempt: 1, + created_at: '2026-11-24T19:48:26Z', + run_started_at: '2026-11-24T19:48:26Z', + html_url: 'https://github.com/example/app/actions/runs/45474097313', +}) + +const run = (overrides = {}) => ({ ...RECORDED_RUN, ...overrides }) +const earlier = (overrides = {}) => run({ + id: 45472178138, + head_branch: 'main', + created_at: '2026-11-24T19:37:29Z', + run_started_at: '2026-11-24T19:37:29Z', + html_url: 'https://github.com/example/app/actions/runs/45472178138', + ...overrides, +}) + +const stateOf = (runs) => releaseTestVerdict(SHA, { 'test.yml': runs }).results[0].state +const passes = (runs) => releaseTestVerdict(SHA, { 'test.yml': runs }).ok +const messageFor = (runs) => + describeResult(releaseTestVerdict(SHA, { 'test.yml': runs }).results[0], { sha: SHA, ref: 'v1.14.0' }) + +test('the release needs exactly the Test workflow', (t) => { + t.alike([...REQUIRED_WORKFLOWS], ['test.yml']) +}) + +test('a commit whose latest test run succeeded may be released', (t) => { + const verdict = releaseTestVerdict(SHA, { 'test.yml': [run()] }) + t.ok(verdict.ok) + t.is(verdict.results[0].state, TEST_STATE.GREEN) + t.is(verdict.results[0].run.id, RECORDED_RUN.id, 'the verdict names the run that decided') + t.ok(passes([run({ event: 'workflow_dispatch' })]), 'a dispatched run counts like a push run') +}) + +test('a commit whose test run did not succeed is refused', (t) => { + for (const conclusion of ['failure', 'cancelled', 'timed_out', 'skipped', 'startup_failure', 'neutral']) { + const runs = [run({ conclusion })] + t.absent(passes(runs), `${conclusion} does not pass`) + t.is(stateOf(runs), TEST_STATE.FAILED) + t.ok(messageFor(runs).includes(`(${conclusion})`), `the message names ${conclusion}`) + } +}) + +test('a commit whose test run has not finished is refused', (t) => { + for (const status of ['in_progress', 'queued', 'requested', 'waiting', 'pending']) { + const runs = [run({ status, conclusion: null })] + t.absent(passes(runs), `${status} does not pass`) + t.is(stateOf(runs), TEST_STATE.RUNNING) + } +}) + +test('a commit with no test run is refused', (t) => { + t.absent(passes([])) + t.is(stateOf([]), TEST_STATE.MISSING) + const unlisted = releaseTestVerdict(SHA, {}) + t.absent(unlisted.ok, 'a workflow the lookup never answered for has no run') + t.is(unlisted.results[0].state, TEST_STATE.MISSING) +}) + +test('with two runs on one commit the later one decides, whatever order they arrive in', (t) => { + const laterGreen = [run(), earlier({ conclusion: 'failure' })] + t.ok(passes(laterGreen), 'a later success outweighs an earlier failure') + t.ok(passes([...laterGreen].reverse()), 'in either order') + + const laterRed = [run({ conclusion: 'failure' }), earlier()] + t.absent(passes(laterRed), 'a later failure outweighs an earlier success') + t.absent(passes([...laterRed].reverse()), 'in either order') + + const laterRunning = [run({ status: 'in_progress', conclusion: null }), earlier()] + t.is(stateOf(laterRunning), TEST_STATE.RUNNING, 'a later run still going outweighs an earlier success') + t.is(stateOf([...laterRunning].reverse()), TEST_STATE.RUNNING, 'in either order') + + const sameSecond = [run({ id: 2, conclusion: 'failure' }), run({ id: 1 })] + t.absent(passes(sameSecond), 'runs created in the same second are ordered by id') + t.absent(passes([...sameSecond].reverse())) +}) + +test('a run from an event that does not test the commit itself is not counted', (t) => { + t.is(stateOf([run({ event: 'pull_request' })]), TEST_STATE.MISSING, 'a pull_request run alone is no run') + t.is(stateOf([run({ event: 'pull_request_target' })]), TEST_STATE.MISSING) + t.is(stateOf([run({ event: 'schedule' })]), TEST_STATE.MISSING) + t.absent(passes([run({ event: 'pull_request' }), earlier({ conclusion: 'failure' })]), + 'a later pull_request success does not outweigh a failed push run') + t.ok(passes([run({ event: 'pull_request', conclusion: 'failure' }), earlier()]), + 'a later pull_request failure does not outweigh a passed push run') +}) + +test('a run on another commit is not counted', (t) => { + t.is(stateOf([run({ head_sha: OTHER_SHA })]), TEST_STATE.MISSING) + t.is(decidingRun(SHA, [run({ head_sha: OTHER_SHA }), earlier({ conclusion: 'failure' })]).id, 45472178138) +}) + +test('a re-run decides through its current attempt', (t) => { + t.ok(passes([run({ run_attempt: 2, run_started_at: '2026-11-24T21:02:11Z' })]), + 'a failed run re-run to success passes') + t.is(stateOf([run({ run_attempt: 2, status: 'in_progress', conclusion: null })]), TEST_STATE.RUNNING, + 'a run being re-run is not finished, whatever its previous attempt concluded') + t.absent(passes([run({ run_attempt: 3, conclusion: 'failure' })]), 'a re-run that failed again does not pass') + + const rerunOfTheEarlier = earlier({ run_attempt: 2, run_started_at: '2026-11-24T22:15:00Z' }) + t.absent(passes([run({ conclusion: 'failure' }), rerunOfTheEarlier]), + 'a re-run keeps its creation time, so it does not overtake a run created after it') +}) + +test('every required workflow has to be green', (t) => { + const required = ['test.yml', 'other.yml'] + t.absent(releaseTestVerdict(SHA, { 'test.yml': [run()] }, required).ok) + t.absent(releaseTestVerdict(SHA, { 'test.yml': [run()], 'other.yml': [run({ conclusion: 'failure' })] }, required).ok) + t.ok(releaseTestVerdict(SHA, { 'test.yml': [run()], 'other.yml': [run()] }, required).ok) +}) + +test('each refusal reads differently and says what to do next', (t) => { + const missing = messageFor([]) + const running = messageFor([run({ status: 'in_progress', conclusion: null })]) + const failed = messageFor([run({ conclusion: 'failure' })]) + + t.is(missing, 'test.yml has no run for commit 6be9f3e8. Start one with ' + + '"gh workflow run test.yml --ref v1.14.0", wait for it to pass, then re-run this job.') + t.is(running, 'test.yml is still running for commit 6be9f3e8 (in_progress): ' + + 'https://github.com/example/app/actions/runs/45474097313 Wait for it to finish, then re-run this job.') + t.is(failed, 'test.yml did not pass for commit 6be9f3e8 (failure): ' + + 'https://github.com/example/app/actions/runs/45474097313 ' + + 'Re-run its failed jobs until it passes, then re-run this job.') + t.is(messageFor([run()]), + 'test.yml passed for commit 6be9f3e8: https://github.com/example/app/actions/runs/45474097313') +})