Skip to content

Commit 4a62f9f

Browse files
cliffhallclaude
andauthored
feat: verify:action-pins, a SHA-pin guard for credentialed workflow jobs
Ported from the Inspector (inspector#2484). A job that can mint an OIDC token or push a package, is handed a secret other than GITHUB_TOKEN, or uploads an artifact such a job downloads, may only use actions pinned to a commit SHA with the release in a trailing comment. The SHA matcher lives in scripts/lib/action-refs.mjs so the dependency sweep planned in #4874 can share it. claude.yml (id-token: write, ANTHROPIC_API_KEY) is pinned here; release.yml is pinned with its split in the next commit, and the guard joins validate:guards there, once the tree passes it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 6a1d753 commit 4a62f9f

5 files changed

Lines changed: 709 additions & 2 deletions

File tree

‎.github/workflows/claude.yml‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ on:
1111
types: [submitted]
1212

1313
jobs:
14+
# This job holds a credential twice over (`id-token: write`, and the
15+
# `ANTHROPIC_API_KEY` secret), so every action in it is pinned to a commit
16+
# SHA with the release it came from in a trailing comment. A moving tag
17+
# here would let whoever can move it run code next to both.
18+
# `verify:action-pins` enforces it.
1419
claude:
1520
timeout-minutes: 30
1621
if: |
@@ -27,13 +32,13 @@ jobs:
2732
actions: read
2833
steps:
2934
- name: Checkout repository
30-
uses: actions/checkout@v6
35+
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
3136
with:
3237
fetch-depth: 1
3338

3439
- name: Run Claude Code
3540
id: claude
36-
uses: anthropics/claude-code-action@v1
41+
uses: anthropics/claude-code-action@12dd8d74c712f5f3669365b2369b558c495b1104 # v1.0.238
3742
with:
3843
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
3944

‎scripts/lib/action-refs.mjs‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// What an action reference (`uses: owner/repo@ref`) can be, for the guards
2+
// and sweeps that read workflow files (#4873).
3+
//
4+
// One fact lives here: the only immutable form of a ref is a full-length
5+
// commit SHA. `verify:action-pins` requires that form in credentialed jobs
6+
// today. The dependency sweep planned in #4874 will read the same pins to
7+
// report a newer release, and it must agree with the guard about what a pin
8+
// is, so the matcher is a module of its own rather than a constant inside
9+
// either script. (The Inspector keeps it in its `dependency-refresh.mjs`,
10+
// which this repo does not have yet.)
11+
12+
/** A full-length commit SHA, the only immutable form a `uses:` ref can take. */
13+
export const SHA_REF = /^[0-9a-f]{40}$/;
14+
15+
/**
16+
* The exact release a SHA pin was resolved from, as written in the trailing
17+
* comment: `# v7.0.1`. A major-only `# v7` does not say which commit was
18+
* meant, and a sweep could then compare it at major precision only, which is
19+
* the moving-tag behavior the pin exists to remove.
20+
*/
21+
export const EXACT_VERSION = /^v\d+\.\d+\.\d+$/;
22+
23+
/**
24+
* Split a `uses:` value into its action and ref. A local action (`./…`) or a
25+
* container image (`docker://…`) has no ref to pin and returns `null`; so does
26+
* a value with no `@` at all.
27+
*
28+
* @param {string} uses
29+
* @returns {{ action: string, ref: string } | null}
30+
*/
31+
export function parseUses(uses) {
32+
if (uses.startsWith("./") || uses.startsWith("docker://")) return null;
33+
const at = uses.lastIndexOf("@");
34+
if (at === -1) return null;
35+
return { action: uses.slice(0, at), ref: uses.slice(at + 1) };
36+
}
37+
38+
/**
39+
* Is this `uses:` value, with the comment that trails it, an immutable pin
40+
* that names the release it came from?
41+
*
42+
* @param {string} uses
43+
* @param {string | null | undefined} comment the YAML comment after the value, without its `#`
44+
* @returns {boolean}
45+
*/
46+
export function isPinned(uses, comment) {
47+
const parsed = parseUses(uses);
48+
return (
49+
parsed !== null &&
50+
SHA_REF.test(parsed.ref) &&
51+
EXACT_VERSION.test((comment ?? "").trim())
52+
);
53+
}

‎scripts/lib/action-refs.test.mjs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Tests for the action-reference matcher (#4873).
2+
// Run via `npm run test:scripts`.
3+
4+
import { test } from "node:test";
5+
import assert from "node:assert/strict";
6+
import { EXACT_VERSION, SHA_REF, isPinned, parseUses } from "./action-refs.mjs";
7+
8+
const SHA = "3d3c42e5aac5ba805825da76410c181273ba90b1";
9+
10+
test("only a full-length lowercase hex SHA is an immutable ref", () => {
11+
assert.equal(SHA_REF.test(SHA), true);
12+
for (const ref of [
13+
"v7",
14+
"v7.0.1",
15+
"main",
16+
SHA.slice(0, 7),
17+
SHA.toUpperCase(),
18+
`${SHA}0`,
19+
])
20+
assert.equal(SHA_REF.test(ref), false, ref);
21+
});
22+
23+
test("a version comment names an exact release", () => {
24+
assert.equal(EXACT_VERSION.test("v7.0.1"), true);
25+
for (const v of ["v7", "v7.0", "7.0.1", "release/v1", "pinned"])
26+
assert.equal(EXACT_VERSION.test(v), false, v);
27+
});
28+
29+
test("parseUses splits at the last @ and skips what has no ref", () => {
30+
assert.deepEqual(parseUses(`actions/checkout@${SHA}`), {
31+
action: "actions/checkout",
32+
ref: SHA,
33+
});
34+
assert.deepEqual(parseUses("org/repo/.github/workflows/x.yml@main"), {
35+
action: "org/repo/.github/workflows/x.yml",
36+
ref: "main",
37+
});
38+
assert.equal(parseUses("./.github/actions/local"), null);
39+
assert.equal(parseUses("docker://alpine:3.20"), null);
40+
assert.equal(parseUses("actions/checkout"), null);
41+
});
42+
43+
test("isPinned needs both the SHA and the exact-version comment", () => {
44+
assert.equal(isPinned(`actions/checkout@${SHA}`, " v7.0.1"), true);
45+
assert.equal(isPinned(`actions/checkout@${SHA}`, " v7"), false);
46+
assert.equal(isPinned(`actions/checkout@${SHA}`, undefined), false);
47+
assert.equal(isPinned("actions/checkout@v7", " v7.0.1"), false);
48+
assert.equal(isPinned("actions/checkout", " v7.0.1"), false);
49+
});

‎scripts/verify-action-pins.mjs‎

Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
#!/usr/bin/env node
2+
// Guard: every action a CREDENTIALED job runs is pinned to a commit SHA (#4873).
3+
// Ported from the MCP Inspector's `scripts/verify-action-pins.mjs`
4+
// (inspector#2484).
5+
//
6+
// This repo's workflows use moving major tags (`actions/checkout@v6`), and for
7+
// an ordinary CI job that stays the convention. It is the wrong rule for a job
8+
// holding a credential: a tag is mutable, so whoever can move `v6` replaces the
9+
// code that runs next to the credential, on the next run, with no change in
10+
// this repository. A SHA cannot be moved. So the narrower rule is: a job
11+
// holding a credential runs only SHA-pinned actions, each with a trailing
12+
// `# vX.Y.Z` comment naming the release the SHA was resolved from. The comment
13+
// is what a reviewer reads, and what the dependency sweep planned in #4874
14+
// will read to report a newer release (`scripts/lib/action-refs.mjs` holds the
15+
// matcher both use).
16+
//
17+
// A job counts as credentialed when it
18+
//
19+
// 1. can mint an OIDC token or push a package: `id-token: write` or
20+
// `packages: write` (or `write-all`), in its own `permissions:` or, absent
21+
// one, the workflow's. Here that is `release.yml`'s two publish jobs and
22+
// `claude.yml`;
23+
// 2. is handed any secret other than `GITHUB_TOKEN`, its own or through the
24+
// workflow-level `env:`, in any spelling of the expression (`secrets.X`,
25+
// `secrets['X']`, `secrets[matrix.name]`), or as a reusable-workflow
26+
// call's `secrets: inherit` (a `secrets:` mapping is read like any other
27+
// expression, so one passing only `GITHUB_TOKEN` does not count). Here
28+
// that is `claude.yml` again, for `ANTHROPIC_API_KEY`; or
29+
// 3. uploads an artifact that a credentialed job downloads and `needs`,
30+
// transitively, so every hop of a `source → package → publish` chain
31+
// counts, not only the last. Here that is `release.yml`'s two build jobs:
32+
// each builds the tarball or wheel its publish job hands to the registry
33+
// under provenance, so a moved tag in the build job publishes as surely
34+
// as one in the publish job would. (The build was split out of the
35+
// publish job to keep the OIDC token away from dependency installs; this
36+
// keeps a moving tag out of what gets published.)
37+
//
38+
// `GITHUB_TOKEN` alone does not count: every job holds one, so counting it
39+
// would turn this into "pin everything", which #4873 does not ask. That is why
40+
// `version-packages.yml` and `prepare-python-release.yml` are out of scope
41+
// although they push branches, and why an upload nothing credentialed
42+
// downloads (`python.yml`'s `dist` artifact) is too.
43+
//
44+
// Parsed with `yaml` (already a root devDependency), for the reason
45+
// `scripts/lib/workflow-gate.mjs` records: hand-rolled workflow parsing loses
46+
// to spellings it had not anticipated. Comments are not data to the parser, so
47+
// a comment that quotes `id-token: write` while explaining why a job does NOT
48+
// hold it cannot trip rule 1, and the one comment that matters, the
49+
// `# vX.Y.Z` after a `uses:`, is read off its node.
50+
//
51+
// Checked offline: a SHA that does not match its comment's release cannot be
52+
// seen without the network. Resolve both from the same lookup when bumping
53+
// (the `release` skill has the command).
54+
//
55+
// ⚠️ Local `./…` actions and reusable workflows are skipped, not traced: the
56+
// remote `uses:` INSIDE one runs under its caller's credentials but is not
57+
// associated with the caller here, and composite-action files are not read at
58+
// all. None exists in this repo; adding the first one to a credentialed job
59+
// means extending this guard to follow it, or it is a silent bypass.
60+
61+
import { readdirSync, readFileSync } from "node:fs";
62+
import path from "node:path";
63+
import { fileURLToPath, pathToFileURL } from "node:url";
64+
import { isAlias, isMap, isScalar, isSeq, parseDocument, visit } from "yaml";
65+
import { isPinned, parseUses } from "./lib/action-refs.mjs";
66+
67+
const repoRoot = path.resolve(
68+
path.dirname(fileURLToPath(import.meta.url)),
69+
"..",
70+
);
71+
72+
// `GITHUB_TOKEN` in either accessor spelling; removed before looking for any
73+
// other `secrets` reference, so every spelling of every other name, a dynamic
74+
// index included, still reads as a secret.
75+
const DEFAULT_TOKEN =
76+
/\bsecrets\s*(?:\.\s*GITHUB_TOKEN\b|\[\s*(['"])GITHUB_TOKEN\1\s*\])/g;
77+
const EXPRESSION = /\$\{\{([\s\S]*?)\}\}/g;
78+
79+
/** Does this `permissions:` value let the job mint a token or push a package? */
80+
function mints(permissions) {
81+
if (permissions === "write-all") return true;
82+
if (permissions === null || typeof permissions !== "object") return false;
83+
return (
84+
permissions["id-token"] === "write" || permissions.packages === "write"
85+
);
86+
}
87+
88+
/** Every string anywhere in a parsed value — keys excluded, as they hold no expression. */
89+
function stringsIn(value) {
90+
if (typeof value === "string") return [value];
91+
if (value === null || typeof value !== "object") return [];
92+
return Object.values(value).flatMap(stringsIn);
93+
}
94+
95+
/**
96+
* Is this job handed any secret but `GITHUB_TOKEN`? `inherited` is the
97+
* workflow-level `env:`, which every job receives the way a job with no
98+
* `permissions:` of its own receives the workflow's.
99+
*/
100+
function handedSecret(job, inherited) {
101+
// `inherit` hands over every secret with no expression to scan. A mapping
102+
// is scanned below with everything else.
103+
if (job.secrets === "inherit") return true;
104+
return stringsIn([job, inherited]).some((text) =>
105+
[...text.matchAll(EXPRESSION)].some(([, body]) =>
106+
/\bsecrets\b/.test(body.replace(DEFAULT_TOKEN, "")),
107+
),
108+
);
109+
}
110+
111+
const needsOf = (job) =>
112+
job.needs == null ? [] : [job.needs].flat().map(String);
113+
114+
const stepsUsing = (job, action) =>
115+
(job.steps ?? []).some(
116+
(step) => typeof step?.uses === "string" && step.uses.startsWith(action),
117+
);
118+
119+
/**
120+
* @param {string} yaml raw contents of a workflow file
121+
* @param {string} [file] only for the parse-error message
122+
*/
123+
function parseWorkflow(yaml, file = "<workflow>") {
124+
const doc = parseDocument(yaml);
125+
if (doc.errors.length > 0)
126+
throw new Error(
127+
`verify:action-pins: could not parse ${file}: ${doc.errors[0].message}`,
128+
);
129+
return doc;
130+
}
131+
132+
/**
133+
* The names of the jobs in this workflow that hold a credential, per the rules
134+
* in the header.
135+
*
136+
* @param {string} yaml raw contents of a workflow file
137+
* @param {string} [file] only for the parse-error message
138+
* @returns {Set<string>}
139+
*/
140+
export function credentialedJobs(yaml, file) {
141+
const workflow = parseWorkflow(yaml, file).toJS() ?? {};
142+
const jobs = Object.entries(workflow.jobs ?? {});
143+
const held = new Set();
144+
for (const [name, job] of jobs) {
145+
const permissions =
146+
"permissions" in job ? job.permissions : workflow.permissions;
147+
if (mints(permissions) || handedSecret(job, workflow.env)) held.add(name);
148+
}
149+
// To a fixed point: marking a producer credentialed can make ITS producers
150+
// credentialed, and job order in the file says nothing about the chain.
151+
for (let grew = true; grew; ) {
152+
grew = false;
153+
for (const [name, job] of jobs) {
154+
if (!held.has(name) || !stepsUsing(job, "actions/download-artifact@"))
155+
continue;
156+
for (const producer of needsOf(job)) {
157+
const upstream = workflow.jobs[producer];
158+
if (
159+
upstream &&
160+
!held.has(producer) &&
161+
stepsUsing(upstream, "actions/upload-artifact@")
162+
) {
163+
held.add(producer);
164+
grew = true;
165+
}
166+
}
167+
}
168+
}
169+
return held;
170+
}
171+
172+
/**
173+
* Every `uses:` in a credentialed job that is not a 40-hex SHA followed by a
174+
* `# vX.Y.Z` comment: each step's, and the job's own when it calls a reusable
175+
* workflow, whose ref is just as mutable. Local (`./…`) actions and workflows
176+
* are repository code, not a ref.
177+
*
178+
* A YAML alias anywhere in a credentialed job is itself a finding. Resolving it
179+
* here would accept a pin that a line-oriented reader (a reviewer, or a sweep
180+
* that reads `uses:` lines) cannot see where it is used; spelling the ref out
181+
* is the only form both can read.
182+
*
183+
* @param {string} yaml raw contents of a workflow file
184+
* @param {string} [file] only for the parse-error message
185+
* @returns {Array<{job: string, uses: string}>}
186+
*/
187+
export function unpinnedRefs(yaml, file) {
188+
const held = credentialedJobs(yaml, file);
189+
const jobs = parseWorkflow(yaml, file).get("jobs", true);
190+
const problems = [];
191+
if (!isMap(jobs)) return problems;
192+
for (const { key, value } of jobs.items) {
193+
const name = String(isScalar(key) ? key.value : key);
194+
if (!held.has(name)) continue;
195+
if (!isMap(value)) {
196+
if (isAlias(value))
197+
problems.push({ job: name, uses: `*${value.source}` });
198+
continue;
199+
}
200+
visit(value, {
201+
Alias: (_, node) => {
202+
problems.push({ job: name, uses: `*${node.source}` });
203+
},
204+
});
205+
const steps = value.get("steps", true);
206+
const nodes = [
207+
value.get("uses", true),
208+
...(isSeq(steps) ? steps.items : []).map((step) =>
209+
isMap(step) ? step.get("uses", true) : undefined,
210+
),
211+
];
212+
for (const node of nodes) {
213+
if (!isScalar(node) || typeof node.value !== "string") continue;
214+
const uses = node.value;
215+
if (uses.startsWith("./")) continue;
216+
// A value with no `@ref` at all, or a container image, is not pinned
217+
// either: `parseUses` returns null for both and `isPinned` rejects it.
218+
if (parseUses(uses) === null || !isPinned(uses, node.comment))
219+
problems.push({ job: name, uses });
220+
}
221+
}
222+
return problems;
223+
}
224+
225+
export function main(root = repoRoot) {
226+
const dir = path.join(root, ".github", "workflows");
227+
const files = readdirSync(dir).filter((f) => /\.ya?ml$/.test(f));
228+
const problems = [];
229+
let jobs = 0;
230+
for (const file of files) {
231+
const yaml = readFileSync(path.join(dir, file), "utf8");
232+
jobs += credentialedJobs(yaml, file).size;
233+
for (const p of unpinnedRefs(yaml, file))
234+
problems.push(` ${file} → ${p.job}: ${p.uses}`);
235+
}
236+
if (problems.length > 0) {
237+
console.error(
238+
`verify:action-pins — ${problems.length} action ref(s) in a credentialed job are not SHA-pinned:\n` +
239+
problems.join("\n") +
240+
"\n\nA job holding `id-token`/`packages: write`, a non-default secret, or building an" +
241+
"\nartifact such a job consumes runs only immutable refs. Pin each as" +
242+
"\n uses: owner/repo@<40-hex sha> # vX.Y.Z" +
243+
"\nresolving the SHA and the exact release from the same tag lookup. The comment" +
244+
"\nnames the release the SHA came from, for a reviewer and for the dependency sweep.",
245+
);
246+
return 1;
247+
}
248+
console.log(
249+
`verify:action-pins — OK (${jobs} credentialed job(s) across ${files.length} workflows, every action SHA-pinned)`,
250+
);
251+
return 0;
252+
}
253+
254+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
255+
process.exit(main());

0 commit comments

Comments
 (0)