Skip to content

Commit e82b652

Browse files
authored
Pin GitHub Actions to full-length commit SHAs (#998)
## Summary This PR pins GitHub Actions to full-length commit SHAs for improved security and reproducibility and adds a 7 day cooldown to Dependabot configuration for GitHub Actions. This work is described in more detail at https://aka.ms/action-pinning. ## Why? Pinning actions to commit SHAs prevents supply-chain attacks where a tag could be moved to point to malicious code. This is a recommended security best practice per the [GitHub Actions security hardening guide](https://docs.github.com/en/actions/security-for-github-actions/security-guides/security-hardening-for-github-actions#using-third-party-actions). This change mitigates the risk of tag retargeting to malicious code as seen in incidents like the [tj-actions/changed-files action compromise](https://www.stepsecurity.io/blog/harden-runner-detection-tj-actions-changed-files-action-is-compromised) or [codfish/semantic-release-action compromise](https://www.stepsecurity.io/blog/supply-chain-compromise-codfish-semantic-release-action) and improves the integrity and reproducibility of the CI/CD pipeline. ## What changed? **Action pinning:** Third-party action references in `.github/workflows/` that used mutable tag-based references (e.g., `actions/checkout@v4`) have been updated to full-length commit SHAs with a version comment (e.g., `actions/checkout@<sha> # v4`) using the [pinact](https://github.com/suzuki-shunsuke/pinact) tool. References that were already pinned to a SHA, or that used immutable release tags, were left unchanged. **Dependabot configuration:** `.github/dependabot.yml` has been updated to ensure a `github-actions` package-ecosystem section is present with a `cooldown` configuration (`default-days: 7`). If the file did not exist, it was created. If a `github-actions` section already existed, only the `cooldown` block was added or its `default-days` value was increased to 7 if it was lower. The 7-day cooldown provides a window for the community to detect and report compromised releases before they are automatically proposed as updates, reducing exposure to supply-chain attacks via newly published malicious versions. ## Is this safe to merge? Yes. The pinned SHAs correspond to the same commits that the existing tags pointed to. No behavioral changes in action execution are introduced. You can verify the pinned SHA value using the GitHub REST API (e.g., the commit hash for `actions/checkout@v7` can be found in the `sha` property in the JSON response for `GET https://api.github.com/repos/actions/checkout/commits/v7`). ## Additional Information For more information, please see https://aka.ms/action-pinning
2 parents eb700bc + 372cda2 commit e82b652

12 files changed

Lines changed: 314 additions & 89 deletions

‎.github/pin-github-actions-shas.js‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
#!/usr/bin/env node
2+
3+
const { execFileSync } = require('node:child_process');
4+
const fs = require('node:fs');
5+
6+
const pinningMessage = `ci: pin GitHub Actions to satisfy downstream policy
7+
8+
Microsoft Git inherits workflows that upstream maintains using symbolic
9+
Action refs. Downstream organizational policy requires full commit IDs
10+
instead, adding pin maintenance to this project's maintainers' workload.
11+
12+
Keep pins aligned with the original upstream Action refs in a fresh
13+
downstream snapshot, independent of any earlier pinning commit.
14+
`;
15+
16+
function git(...args) {
17+
return execFileSync('git', ['--no-pager', ...args], {
18+
encoding: 'utf8',
19+
stdio: ['ignore', 'pipe', 'pipe'],
20+
maxBuffer: 16 * 1024 * 1024
21+
}).trim();
22+
}
23+
24+
const isSHA = value => /^[0-9a-f]{40}$/i.test(value);
25+
const uses = /^( *-? *uses: *)(["']?)([\w./-]+)@([^ \t"'\r\n]+)\2([^\r\n]*)/gm;
26+
const useLine = new RegExp(uses.source);
27+
28+
function findOriginalActionRef(file, actionName, workflowHistory) {
29+
for (const patch of workflowHistory.split('\0')) {
30+
const removed = patch.replace(/^-/gm, '');
31+
const versions = [...removed.matchAll(uses)]
32+
.filter(use => use[3] === actionName &&
33+
!isSHA(use[4]))
34+
.map(use => use[4]);
35+
if (!versions.length)
36+
continue;
37+
const [version] = versions;
38+
if (versions.some(candidate => candidate !== version))
39+
throw new Error('Ambiguous Action ref: ' +
40+
`${file}, ${actionName}`);
41+
return version;
42+
}
43+
throw new Error(`Cannot recover Action ref: ${file}, ${actionName}`);
44+
}
45+
46+
function readWorkflow(file) {
47+
const text = fs.readFileSync(file, 'utf8');
48+
const parts = text.split(/(^ *-? *uses:[^\r\n]*)/m);
49+
const matches = parts.map(part => part.match(useLine))
50+
.filter(use => use && !use[3].startsWith('./'));
51+
const workflowHistory = matches.some(use => isSHA(use[4]))
52+
? git('log', '--follow', '-p', '-U0',
53+
'-Guses:.*@', '--no-ext-diff', '--no-textconv',
54+
'--format=%x00', '--', file)
55+
: '';
56+
const actionRefs = matches.map(use => {
57+
const actionName = use[3];
58+
const version = isSHA(use[4]) ?
59+
findOriginalActionRef(
60+
file, actionName, workflowHistory) :
61+
use[4];
62+
const actionRepo = actionName.split('/').slice(0, 2).join('/');
63+
return {
64+
use, actionName, version,
65+
pinKey: `${actionRepo}@${version}`
66+
};
67+
});
68+
return { file, text, parts, actionRefs };
69+
}
70+
71+
function resolveActionSHA(actionName, version) {
72+
const actionRepo = actionName.split('/').slice(0, 2).join('/');
73+
const actionTagRef = `refs/tags/${version}`;
74+
const output = git('ls-remote', '--quiet',
75+
`https://github.com/${actionRepo}`,
76+
actionTagRef, `${actionTagRef}^{}`, `refs/heads/${version}`);
77+
const actionRepoRefs = Object.fromEntries(output.split('\n')
78+
.map(line => line.split('\t').reverse()));
79+
const sha = actionRepoRefs[`${actionTagRef}^{}`] ||
80+
actionRepoRefs[actionTagRef] ||
81+
actionRepoRefs[`refs/heads/${version}`];
82+
if (!sha || !isSHA(sha))
83+
throw new Error('Cannot resolve Action ref: ' +
84+
`${actionName}@${version}`);
85+
return sha;
86+
}
87+
88+
function substitute({ file, text, parts, actionRefs }, pins) {
89+
const replacements = new Map(actionRefs.map(actionRef => {
90+
const { use, version, pinKey } = actionRef;
91+
const [, prefix, quote, actionName, , suffix] = use;
92+
const sha = pins[pinKey];
93+
let note = suffix.trim().replace(/^#\s*/, '');
94+
if (note.startsWith(`${version}; `))
95+
note = note.slice(version.length + 2);
96+
else if (note === version || /^v?\d[\w.+-]*$/.test(note))
97+
note = '';
98+
const pinned = `${prefix}${quote}${actionName}@${sha}${quote}` +
99+
` # ${version}` + (note ? `; ${note}` : '');
100+
return [use[0], pinned];
101+
}));
102+
const updated = parts.map(part => replacements.get(part) ?? part)
103+
.join('');
104+
return updated === text ? null : [file, updated];
105+
}
106+
107+
try {
108+
process.chdir(git('rev-parse', '--show-toplevel'));
109+
const files = git('ls-files', '-z', '--', '.github/workflows')
110+
.split('\0').filter(file => /\.ya?ml$/.test(file));
111+
if (git('status', '--porcelain', '--untracked-files=no',
112+
'--', '.github/workflows'))
113+
throw new Error('Workflow files have uncommitted changes');
114+
const workflows = files.map(readWorkflow);
115+
const actionRefs = workflows.flatMap(workflow => workflow.actionRefs);
116+
const uniquePins = new Map(actionRefs.map(actionRef =>
117+
[actionRef.pinKey, actionRef]));
118+
const pins = Object.fromEntries([...uniquePins.values()].map(
119+
({ pinKey, actionName, version }) =>
120+
[pinKey, resolveActionSHA(actionName, version)]));
121+
const changed = workflows.map(workflow => substitute(workflow, pins))
122+
.filter(Boolean);
123+
if (changed.length) {
124+
const message = git('rev-parse', '--git-path',
125+
'COMMIT_EDITMSG');
126+
fs.writeFileSync(message, pinningMessage);
127+
for (const [file, text] of changed)
128+
fs.writeFileSync(file, text);
129+
console.log(git('commit', '--signoff', '-F', message,
130+
'--', ...changed.map(([file]) => file)));
131+
} else {
132+
console.log('Action pins are up to date.');
133+
}
134+
} catch (error) {
135+
console.error(`error: ${error.message}`);
136+
process.exitCode = 1;
137+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
const assert = require('node:assert/strict');
2+
const { execFileSync } = require('node:child_process');
3+
const fs = require('node:fs');
4+
const os = require('node:os');
5+
const path = require('node:path');
6+
const { test } = require('node:test');
7+
const { pathToFileURL } = require('node:url');
8+
9+
test('fresh pinning commits preserve unrelated work', t => {
10+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'pin test-'));
11+
t.after(() => fs.rmSync(directory, { recursive: true }));
12+
const env = Object.fromEntries(Object.entries(process.env)
13+
.filter(([key]) => !/^GIT_/i.test(key)));
14+
env.GIT_CONFIG_NOSYSTEM = '1';
15+
env.GIT_CONFIG_GLOBAL = os.devNull;
16+
const git = (...args) => execFileSync('git', args, {
17+
cwd: directory, env, encoding: 'utf8',
18+
stdio: ['ignore', 'pipe', 'pipe']
19+
}).trim();
20+
git('init', '-q', '--initial-branch=test', '--object-format=sha1');
21+
git('config', 'user.name', 'Pin Test');
22+
git('config', 'user.email', 'pins@example.com');
23+
const workflows = path.join(directory, '.github/workflows');
24+
fs.mkdirSync(workflows, { recursive: true });
25+
const file = path.join(workflows, 'main.yml');
26+
const write = text => fs.writeFileSync(file, text);
27+
const read = () => fs.readFileSync(file, 'utf8');
28+
const run = () => execFileSync(process.execPath,
29+
[path.join(__dirname, 'pin-github-actions-shas.js')],
30+
{ cwd: directory, env, stdio: ['ignore', 'pipe', 'pipe'] });
31+
const workflow = `on: push
32+
jobs:
33+
test:
34+
runs-on: ubuntu-latest
35+
steps:
36+
- uses: 'example/action@v1'
37+
- uses: example/action/subpath@v2
38+
if: false
39+
- uses: ./local-action
40+
reusable:
41+
uses: example/action/.github/workflows/test.yaml@master
42+
`.replace(/\n/g, '\r\n');
43+
write(workflow);
44+
const another = path.join(workflows, 'another.yaml');
45+
fs.writeFileSync(another, workflow.replace('@v1', '@v2'));
46+
const unrelated = path.join(directory, 'unrelated');
47+
fs.writeFileSync(unrelated, 'original\n');
48+
git('add', '--', '.github/workflows', 'unrelated');
49+
git('commit', '-qm', 'Upstream workflows');
50+
const first = git('rev-parse', 'HEAD');
51+
git('tag', 'v1');
52+
git('tag', '-am', 'Annotated version', 'v2');
53+
git('commit', '--allow-empty', '-qm', 'Update action');
54+
const second = git('rev-parse', 'HEAD');
55+
const pinned = v1 => workflow
56+
.replace(/@v1'/, `@${v1}' # v1`)
57+
.replace('@v2', `@${first} # v2`)
58+
.replace('@master', `@${second} # master`);
59+
git('branch', 'master');
60+
git('branch', 'v1');
61+
git('config', `url.${pathToFileURL(directory).href}.insteadOf`,
62+
'https://github.com/example/action');
63+
fs.writeFileSync(unrelated, 'staged change\n');
64+
git('add', '--', 'unrelated');
65+
const expectedSubject =
66+
'ci: pin GitHub Actions to satisfy downstream policy';
67+
run();
68+
assert.equal(git('log', '-1', '--format=%s'), expectedSubject);
69+
assert.equal(git('rev-parse', 'HEAD^'), second);
70+
assert.equal(read(), pinned(first));
71+
assert.match(git('log', '-1', '--format=%B'),
72+
/Signed-off-by: Pin Test <pins@example.com>/);
73+
write(read().replace(/# v[12]/g, '# v0.0.0'));
74+
git('commit', '-qm', 'Release labels', '--', '.github/workflows');
75+
git('tag', '-f', 'v1', second);
76+
const beforeRefresh = git('rev-parse', 'HEAD');
77+
run();
78+
assert.equal(git('log', '-1', '--format=%s'), expectedSubject);
79+
assert.equal(git('rev-parse', 'HEAD^'), beforeRefresh);
80+
assert.equal(read(), pinned(second));
81+
assert.equal(fs.readFileSync(another, 'utf8'),
82+
pinned(first).replace('# v1', '# v2'));
83+
const head = git('rev-parse', 'HEAD');
84+
run();
85+
assert.equal(git('rev-parse', 'HEAD'), head);
86+
assert.equal(git('diff', '--cached', '--name-only'), 'unrelated');
87+
assert.equal(git('show', 'HEAD:unrelated'), 'original');
88+
});

0 commit comments

Comments
 (0)