From 275dc67b74a4b2338ea3def707da3d38c2d7fcb2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:35:27 +0000 Subject: [PATCH 1/3] fix(ci): adopt the template workflow linter (SPDX header block, lock-aware pins) lint-workflows has failed on every main push since at least 2026-10-19 (runs 39242174895 .. 43851937056). The repo-local linter is a pre-fix copy: it requires the SPDX identifier on line 1, but `gh actions-lock` inserts "# This workflow is managed by gh actions-lock." there, so all 30 workflows were reported as missing a header they carry on line 2. Behind that, the "Check SHA-Pinned Actions" step only accepted inline 40-hex refs, while ruling R2 puts the tag in the YAML and the commit SHA in actions.lock, so it could never pass either. Both steps now match hyperpolymath/rsr-template-repo verbatim: - SPDX is required in the leading comment block, before the workflow body (same rule as standards governance-reusable.yml; standards issue #727); - pinning is checked by scripts/check-action-pinning.js, which accepts an inline SHA or a ref resolved by actions.lock; - Bun 1.4.2 is installed from the release zip with a sha256 check, so the linter adds no third-party action and actions.lock is unchanged for it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgmF8D98muB2umfURd --- .github/workflows/workflow-linter.yml | 45 ++++++++--- scripts/check-action-pinning.js | 105 ++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 11 deletions(-) create mode 100755 scripts/check-action-pinning.js diff --git a/.github/workflows/workflow-linter.yml b/.github/workflows/workflow-linter.yml index 9ff1a04..ea906ab 100644 --- a/.github/workflows/workflow-linter.yml +++ b/.github/workflows/workflow-linter.yml @@ -1,14 +1,15 @@ # This workflow is managed by gh actions-lock. # SPDX-License-Identifier: MPL-2.0 -# This workflow is managed by gh actions-lock. -# This workflow is managed by gh actions-lock. -# This workflow is managed by gh actions-lock. # workflow-linter.yml - Validates GitHub workflows against RSR security standards # This workflow can be copied to other repos for consistent enforcement name: Workflow Security Linter on: push: + # A PR push already runs this through pull_request; push runs only on + # main, so each PR push is linted once and main is still checked after merge. + branches: + - main paths: - '.github/workflows/**' pull_request: @@ -24,7 +25,7 @@ permissions: jobs: lint-workflows: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: contents: read @@ -39,13 +40,15 @@ jobs: failed=0 for file in .github/workflows/*.yml .github/workflows/*.yaml; do [ -f "$file" ] || continue - if ! head -1 "$file" | grep -q "^# SPDX-License-Identifier:"; then + # actions-lock may prepend its own comment. Require the licence + # in the leading comment block, before the workflow body. + if ! awk '/^# SPDX-License-Identifier:/ { found=1 } /^[[:space:]]*[^#[:space:]]/ { exit } END { exit !found }' "$file"; then echo "ERROR: $file missing SPDX header" failed=1 fi done if [ $failed -eq 1 ]; then - echo "Add '# SPDX-License-Identifier: MPL-2.0' as first line" + echo "Add '# SPDX-License-Identifier: MPL-2.0' to the leading comment block" exit 1 fi echo "All workflows have SPDX headers" @@ -67,18 +70,39 @@ jobs: fi echo "All workflows have permissions declared" + # Bun is the estate's first-choice runtime (LANGUAGE-POLICY.adoc §1: + # Bun > Deno > pnpm > npm). It is the estate pin 1.4.2, downloaded and + # sha256-checked as Estate Rules installs its tools, so this gate runs + # no third-party action and no unpinned runtime. + - name: Install verified Bun 1.4.2 + run: | + curl --proto '=https' --proto-redir '=https' --fail --silent --show-error --location \ + https://github.com/oven-sh/bun/releases/download/bun-v1.4.2/bun-linux-x64.zip \ + --output "$RUNNER_TEMP/bun.zip" + echo "36368faef7527875d5ffa52e53cd48021741f2a83eb6208a8dd64068d422a913 $RUNNER_TEMP/bun.zip" | sha256sum --check --strict + unzip -q "$RUNNER_TEMP/bun.zip" -d "$RUNNER_TEMP" + echo "$RUNNER_TEMP/bun-linux-x64" >> "$GITHUB_PATH" + - name: Check SHA-Pinned Actions run: | echo "=== Checking Action Pinning ===" # Find any uses: lines that don't have @SHA format # Pattern: uses: owner/repo@<40-char-hex> - unpinned=$(grep -rnE "^[[:space:]]+uses:" .github/workflows/ | \ - grep -v "@[a-f0-9]\{40\}" | \ - grep -v "uses: \./\|uses: docker://\|uses: actions/github-script" || true) + # Delegated to scripts/check-action-pinning.js. The rule it enforces is + # unchanged in spirit — every action ref must resolve to an immutable + # commit — but "pinned" now includes refs the workflow lockfile + # resolves, which is how this repo pins them. Kept as a script rather + # than inline because the inline form needs a heredoc inside a YAML + # block scalar, and that is a well-known way to ship a gate that + # silently does nothing. + if ! bun scripts/check-action-pinning.js; then + unpinned="see above" + else + unpinned="" + fi if [ -n "$unpinned" ]; then echo "ERROR: Found unpinned actions:" - echo "$unpinned" echo "" echo "Replace version tags with SHA pins, e.g.:" echo " uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6.0.1" @@ -118,7 +142,6 @@ jobs: has_rb=$(find . -name "*.rb" -path "*/lib/*" -o -path "*/app/*" 2>/dev/null | head -1) echo "Detected languages:" - [ -n "$has_js" ] && echo " - javascript-typescript" [ -n "$has_py" ] && echo " - python" [ -n "$has_go" ] && echo " - go" [ -n "$has_rs" ] && echo " - rust (note: CodeQL rust is limited)" diff --git a/scripts/check-action-pinning.js b/scripts/check-action-pinning.js new file mode 100755 index 0000000..80533f6 --- /dev/null +++ b/scripts/check-action-pinning.js @@ -0,0 +1,105 @@ +#!/usr/bin/env bun +// SPDX-License-Identifier: MPL-2.0 +// +// Assert every workflow action ref is pinned — inline SHA, or via actions.lock. +// +// What counts as "pinned" changed when GitHub introduced workflow lockfiles. A +// ref is pinned if EITHER it is an inline 40-hex SHA, OR +// .github/workflows/actions.lock resolves it to one. The previous inline-only +// rule rejected all 40 of this repo's own refs, so `Workflow Security Linter` +// was red on main permanently — and every repo minted from this template +// inherited both the tag-form workflows and the gate that rejects them. +// +// Runtime: Bun — the estate's first-choice runtime per LANGUAGE-POLICY.adoc §1 +// (Bun > Deno > pnpm > npm). Plain JavaScript, not TypeScript: TypeScript is +// banned estate-wide (owner ruling; CLAUDE.md banned-languages table). Note +// LANGUAGE-POLICY.adoc §1.2 currently claims TS is "permitted under Bun" — that +// line is wrong and should be corrected; the ban stands. +// +// Python was the first draft of this script and is banned with no exceptions. +// +// Three details are load-bearing, each of them a defect found by testing: +// +// `-?` in the pattern. `- uses:` is the list-item form and by far the most +// common; a `\s+uses:` pattern silently misses every one of them. Estate +// memory records this exact failure — "green linter != full SHA-pinning". A +// gate that cannot see the common case reads as coverage and enforces nothing. +// +// Case-insensitive comparison. Workflows write `SonarSource/...`; the lockfile +// records `sonarsource/...`. Action refs are case-insensitive in practice, so +// a case-sensitive match reports a false positive on a correctly-pinned action. +// +// Only *.yml / *.yaml, depth 1. A bare recursive grep also reads actions.lock +// (whose `uses:` keys are lockfile entries, not refs) and *.yml.template +// (whose tag ref is deliberate and resolved at mint time). Both were reported +// as unpinned, which made the gate unsatisfiable the moment a lockfile existed. +// +// Exit 0 if every ref is pinned, 1 otherwise, listing file:line: ref. + +import { readdirSync, readFileSync, existsSync, statSync } from "node:fs"; +import { join } from "node:path"; + +const WF = ".github/workflows"; +const LOCK = join(WF, "actions.lock"); +// `-?` matches the list-item form; see the header. +const USES = /^\s*-?\s*uses:\s*([^\s#]+)/; +const SHA = /@[a-f0-9]{40}$/; +const EXEMPT_PREFIX = ["./", "$", "docker://"]; + +function workflowFiles() { + if (!existsSync(WF) || !statSync(WF).isDirectory()) return []; + return readdirSync(WF) + .filter((f) => f.endsWith(".yml") || f.endsWith(".yaml")) + .sort() + .map((f) => join(WF, f)); +} + +function main() { + if (!existsSync(WF)) { + console.log("no .github/workflows — nothing to check"); + return 0; + } + + let known = new Set(); + if (existsSync(LOCK)) { + const lock = readFileSync(LOCK, "utf8"); + known = new Set( + [...lock.matchAll(/'([^']+@[^']+)'/g)].map((m) => m[1].toLowerCase()), + ); + console.log(`lockfile present: ${known.size} ref(s) resolvable through it`); + } else { + console.log("no lockfile — every ref must be an inline 40-character SHA"); + } + + const bad = []; + for (const wf of workflowFiles()) { + const lines = readFileSync(wf, "utf8").split("\n"); + lines.forEach((line, i) => { + const m = USES.exec(line); + if (!m) return; + const ref = m[1]; + if (EXEMPT_PREFIX.some((p) => ref.startsWith(p))) return; + if (ref.includes("actions/github-script")) return; + if (SHA.test(ref)) return; + const at = ref.lastIndexOf("@"); + const name = at === -1 ? ref : ref.slice(0, at); + const tag = at === -1 ? "" : ref.slice(at + 1); + // subpath actions key by repo root: github/codeql-action/init -> github/codeql-action + const root = name.split("/").slice(0, 2).join("/"); + if (known.has(ref.toLowerCase()) || known.has(`${root}@${tag}`.toLowerCase())) return; + bad.push(`${wf}:${i + 1}: ${ref}`); + }); + } + + if (bad.length) { + console.log("\nERROR: these action refs are neither SHA-pinned nor covered by the lockfile:"); + for (const b of bad) console.log(` ${b}`); + console.log("\nEither pin to a full commit SHA, or run `gh actions-lock` so the"); + console.log("lockfile resolves the ref."); + return 1; + } + console.log("all action refs are pinned"); + return 0; +} + +process.exit(main()); From b69d2ec072584315c5d877400c99bc39adf544ea Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:35:27 +0000 Subject: [PATCH 2/3] fix(ci): resync actions.lock with the workflow YAML Dependabot #57 and #61 bumped three actions in the YAML without updating actions.lock. standards scripts/check-lock-sync.sh reported it as out of sync, a state GitHub rejects at startup with zero jobs: - pages.yml: haskell-actions/setup v2.12.0 -> v2.12.1 (peeled commit 0f8e8c99d88aeb3fbfd523f1ef2c6f762d10d64d) - static-analysis-gate.yml: actions/download-artifact v8.0.1 -> v8.0.2 (commit 9000827ccba6bdab643e8b6fd33ac0654aef8333) - ci.yml, static-analysis-gate.yml: actions/upload-artifact v7.0.1 -> v7.0.2 (record already present; the orphaned v7.0.1 record is removed) The actions/deploy-pages record also repeated its commit SHA as `ref`, which standards scripts/check-lock-pin-contract.sh rejects as an invalid lockfile pin. Its ref is now the tag v5.0.1, which resolves to that commit. Every commit was resolved with `git ls-remote` against the action's repository. The new versions are node24 actions with no nested `uses:`. `gh actions-lock` was not available in the session that made this change, so the records were edited by hand and checked with the standards checkers instead: - check-lock-sync.sh: in sync (main: malformed/out of sync); - check-lock-pin-contract.sh: 14 violations, all the estate-wide "lock keys must be SHA-pinned" (canon rule 10) form (main: 16). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgmF8D98muB2umfURd --- .github/workflows/actions.lock | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index d7fcd45..a758a09 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -7,7 +7,7 @@ workflows: - 'actions/checkout@v7.0.1' '.github/workflows/ci.yml': - 'actions/checkout@v7.0.1' - - 'actions/upload-artifact@v7.0.1' + - 'actions/upload-artifact@v7.0.2' - 'goto-bus-stop/setup-zig@v2.2.1' '.github/workflows/codeql.yml': - 'actions/checkout@v7.0.1' @@ -37,7 +37,7 @@ workflows: - 'actions/configure-pages@v6.0.0' - 'actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346' - 'actions/upload-pages-artifact@v5.0.0' - - 'haskell-actions/setup@v2.12.0' + - 'haskell-actions/setup@v2.12.1' '.github/workflows/quality.yml': - 'actions/checkout@v7.0.1' - 'editorconfig-checker/action-editorconfig-checker@51f63319f592f97930c73d9c46184d20bd206393' @@ -61,8 +61,8 @@ workflows: - 'sonarsource/sonarqube-scan-action@v8.4.1' '.github/workflows/static-analysis-gate.yml': - 'actions/checkout@v7.0.1' - - 'actions/download-artifact@v8.0.1' - - 'actions/upload-artifact@v7.0.1' + - 'actions/download-artifact@v8.0.2' + - 'actions/upload-artifact@v7.0.2' - 'erlef/setup-beam@v1.24.1' '.github/workflows/test-suite.yml': - 'actions/checkout@v7.0.1' @@ -109,13 +109,13 @@ dependencies: owner_id: 44036562 repo_id: 513659658 'actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346': - ref: '368f82528645a54fb793d4d04e342629a3f51346' + ref: 'v5.0.1' commit: 'sha1-368f82528645a54fb793d4d04e342629a3f51346' owner_id: 44036562 repo_id: 438112499 - 'actions/download-artifact@v8.0.1': - ref: 'v8.0.1' - commit: 'sha1-3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c' + 'actions/download-artifact@v8.0.2': + ref: 'v8.0.2' + commit: 'sha1-9000827ccba6bdab643e8b6fd33ac0654aef8333' owner_id: 44036562 repo_id: 192626254 'actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f': @@ -123,11 +123,6 @@ dependencies: commit: 'sha1-bbbca2ddaa5d8feaa63e36b76fdaad77386f024f' owner_id: 44036562 repo_id: 192625955 - 'actions/upload-artifact@v7.0.1': - ref: 'v7.0.1' - commit: 'sha1-043fb46d1a93c77aae656e7c1c64a875d1fc6a0a' - owner_id: 44036562 - repo_id: 192625955 'actions/upload-artifact@v7.0.2': ref: 'v7.0.2' commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9' @@ -165,9 +160,9 @@ dependencies: commit: 'sha1-abea47f85e598557f500fa1fd2ab7464fcb39406' owner_id: 1006268 repo_id: 212984112 - 'haskell-actions/setup@v2.12.0': - ref: 'v2.12.0' - commit: 'sha1-6037f33647c3f17758a2356c80fc4a53d7e0685d' + 'haskell-actions/setup@v2.12.1': + ref: 'v2.12.1' + commit: 'sha1-0f8e8c99d88aeb3fbfd523f1ef2c6f762d10d64d' owner_id: 75048950 repo_id: 623796603 'leanprover/lean-action@ba3fdfe5c4476c925da13bf11a005ddb47e47aee': From e906f68a315c09a5d0674dc5e41051118cb3590f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:51:56 +0000 Subject: [PATCH 3/3] fix(ci): make the pinning checker parse YAML and check the lock per workflow Review of PR #68 (CodeRabbit) found the template's check-action-pinning.js weaker than the gate it replaced. A new self-test confirms each finding: the template script fails 10 of its 18 cases. - Workflows were matched line by line, so quoted refs failed and flow-style steps (`- { uses: "o/r@main" }`) were invisible. They are now parsed with Bun.YAML, and a file that does not parse is an error. - Lock coverage was one global set, so a ref passed if ANY workflow's entry listed it. Coverage is now per workflow, which is the check GitHub applies at run start. Against origin/main the new check names exactly the drift that made CI and Static Analysis Gate startup_fail on #67 (ci.yml, pages.yml, static-analysis-gate.yml). The template version missed ci.yml. - A workflow-list entry counted as pinned on its own. Its dependency record must now exist, carry a sha1-<40 hex> commit, and record the tag in its key. - `actions/github-script` was exempt by substring, which also let `evil-actions/github-script@main` through. Both are now checked. - Job-level reusable calls must be SHA-pinned. They are not required in the lock (standards#968). The linter runs scripts/tests/check-action-pinning-test.sh before the check, and both files are in the workflow's path filters, so a change to the checker triggers the linter. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgmF8D98muB2umfURd --- .github/workflows/workflow-linter.yml | 37 ++-- scripts/check-action-pinning.js | 210 +++++++++++++-------- scripts/tests/check-action-pinning-test.sh | 73 +++++++ 3 files changed, 222 insertions(+), 98 deletions(-) create mode 100755 scripts/tests/check-action-pinning-test.sh diff --git a/.github/workflows/workflow-linter.yml b/.github/workflows/workflow-linter.yml index ea906ab..4b4fd60 100644 --- a/.github/workflows/workflow-linter.yml +++ b/.github/workflows/workflow-linter.yml @@ -12,9 +12,13 @@ on: - main paths: - '.github/workflows/**' + - 'scripts/check-action-pinning.js' + - 'scripts/tests/check-action-pinning-test.sh' pull_request: paths: - '.github/workflows/**' + - 'scripts/check-action-pinning.js' + - 'scripts/tests/check-action-pinning-test.sh' workflow_dispatch: concurrency: @@ -83,32 +87,19 @@ jobs: unzip -q "$RUNNER_TEMP/bun.zip" -d "$RUNNER_TEMP" echo "$RUNNER_TEMP/bun-linux-x64" >> "$GITHUB_PATH" + # The checker is tested before it judges anything: a gate that has + # regressed to passing everything must fail here, not go green below. + - name: Self-test the pinning checker + run: bash scripts/tests/check-action-pinning-test.sh + - name: Check SHA-Pinned Actions run: | echo "=== Checking Action Pinning ===" - # Find any uses: lines that don't have @SHA format - # Pattern: uses: owner/repo@<40-char-hex> - # Delegated to scripts/check-action-pinning.js. The rule it enforces is - # unchanged in spirit — every action ref must resolve to an immutable - # commit — but "pinned" now includes refs the workflow lockfile - # resolves, which is how this repo pins them. Kept as a script rather - # than inline because the inline form needs a heredoc inside a YAML - # block scalar, and that is a well-known way to ship a gate that - # silently does nothing. - if ! bun scripts/check-action-pinning.js; then - unpinned="see above" - else - unpinned="" - fi - - if [ -n "$unpinned" ]; then - echo "ERROR: Found unpinned actions:" - echo "" - echo "Replace version tags with SHA pins, e.g.:" - echo " uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6.0.1" - exit 1 - fi - echo "All actions are SHA-pinned" + # Every step-level ref must be an inline 40-hex SHA, or be listed + # under its own workflow in actions.lock with a dependency record + # that resolves to a commit (the check GitHub applies at run start). + # Job-level reusable calls must be SHA-pinned. See the script header. + bun scripts/check-action-pinning.js - name: Check for Duplicate Workflows run: | diff --git a/scripts/check-action-pinning.js b/scripts/check-action-pinning.js index 80533f6..63a8554 100755 --- a/scripts/check-action-pinning.js +++ b/scripts/check-action-pinning.js @@ -1,104 +1,164 @@ #!/usr/bin/env bun // SPDX-License-Identifier: MPL-2.0 // -// Assert every workflow action ref is pinned — inline SHA, or via actions.lock. +// Assert every workflow action ref is pinned to an immutable commit, and that +// actions.lock covers every step-level ref under the workflow that uses it. // -// What counts as "pinned" changed when GitHub introduced workflow lockfiles. A -// ref is pinned if EITHER it is an inline 40-hex SHA, OR -// .github/workflows/actions.lock resolves it to one. The previous inline-only -// rule rejected all 40 of this repo's own refs, so `Workflow Security Linter` -// was red on main permanently — and every repo minted from this template -// inherited both the tag-form workflows and the gate that rejects them. +// Pinned means EITHER an inline 40-hex SHA, OR a ref that actions.lock lists +// under THIS workflow and resolves through a well-formed dependency record +// (commit `sha1-<40 hex>`, and `ref` equal to the tag in the key). That is the +// per-workflow check GitHub itself applies at run start: a workflow that asks +// for a ref its own lock entry lacks is refused with zero jobs. Measured on +// this repo 2026-11-17: `CI` and `Static Analysis Gate` hit startup_failure +// on PR #67 for exactly that drift, and both ran once the lock was resynced. // -// Runtime: Bun — the estate's first-choice runtime per LANGUAGE-POLICY.adoc §1 -// (Bun > Deno > pnpm > npm). Plain JavaScript, not TypeScript: TypeScript is -// banned estate-wide (owner ruling; CLAUDE.md banned-languages table). Note -// LANGUAGE-POLICY.adoc §1.2 currently claims TS is "permitted under Bun" — that -// line is wrong and should be corrected; the ban stands. +// Why each rule is here (all found in review of the earlier template copy): // -// Python was the first draft of this script and is banned with no exceptions. +// * Workflows are PARSED (Bun.YAML), not matched line by line, so quoted +// refs and flow-style steps (`- { uses: "o/r@main" }`) are seen. A file +// that does not parse is an error, never "no refs found". +// * Coverage is per workflow. A global set accepted a ref because some OTHER +// workflow's lock entry listed it. +// * A workflow-list entry is not proof on its own: its dependency record +// must exist and resolve to a commit. +// * No name-based exemptions. `actions/github-script` used to be skipped by +// substring, which also let `evil-actions/github-script@main` through. +// Only local actions (`./…`) and `docker://` images are not GitHub refs. +// * Job-level reusable-workflow calls (`jobs..uses`) must be SHA-pinned +// but are not required in the lock: GitHub does not check them there +// (standards#968, measured harmless). // -// Three details are load-bearing, each of them a defect found by testing: -// -// `-?` in the pattern. `- uses:` is the list-item form and by far the most -// common; a `\s+uses:` pattern silently misses every one of them. Estate -// memory records this exact failure — "green linter != full SHA-pinning". A -// gate that cannot see the common case reads as coverage and enforces nothing. -// -// Case-insensitive comparison. Workflows write `SonarSource/...`; the lockfile -// records `sonarsource/...`. Action refs are case-insensitive in practice, so -// a case-sensitive match reports a false positive on a correctly-pinned action. -// -// Only *.yml / *.yaml, depth 1. A bare recursive grep also reads actions.lock -// (whose `uses:` keys are lockfile entries, not refs) and *.yml.template -// (whose tag ref is deliberate and resolved at mint time). Both were reported -// as unpinned, which made the gate unsatisfiable the moment a lockfile existed. -// -// Exit 0 if every ref is pinned, 1 otherwise, listing file:line: ref. +// Runtime: Bun (estate first choice). Plain JavaScript, not TypeScript. +// Exit 0 if every ref passes, 1 otherwise (listing file: problem), 2 on a +// usage error. `--root DIR` checks another tree (used by the self-test). import { readdirSync, readFileSync, existsSync, statSync } from "node:fs"; import { join } from "node:path"; -const WF = ".github/workflows"; +const args = process.argv.slice(2); +const rootIdx = args.indexOf("--root"); +const ROOT = rootIdx === -1 ? "." : args[rootIdx + 1]; +if (rootIdx !== -1 && !ROOT) { + console.error("usage: check-action-pinning.js [--root DIR]"); + process.exit(2); +} +const WF = join(ROOT, ".github/workflows"); const LOCK = join(WF, "actions.lock"); -// `-?` matches the list-item form; see the header. -const USES = /^\s*-?\s*uses:\s*([^\s#]+)/; -const SHA = /@[a-f0-9]{40}$/; -const EXEMPT_PREFIX = ["./", "$", "docker://"]; +const isSha = (s) => s.length === 40 && /^[0-9a-f]+$/.test(s); -function workflowFiles() { - if (!existsSync(WF) || !statSync(WF).isDirectory()) return []; - return readdirSync(WF) - .filter((f) => f.endsWith(".yml") || f.endsWith(".yaml")) - .sort() - .map((f) => join(WF, f)); +// owner/repo[/path]@ref -> { root: "owner/repo" (lower-cased), ref } +function split(uses) { + const at = uses.lastIndexOf("@"); + if (at <= 0 || at === uses.length - 1) return null; + const parts = uses.slice(0, at).split("/"); + if (parts.length < 2 || !parts[0] || !parts[1]) return null; + return { root: `${parts[0]}/${parts[1]}`.toLowerCase(), ref: uses.slice(at + 1) }; } -function main() { - if (!existsSync(WF)) { - console.log("no .github/workflows — nothing to check"); - return 0; +// Every `uses:` in a parsed workflow, tagged step or job level. +function refsOf(doc) { + const out = []; + const jobs = doc && typeof doc === "object" ? doc.jobs : null; + if (!jobs || typeof jobs !== "object") return out; + for (const [id, job] of Object.entries(jobs)) { + if (!job || typeof job !== "object") continue; + if (typeof job.uses === "string") out.push({ level: "job", where: `jobs.${id}`, uses: job.uses.trim() }); + if (Array.isArray(job.steps)) { + job.steps.forEach((step, i) => { + if (step && typeof step === "object" && typeof step.uses === "string") { + out.push({ level: "step", where: `jobs.${id}.steps[${i}]`, uses: step.uses.trim() }); + } + }); + } } + return out; +} - let known = new Set(); - if (existsSync(LOCK)) { - const lock = readFileSync(LOCK, "utf8"); - known = new Set( - [...lock.matchAll(/'([^']+@[^']+)'/g)].map((m) => m[1].toLowerCase()), - ); - console.log(`lockfile present: ${known.size} ref(s) resolvable through it`); - } else { - console.log("no lockfile — every ref must be an inline 40-character SHA"); +function loadLock(bad) { + if (!existsSync(LOCK)) return null; + let lock; + try { + lock = Bun.YAML.parse(readFileSync(LOCK, "utf8")); + } catch (e) { + bad.push(`${LOCK}: does not parse (${e.message})`); + return undefined; } + if (!lock || typeof lock.workflows !== "object" || typeof lock.dependencies !== "object") { + bad.push(`${LOCK}: missing 'workflows' or 'dependencies' map`); + return undefined; + } + // Dependency records that resolve, keyed by lower-cased owner/repo@ref. + const resolved = new Set(); + for (const [key, rec] of Object.entries(lock.dependencies)) { + const k = split(key); + const commit = rec && typeof rec.commit === "string" ? rec.commit : ""; + const okCommit = commit.startsWith("sha1-") && isSha(commit.slice(5).toLowerCase()); + // A tag key must record that tag; a SHA key must resolve to that SHA. + const okRef = k && (isSha(k.ref) ? commit.toLowerCase() === `sha1-${k.ref}` : rec.ref === k.ref); + if (k && okCommit && okRef) resolved.add(`${k.root}@${k.ref}`); + else bad.push(`${LOCK}: dependency record '${key}' does not resolve to a commit`); + } + // Per-workflow lists, keyed by workflow path relative to the root. + const perWorkflow = new Map(); + for (const [path, list] of Object.entries(lock.workflows)) { + const set = new Set(); + for (const entry of Array.isArray(list) ? list : []) { + const k = typeof entry === "string" ? split(entry) : null; + if (k) set.add(`${k.root}@${k.ref}`); + } + perWorkflow.set(path, set); + } + return { resolved, perWorkflow }; +} +function main() { + if (!existsSync(WF) || !statSync(WF).isDirectory()) { + console.log("no .github/workflows — nothing to check"); + return 0; + } const bad = []; - for (const wf of workflowFiles()) { - const lines = readFileSync(wf, "utf8").split("\n"); - lines.forEach((line, i) => { - const m = USES.exec(line); - if (!m) return; - const ref = m[1]; - if (EXEMPT_PREFIX.some((p) => ref.startsWith(p))) return; - if (ref.includes("actions/github-script")) return; - if (SHA.test(ref)) return; - const at = ref.lastIndexOf("@"); - const name = at === -1 ? ref : ref.slice(0, at); - const tag = at === -1 ? "" : ref.slice(at + 1); - // subpath actions key by repo root: github/codeql-action/init -> github/codeql-action - const root = name.split("/").slice(0, 2).join("/"); - if (known.has(ref.toLowerCase()) || known.has(`${root}@${tag}`.toLowerCase())) return; - bad.push(`${wf}:${i + 1}: ${ref}`); - }); + const lock = loadLock(bad); + if (lock) console.log(`lockfile present: ${lock.resolved.size} resolvable record(s)`); + else if (lock === null) console.log("no lockfile — every ref must be an inline 40-character SHA"); + + const files = readdirSync(WF).filter((f) => f.endsWith(".yml") || f.endsWith(".yaml")).sort(); + let count = 0; + for (const f of files) { + const rel = `.github/workflows/${f}`; + let doc; + try { + doc = Bun.YAML.parse(readFileSync(join(WF, f), "utf8")); + } catch (e) { + bad.push(`${rel}: does not parse as YAML (${e.message})`); + continue; + } + const listed = lock ? lock.perWorkflow.get(rel) : undefined; + for (const { level, where, uses } of refsOf(doc)) { + if (uses.startsWith("./") || uses.startsWith("docker://")) continue; + count++; + const k = split(uses); + if (!k) { bad.push(`${rel} ${where}: '${uses}' is not owner/repo@ref`); continue; } + const key = `${k.root}@${k.ref}`; + if (level === "job") { + if (!isSha(k.ref)) bad.push(`${rel} ${where}: reusable workflow '${uses}' is not pinned to a 40-hex commit`); + continue; + } + if (lock) { + if (!listed || !listed.has(key)) bad.push(`${rel} ${where}: '${uses}' is not in this workflow's actions.lock entry`); + else if (!lock.resolved.has(key)) bad.push(`${rel} ${where}: '${uses}' has no dependency record that resolves to a commit`); + } else if (!isSha(k.ref)) { + bad.push(`${rel} ${where}: '${uses}' is not pinned to a 40-hex commit`); + } + } } if (bad.length) { - console.log("\nERROR: these action refs are neither SHA-pinned nor covered by the lockfile:"); + console.log("\nERROR: unpinned or unlocked action refs:"); for (const b of bad) console.log(` ${b}`); - console.log("\nEither pin to a full commit SHA, or run `gh actions-lock` so the"); - console.log("lockfile resolves the ref."); + console.log("\nPin to a full commit SHA, or run `gh actions-lock` so this workflow's lock entry resolves the ref."); return 1; } - console.log("all action refs are pinned"); + console.log(`all ${count} action ref(s) in ${files.length} workflow(s) are pinned`); return 0; } diff --git a/scripts/tests/check-action-pinning-test.sh b/scripts/tests/check-action-pinning-test.sh new file mode 100755 index 0000000..2eb6af5 --- /dev/null +++ b/scripts/tests/check-action-pinning-test.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# Self-test for scripts/check-action-pinning.js. Each case builds a tiny +# .github/workflows tree and asserts the checker's exit code. The cases are +# the gaps found in review of the earlier template copy, so a regression to +# line matching, a global lock set, or a name exemption fails here first. +# Needs bun on PATH. No network. +set -uo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +checker="$here/../check-action-pinning.js" +work="$(mktemp -d)"; trap 'rm -rf "$work"' EXIT +pass=0; fail=0 +SHA=3d3c42e5aac5ba805825da76410c181273ba90b1 + +# tree [lock-yaml] — workflow lands at a.yml. +tree() { + mkdir -p "$work/$1/.github/workflows" + printf '%s\n' "$2" > "$work/$1/.github/workflows/a.yml" + [ -n "${3:-}" ] && printf '%s\n' "$3" > "$work/$1/.github/workflows/actions.lock" + return 0 +} +expect() { # expect