-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathaction.yml
More file actions
402 lines (361 loc) · 14.7 KB
/
Copy pathaction.yml
File metadata and controls
402 lines (361 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
name: Verify SHA Pinning
description: >
Verifies that SHA-pinned GitHub Actions in workflow files match
the tag claimed in their version comment. Prevents supply chain
attacks where tags are force-pushed to malicious commits.
inputs:
github-token:
description: 'GitHub token for API calls to resolve tags and post PR comments'
required: true
workflow-dir:
description: 'Directory containing workflow files to scan'
required: false
default: '.github/workflows'
outputs:
verified-count:
description: 'Number of SHA-pinned actions verified'
value: ${{ steps.verify.outputs.verified_count }}
failed-count:
description: 'Number of mismatches found'
value: ${{ steps.verify.outputs.failed_count }}
status:
description: 'Overall result: pass or fail'
value: ${{ steps.verify.outputs.status }}
runs:
using: composite
steps:
- name: Verify SHA pins against upstream tags
id: verify
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
WORKFLOW_DIR: ${{ inputs.workflow-dir }}
with:
github-token: ${{ inputs.github-token }}
script: |
const fs = require('fs');
const path = require('path');
const workflowDir = process.env.WORKFLOW_DIR;
const tagShaCache = new Map();
const nonRetryableStatuses = new Set([400, 401, 403, 404, 422]);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function withRetries(operation, label, maxAttempts = 3) {
let lastErr;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await operation();
} catch (err) {
if (nonRetryableStatuses.has(err.status)) {
throw err;
}
lastErr = err;
if (attempt < maxAttempts) {
core.warning(`${label} failed on attempt ${attempt}/${maxAttempts}: ${err.message}; retrying`);
await sleep(250 * attempt);
}
}
}
throw lastErr;
}
// Find all workflow files
const files = fs.readdirSync(workflowDir)
.filter(f => f.endsWith('.yml') || f.endsWith('.yaml'))
.map(f => path.join(workflowDir, f));
if (files.length === 0) {
core.info('No workflow files found');
core.setOutput('verified_count', 0);
core.setOutput('failed_count', 0);
core.setOutput('status', 'pass');
core.setOutput('results_json', '[]');
return;
}
// Match: uses: owner/repo[/sub]@<40-char-sha> # <tag>
const pattern = /uses:\s*([^\/\s]+)\/([^@\/\s]+)(?:\/[^@\s]+)?@([a-f0-9]{40})\s*#\s*(v\S+)/g;
// Collect all pinned references
const refs = [];
for (const file of files) {
const content = fs.readFileSync(file, 'utf8');
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
let match;
pattern.lastIndex = 0;
while ((match = pattern.exec(lines[i])) !== null) {
refs.push({
file: path.basename(file),
line: i + 1,
owner: match[1],
repo: match[2],
pinnedSha: match[3],
tag: match[4],
});
}
}
}
if (refs.length === 0) {
core.info('No SHA-pinned actions found');
core.setOutput('verified_count', 0);
core.setOutput('failed_count', 0);
core.setOutput('status', 'pass');
core.setOutput('results_json', '[]');
return;
}
core.info(`Found ${refs.length} SHA-pinned action(s) to verify\n`);
// Resolve a tag to its commit SHA, handling annotated tags
async function resolveTagSha(owner, repo, tag) {
const cacheKey = `${owner}/${repo}@${tag}`;
if (tagShaCache.has(cacheKey)) {
return tagShaCache.get(cacheKey);
}
try {
const ref = await withRetries(
() => github.rest.git.getRef({
owner,
repo,
ref: `tags/${tag}`,
}),
`Resolving ${cacheKey}`
);
const obj = ref.data.object;
let sha;
// Lightweight tag — points directly to a commit
if (obj.type === 'commit') {
sha = obj.sha;
tagShaCache.set(cacheKey, sha);
return sha;
}
// Annotated tag — dereference to get the commit
if (obj.type === 'tag') {
const tagObj = await withRetries(
() => github.rest.git.getTag({
owner,
repo,
tag_sha: obj.sha,
}),
`Dereferencing ${cacheKey}`
);
sha = tagObj.data.object.sha;
tagShaCache.set(cacheKey, sha);
return sha;
}
throw new Error(`Unexpected ref object type: ${obj.type}`);
} catch (err) {
if (err.status === 404) {
throw new Error(`Tag "${tag}" not found in ${owner}/${repo}`);
}
throw err;
}
}
// Investigate a mismatched SHA: check if it exists in the repo and find matching tags
async function investigateMismatch(owner, repo, pinnedSha) {
const details = { existsInRepo: false, matchingTags: [] };
// Check if the pinned SHA exists in this repo at all
try {
await withRetries(
() => github.rest.repos.getCommit({ owner, repo, ref: pinnedSha }),
`Checking ${owner}/${repo}@${pinnedSha}`
);
details.existsInRepo = true;
} catch (err) {
details.existsInRepo = (err.status !== 404 && err.status !== 422);
}
// Find which tags (if any) point to this SHA
if (details.existsInRepo) {
try {
const tags = await withRetries(
() => github.paginate(github.rest.repos.listTags, {
owner, repo, per_page: 100,
}),
`Listing tags for ${owner}/${repo}`
);
details.matchingTags = tags
.filter(t => t.commit.sha === pinnedSha)
.map(t => t.name);
} catch {
// Non-fatal — we still have the existence check
}
}
return details;
}
let verified = 0;
let failed = 0;
const errors = [];
const results = [];
for (const ref of refs) {
const label = `${ref.owner}/${ref.repo}@${ref.tag}`;
try {
const resolvedSha = await resolveTagSha(ref.owner, ref.repo, ref.tag);
if (resolvedSha === ref.pinnedSha) {
core.info(`✅ ${label} — SHA verified (${ref.file}:${ref.line})`);
verified++;
results.push({
action: label, file: ref.file, line: ref.line,
status: 'verified',
});
} else {
const info = await investigateMismatch(ref.owner, ref.repo, ref.pinnedSha);
let msg = `❌ ${label} — SHA mismatch (${ref.file}:${ref.line})\n` +
` Pinned: ${ref.pinnedSha}\n` +
` Expected: ${resolvedSha}`;
let detail = '';
if (!info.existsInRepo) {
detail = `Pinned SHA does not exist in ${ref.owner}/${ref.repo} — possible fork or typosquat`;
msg += `\n ⚠️ ${detail}`;
} else if (info.matchingTags.length > 0) {
detail = `Pinned SHA corresponds to: ${info.matchingTags.join(', ')}`;
msg += `\n ℹ️ ${detail}`;
} else {
detail = 'Pinned SHA exists in repo but has no matching tags';
msg += `\n ℹ️ ${detail}`;
}
core.error(msg);
errors.push(msg);
failed++;
results.push({
action: label, file: ref.file, line: ref.line,
status: 'mismatch', pinnedSha: ref.pinnedSha,
expectedSha: resolvedSha, detail,
});
}
} catch (err) {
const detail = err.message;
const msg = `❌ ${label} — ${detail} (${ref.file}:${ref.line})`;
core.error(msg);
errors.push(msg);
failed++;
results.push({
action: label, file: ref.file, line: ref.line,
status: 'error', detail,
});
}
}
core.info(`\n${'─'.repeat(60)}`);
core.info(`Verified: ${verified} Failed: ${failed} Total: ${refs.length}`);
core.setOutput('verified_count', verified);
core.setOutput('failed_count', failed);
core.setOutput('status', failed > 0 ? 'fail' : 'pass');
core.setOutput('results_json', JSON.stringify(results));
if (failed > 0) {
core.setFailed(
`${failed} SHA-pinned action(s) failed verification:\n\n` +
errors.join('\n\n')
);
}
- name: Post or update PR comment
if: always() && github.event_name == 'pull_request'
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
RESULTS_JSON: ${{ steps.verify.outputs.results_json }}
VERIFIED_COUNT: ${{ steps.verify.outputs.verified_count }}
FAILED_COUNT: ${{ steps.verify.outputs.failed_count }}
STATUS: ${{ steps.verify.outputs.status }}
with:
github-token: ${{ inputs.github-token }}
script: |
const marker = '<!-- verify-sha-pinning -->';
const nonRetryableStatuses = new Set([400, 401, 403, 404, 422]);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function withRetries(operation, label, maxAttempts = 3) {
let lastErr;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await operation();
} catch (err) {
if (nonRetryableStatuses.has(err.status)) {
throw err;
}
lastErr = err;
if (attempt < maxAttempts) {
core.warning(`${label} failed on attempt ${attempt}/${maxAttempts}: ${err.message}; retrying`);
await sleep(250 * attempt);
}
}
}
throw lastErr;
}
const prNumber = context.issue.number;
if (!prNumber) {
core.info('Not a PR context — skipping comment');
return;
}
const results = JSON.parse(process.env.RESULTS_JSON || '[]');
const verified = parseInt(process.env.VERIFIED_COUNT || '0', 10);
const failed = parseInt(process.env.FAILED_COUNT || '0', 10);
const total = verified + failed;
const status = process.env.STATUS || 'pass';
// Find existing comment
const { data: comments } = await withRetries(
() => github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
}),
`Listing comments for PR #${prNumber}`
);
const existing = comments.find(c => c.body?.includes(marker));
let body;
if (status === 'fail') {
// Build failure table
const rows = results.map(r => {
const loc = `\`${r.file}:${r.line}\``;
if (r.status === 'verified') {
return `| \`${r.action}\` | ${loc} | ✅ Verified | |`;
} else {
return `| \`${r.action}\` | ${loc} | ❌ ${r.status === 'error' ? 'Error' : 'Mismatch'} | ${r.detail || ''} |`;
}
}).join('\n');
body = `${marker}
> [!WARNING]
> #### SHA Pin Verification Failed
>
> **${failed} of ${total}** SHA-pinned action(s) failed verification.
| Action | Location | Status | Details |
|--------|----------|--------|---------|
${rows}
See the [action run](${'https://github.com/' + context.repo.owner + '/' + context.repo.repo + '/actions/runs/' + context.runId}) for full details.`;
} else if (total === 0) {
// No SHA-pinned actions found — only update if there was a previous warning
if (!existing) return;
body = `${marker}
> [!NOTE]
> #### SHA Pin Verification — No Pins Found
>
> No SHA-pinned actions detected in workflow files.`;
} else {
// All passed — only post if updating a previous warning
if (!existing) {
core.info('All SHA pins verified — no previous comment to update');
return;
}
// Skip update if already showing success
if (existing.body?.includes('Passed ✅')) {
core.info('Comment already shows success — no update needed');
return;
}
body = `${marker}
> [!NOTE]
> #### SHA Pin Verification Passed ✅
>
> All **${total}** SHA-pinned action(s) verified against upstream tags.`;
}
if (existing) {
await withRetries(
() => github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
}),
`Updating comment #${existing.id}`
);
core.info(`Updated existing comment #${existing.id}`);
} else {
await withRetries(
() => github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body,
}),
`Creating comment for PR #${prNumber}`
);
core.info('Created new PR comment');
}