diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 9a5b5072cf..21a2425fe3 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -19,7 +19,7 @@ jobs: analyze: name: Analyze runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 10 + timeout-minutes: 15 strategy: fail-fast: false @@ -32,11 +32,11 @@ jobs: uses: actions/checkout@v6 - name: Initialize CodeQL - uses: github/codeql-action/init@v4.38.0 + uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0 with: languages: ${{ matrix.language }} - name: Perform CodeQL Analysis - uses: github/codeql-action/init@v4.38.0 + uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0 with: category: "/language:${{ matrix.language }}" diff --git a/scripts/__tests__/lib/workflows.mjs b/scripts/__tests__/lib/workflows.mjs index e8f933176a..9d9ec7975e 100644 --- a/scripts/__tests__/lib/workflows.mjs +++ b/scripts/__tests__/lib/workflows.mjs @@ -1,4 +1,4 @@ -import { readdirSync, readFileSync } from 'node:fs' +import { existsSync, readdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' import yaml from 'js-yaml' import { REPO_ROOT } from './repo-root.mjs' @@ -44,8 +44,8 @@ export function workflowFiles() { /** * Parse one repo-relative YAML file from the workflow graph — a workflow, or a * composite action manifest that a workflow reaches through `uses: ./...`. - * `workflow-node-gyp.test.mjs` follows those `uses:` edges and needs to parse - * both kinds with the same reader. + * `flattenSteps` below follows those `uses:` edges and needs to parse both + * kinds with the same reader. * * Note for callers: `on:` parses as the boolean `true` under YAML 1.1 (the * "Norway problem"), so read triggers as `wf.on ?? wf[true]`. @@ -53,3 +53,98 @@ export function workflowFiles() { export function readWorkflow(relPath) { return yaml.load(readFileSync(join(REPO_ROOT, relPath), 'utf8')) } + +export function usesOf(step) { + return typeof step?.uses === 'string' ? step.uses.trim() || null : null +} + +const LOCAL_USES = /^\.{1,2}\// + +function stepLabel(step, index) { + return step?.name || usesOf(step) || `step #${index + 1}` +} + +/** + * Flattens a step list, splicing a local composite action's own steps in at the + * position of the `uses:` that reaches it. The result is the sequence GitHub + * actually executes, which is the only sequence in which "before" means + * anything. + * + * `resolveComposite` is injected so a guard can exercise its checker against + * synthetic composites without writing fixture files — an in-repo scan is not + * a test of the traversal, it is a test of the repo. The repo's own resolver is + * `resolveRepoComposite`. + * + * `expanding` holds only the composites on the current call path, which is + * enough to break the `A uses B uses A` cycle. A composite leaves it once its + * expansion ends, so a second call to it is expanded again: GitHub runs it + * twice, and a guard that counts steps must see both runs. + * + * Each entry's `conditions` lists the `if:` of every composite call that + * encloses the step, outermost first. GitHub skips the whole composite when + * one of them is false, whatever the step's own `if:` says. + */ +export function flattenSteps( + steps, + resolveComposite, + trail = '', + expanding = new Set(), + conditions = [], +) { + const flat = [] + const unresolved = [] + + ;(Array.isArray(steps) ? steps : []).forEach((step, index) => { + const label = `${trail}${stepLabel(step, index)}` + const uses = usesOf(step) + + if (uses === null || !LOCAL_USES.test(uses)) { + flat.push({ step, label, conditions }) + return + } + + const composite = resolveComposite(uses) + if (composite === null) { + // Fail closed. A local `uses:` pointing at nothing fails the job on + // GitHub anyway; passing it here would make "rename the action" a way to + // leave a check with nothing to read. + unresolved.push(`${label}: \`uses: ${uses}\` — no action manifest there`) + flat.push({ step, label, conditions }) + return + } + if (expanding.has(composite.id)) return + expanding.add(composite.id) + + const nested = flattenSteps( + composite.steps, + resolveComposite, + `${label} -> ${composite.id} step "`, + expanding, + step?.if === undefined ? conditions : [...conditions, step.if], + ) + expanding.delete(composite.id) + for (const entry of nested.flat) { + flat.push({ ...entry, label: `${entry.label}"` }) + } + unresolved.push(...nested.unresolved) + }) + + return { flat, unresolved } +} + +/** + * GitHub resolves `uses: ./x` against the checkout root, not the calling file. + * Both manifest spellings are valid, so probing only `action.yml` would stop + * the traversal dead at a composite that used the other one. + */ +export function resolveRepoComposite(usesPath) { + const dir = usesPath.replace(LOCAL_USES, '') + for (const name of ['action.yml', 'action.yaml']) { + const rel = `${dir}/${name}` + if (existsSync(join(REPO_ROOT, rel))) { + const doc = readWorkflow(rel) + return { id: rel, steps: doc?.runs?.steps ?? [] } + } + } + return null +} diff --git a/scripts/__tests__/workflow-codeql-analyze.test.mjs b/scripts/__tests__/workflow-codeql-analyze.test.mjs new file mode 100644 index 0000000000..48432ea193 --- /dev/null +++ b/scripts/__tests__/workflow-codeql-analyze.test.mjs @@ -0,0 +1,195 @@ +import { describe, expect, it } from 'vitest' +import { + flattenSteps, + readWorkflow, + resolveRepoComposite, + workflowFiles, +} from './lib/workflows.mjs' + +/** + * A job that starts CodeQL must also run the analysis. + * + * `codeql-action/init` only prepares the database. `codeql-action/analyze` + * runs the queries and uploads the results. Commit `ed08dce88`, on 12 May + * 2026, changed the analysis step in `codeql.yml` to name `init` by mistake. + * Until November 2026 the job still passed, with only a warning about the + * unexpected `category` input, so nothing showed that no code on `main` was + * analysed. + */ +const CODEQL_STEP = /^github\/codeql-action\/(init|analyze)@/ + +// A local action that cannot be opened is reported, because a CodeQL step +// could be inside it. +function codeqlSteps(steps, resolveComposite) { + const { flat, unresolved } = flattenSteps(steps, resolveComposite) + const found = flat.flatMap(({ step, label, conditions }) => { + const match = + typeof step?.uses === 'string' ? step.uses.match(CODEQL_STEP) : null + return match ? [{ action: match[1], step, label, conditions }] : [] + }) + return { + actions: found.map(({ action }) => action), + analyses: found.filter(({ action }) => action === 'analyze'), + unresolved, + } +} + +// `if: false`, `if: 'false'` and `if: ${{ false }}` all skip the step. +const ALWAYS_FALSE = /^\s*(?:\$\{\{\s*false\s*\}\}|false)\s*$/ +const alwaysFalse = (condition) => + condition === false || + (typeof condition === 'string' && ALWAYS_FALSE.test(condition)) + +// `enclosing` is the `if:` of each composite call around the step, from +// `flattenSteps`. The analyze action uploads to code scanning only when +// `upload` is `always`, which is its default. +function analysisProblem(step, enclosing = []) { + if (alwaysFalse(step?.if)) { + return '`if:` is always false, so the analysis never runs' + } + if (enclosing.some(alwaysFalse)) { + return 'the composite action around it is called with an `if:` that is always false, so the analysis never runs' + } + const upload = step?.with?.upload + if (upload !== undefined && upload !== 'always') { + return `\`upload: ${upload}\` keeps the results out of code scanning. Remove \`upload\`, or set it to \`always\`.` + } + return null +} + +const scanned = workflowFiles().flatMap((file) => + Object.entries(readWorkflow(file)?.jobs ?? {}).map(([id, job]) => ({ + ref: `${file}#${id}`, + ...codeqlSteps(job?.steps, resolveRepoComposite), + })), +) +const codeqlJobs = scanned.filter(({ actions }) => actions.length > 0) + +describe('CodeQL jobs run the analysis', () => { + it('finds the CodeQL job', () => { + // An empty scan would pass the check below. + expect(codeqlJobs.map(({ ref }) => ref)).toContain( + '.github/workflows/codeql.yml#analyze', + ) + }) + + it('opens every local action that a job uses', () => { + const unresolved = scanned.flatMap(({ ref, unresolved }) => + unresolved.map((entry) => `${ref}: ${entry}`), + ) + expect(unresolved).toEqual([]) + }) + + it('runs init once, then analyze, in every CodeQL job', () => { + const wrong = codeqlJobs + .filter(({ actions }) => actions.join(', ') !== 'init, analyze') + .map(({ ref, actions }) => `${ref}: ${actions.join(', ')}`) + expect(wrong).toEqual([]) + }) + + it('runs every CodeQL analysis and uploads its results', () => { + const wrong = codeqlJobs.flatMap(({ ref, analyses }) => + analyses.flatMap(({ step, label, conditions }) => { + const problem = analysisProblem(step, conditions) + return problem ? [`${ref}: ${label}: ${problem}`] : [] + }), + ) + expect(wrong).toEqual([]) + }) +}) + +describe('the checker this guard depends on', () => { + const init = { uses: 'github/codeql-action/init@v4.38.0' } + const analyze = { uses: 'github/codeql-action/analyze@v4.38.0' } + const callComposite = { uses: './.github/actions/codeql' } + const noComposites = () => null + const composite = (steps) => (uses) => + uses === callComposite.uses ? { id: 'codeql/action.yml', steps } : null + + it('reproduces the defect: init named twice', () => { + expect(codeqlSteps([init, init], noComposites).actions).toEqual([ + 'init', + 'init', + ]) + }) + + it('finds init inside a composite action', () => { + expect( + codeqlSteps([callComposite, analyze], composite([init])).actions, + ).toEqual(['init', 'analyze']) + }) + + it('finds a composite action that runs init with no analysis', () => { + expect(codeqlSteps([callComposite], composite([init])).actions).toEqual([ + 'init', + ]) + }) + + it('counts each call to the same composite action', () => { + expect( + codeqlSteps([callComposite, callComposite, analyze], composite([init])) + .actions, + ).toEqual(['init', 'init', 'analyze']) + }) + + it('reports a local action it cannot open', () => { + expect(codeqlSteps([callComposite], noComposites).unresolved).toHaveLength( + 1, + ) + }) + + it('finds an analysis inside a composite action, to check its settings', () => { + const skipped = { ...analyze, if: false } + const { analyses } = codeqlSteps( + [init, callComposite], + composite([skipped]), + ) + expect(analyses.map(({ step }) => step)).toEqual([skipped]) + }) + + // biome-ignore lint/suspicious/noTemplateCurlyInString: a literal Actions expression, as written in a workflow. + it.each([false, 'false', '${{ false }}'])( + 'refuses an analysis with `if: %j`', + (condition) => { + expect(analysisProblem({ ...analyze, if: condition })).toMatch(/`if:`/) + }, + ) + + it('refuses an analysis inside a composite action called with `if: false`', () => { + const [analysis] = codeqlSteps( + [init, { ...callComposite, if: false }], + composite([analyze]), + ).analyses + expect(analysisProblem(analysis.step, analysis.conditions)).toMatch(/`if:`/) + }) + + it('accepts an analysis inside a composite action called with no `if:`', () => { + const [analysis] = codeqlSteps( + [init, callComposite], + composite([analyze]), + ).analyses + expect(analysisProblem(analysis.step, analysis.conditions)).toBeNull() + }) + + it('accepts an analysis whose `if:` can be true', () => { + expect( + analysisProblem({ ...analyze, if: "github.event_name == 'push'" }), + ).toBeNull() + }) + + it.each(['never', 'failure-only', false])( + 'refuses an analysis with `upload: %j`', + (upload) => { + expect(analysisProblem({ ...analyze, with: { upload } })).toMatch( + /`upload: /, + ) + }, + ) + + it('accepts an analysis that leaves `upload` unset, or sets it to always', () => { + expect(analysisProblem(analyze)).toBeNull() + expect( + analysisProblem({ ...analyze, with: { upload: 'always' } }), + ).toBeNull() + }) +}) diff --git a/scripts/__tests__/workflow-node-gyp.test.mjs b/scripts/__tests__/workflow-node-gyp.test.mjs index 3cb65bb2b4..97b75bf301 100644 --- a/scripts/__tests__/workflow-node-gyp.test.mjs +++ b/scripts/__tests__/workflow-node-gyp.test.mjs @@ -1,8 +1,11 @@ -import { existsSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { REPO_ROOT } from './lib/repo-root.mjs' -import { readWorkflow, workflowFiles } from './lib/workflows.mjs' +import { + flattenSteps, + readWorkflow, + resolveRepoComposite, + usesOf, + workflowFiles, +} from './lib/workflows.mjs' /** * Every job that runs `pnpm install` on a Linux runner must install `node-gyp` @@ -137,10 +140,6 @@ const IGNORE_SCRIPTS = /--ignore-scripts\b/ */ const PREBUILT_RUNNER = /(?:^|[\s-])(?:macos|windows|win32|darwin)(?:[\s-]|$)/i -function usesOf(step) { - return typeof step?.uses === 'string' ? step.uses.trim() || null : null -} - function runOf(step) { return typeof step?.run === 'string' ? step.run : null } @@ -176,71 +175,6 @@ export function needsNodeGyp(runsOn) { // Traversal // --------------------------------------------------------------------------- -const LOCAL_USES = /^\.{1,2}\// - -function stepLabel(step, index) { - return step?.name || usesOf(step) || `step #${index + 1}` -} - -/** - * Flattens a step list, splicing a local composite action's own steps in at the - * position of the `uses:` that reaches it. The result is the sequence GitHub - * actually executes, which is the only sequence in which "before" means - * anything. - * - * `resolveComposite` is injected so the checker can be exercised against - * synthetic composites below without writing fixture files — an in-repo scan is - * not a test of the traversal, it is a test of the repo. - * - * `visited` breaks the `A uses B uses A` cycle. Scoped per job, matching - * `lint-no-workflow-caching.mjs`: a composite shared by two jobs is flattened - * into each. - */ -export function flattenSteps( - steps, - resolveComposite, - trail = '', - visited = new Set(), -) { - const flat = [] - const unresolved = [] - - ;(Array.isArray(steps) ? steps : []).forEach((step, index) => { - const label = `${trail}${stepLabel(step, index)}` - const uses = usesOf(step) - - if (uses === null || !LOCAL_USES.test(uses)) { - flat.push({ step, label }) - return - } - - const composite = resolveComposite(uses) - if (composite === null) { - // Fail closed. A local `uses:` pointing at nothing fails the job on - // GitHub anyway; passing it here would make "rename the action" a way to - // leave this check with nothing to read. - unresolved.push(`${label}: \`uses: ${uses}\` — no action manifest there`) - flat.push({ step, label }) - return - } - if (visited.has(composite.id)) return - visited.add(composite.id) - - const nested = flattenSteps( - composite.steps, - resolveComposite, - `${label} -> ${composite.id} step "`, - visited, - ) - for (const entry of nested.flat) { - flat.push({ step: entry.step, label: `${entry.label}"` }) - } - unresolved.push(...nested.unresolved) - }) - - return { flat, unresolved } -} - /** * The rule itself, over an already-flattened sequence: for each install step, * some EARLIER step must have put node-gyp on PATH. @@ -270,23 +204,6 @@ export function auditFlattened(flat) { // The repo scan // --------------------------------------------------------------------------- -/** - * GitHub resolves `uses: ./x` against the checkout root, not the calling file. - * Both manifest spellings are valid, so probing only `action.yml` would stop - * the traversal dead at a composite that used the other one. - */ -function resolveRepoComposite(usesPath) { - const dir = usesPath.replace(LOCAL_USES, '') - for (const name of ['action.yml', 'action.yaml']) { - const rel = `${dir}/${name}` - if (existsSync(join(REPO_ROOT, rel))) { - const doc = readWorkflow(rel) - return { id: rel, steps: doc?.runs?.steps ?? [] } - } - } - return null -} - function scan() { const jobs = [] for (const relPath of workflowFiles()) {