Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions .claude/build-process.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -153,6 +155,20 @@ backported fix's entry goes while a patch is pending is in *Branches & releases*
3. the top `## v<version>` 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 <branch or tag>`. 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`
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions .github/workflows/build-electron.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down Expand Up @@ -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' }}
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
110 changes: 110 additions & 0 deletions scripts/ci/require-green-tests.mjs
Original file line number Diff line number Diff line change
@@ -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)
}
}
37 changes: 37 additions & 0 deletions test/invariants/release-workflow-hardening.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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))
Expand Down
Loading
Loading