-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathcontainer-vulnerability-pr-report.yml
More file actions
302 lines (271 loc) · 12.1 KB
/
Copy pathcontainer-vulnerability-pr-report.yml
File metadata and controls
302 lines (271 loc) · 12.1 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
name: "[Core] Container Vulnerability PR Report"
# Runs with PR write permission only after the unprivileged Core CI workflow
# completes. Never check out or execute PR code here; scan artifacts are treated
# as bounded, untrusted JSON data.
on:
workflow_run:
# Workflow names are glob patterns, so literal brackets must be escaped.
# https://github.com/github/docs/issues/12572#issuecomment-1014035978
workflows: ['\[Core\] CI']
types: [completed]
permissions:
actions: read
contents: read
pull-requests: write
concurrency:
group: >-
container-vulnerability-pr-report-${{ github.event.workflow_run.head_repository.id }}-${{ github.event.workflow_run.head_branch }}
cancel-in-progress: true
jobs:
report:
name: "💬 Report container vulnerabilities"
if: ${{ github.event.workflow_run.event == 'pull_request' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Resolve pull request and reports
id: report-context
uses: actions/github-script@v9
with:
script: |
const run = context.payload.workflow_run;
let pullRequest;
const payloadPrNumber = run.pull_requests?.[0]?.number;
if (Number.isSafeInteger(payloadPrNumber)) {
const response = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: payloadPrNumber,
});
pullRequest = response.data;
} else {
const headOwner = run.head_repository?.owner?.login;
if (headOwner && run.head_branch) {
const response = await github.rest.pulls.list({
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
head: `${headOwner}:${run.head_branch}`,
per_page: 100,
});
pullRequest = response.data.find(candidate =>
candidate.head.repo?.full_name === run.head_repository.full_name
&& candidate.head.ref === run.head_branch
);
}
}
if (!pullRequest) {
core.notice(`No open pull request found for workflow run ${run.id}`);
return;
}
const recentRuns = await github.rest.actions.listWorkflowRuns({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: run.workflow_id,
event: 'pull_request',
per_page: 100,
});
const newerRun = recentRuns.data.workflow_runs.find(candidate =>
candidate.id !== run.id
&& candidate.head_repository?.id === run.head_repository?.id
&& candidate.head_branch === run.head_branch
&& (
Date.parse(candidate.created_at) > Date.parse(run.created_at)
|| (
candidate.created_at === run.created_at
&& candidate.id > run.id
)
)
);
if (newerRun) {
core.notice(`Skipping stale run ${run.id}; run ${newerRun.id} is newer`);
return;
}
const artifacts = await github.paginate(
github.rest.actions.listWorkflowRunArtifacts,
{
owner: context.repo.owner,
repo: context.repo.repo,
run_id: run.id,
per_page: 100,
},
);
const maxArchiveBytes = 20 * 1024 * 1024;
function findReport(name) {
const artifact = artifacts.find(candidate =>
candidate.name === name && !candidate.expired
);
if (artifact && artifact.size_in_bytes > maxArchiveBytes) {
core.warning(`${name} exceeds the 20 MiB archive limit`);
return undefined;
}
return artifact;
}
const standard = findReport('container-vulnerability-report-standard');
const ubi9 = findReport('container-vulnerability-report-ubi9');
core.setOutput('pr-number', String(pullRequest.number));
core.setOutput('standard-artifact-id', standard ? String(standard.id) : '');
core.setOutput('ubi9-artifact-id', ubi9 ? String(ubi9.id) : '');
- name: Download standard vulnerability report
if: ${{ steps.report-context.outputs.standard-artifact-id != '' }}
uses: actions/download-artifact@v8
with:
artifact-ids: ${{ steps.report-context.outputs.standard-artifact-id }}
path: ${{ runner.temp }}/container-vulnerability-reports/standard
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Download UBI9 vulnerability report
if: ${{ steps.report-context.outputs.ubi9-artifact-id != '' }}
uses: actions/download-artifact@v8
with:
artifact-ids: ${{ steps.report-context.outputs.ubi9-artifact-id }}
path: ${{ runner.temp }}/container-vulnerability-reports/ubi9
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Update pull request report
if: ${{ always() && steps.report-context.outputs.pr-number != '' }}
uses: actions/github-script@v9
env:
PR_NUMBER: ${{ steps.report-context.outputs.pr-number }}
REPORT_ROOT: ${{ runner.temp }}/container-vulnerability-reports
STANDARD_ARTIFACT_ID: ${{ steps.report-context.outputs.standard-artifact-id }}
UBI9_ARTIFACT_ID: ${{ steps.report-context.outputs.ubi9-artifact-id }}
with:
script: |
const fs = require('fs');
const path = require('path');
const marker = '<!-- openaev-container-vulnerability-report -->';
const maxReportBytes = 25 * 1024 * 1024;
const pullNumber = Number(process.env.PR_NUMBER);
if (!Number.isSafeInteger(pullNumber) || pullNumber < 1) {
throw new Error(`Invalid pull request number: ${process.env.PR_NUMBER}`);
}
function readReport(label, directory, fileName, artifactId) {
if (!/^\d+$/.test(artifactId)) {
return { label, state: 'unavailable', critical: 0, high: 0, total: 0 };
}
const reportPath = path.join(process.env.REPORT_ROOT, directory, fileName);
if (!fs.existsSync(reportPath)) {
core.warning(`${label} report artifact was not downloaded`);
return { label, state: 'unavailable', critical: 0, high: 0, total: 0 };
}
try {
const reportSize = fs.statSync(reportPath).size;
if (reportSize > maxReportBytes) {
throw new Error('report exceeds the 25 MiB JSON limit');
}
const report = JSON.parse(fs.readFileSync(reportPath, 'utf8'));
const results = report.Results == null ? [] : report.Results;
if (!Array.isArray(results)) {
throw new Error('report does not contain a Results array');
}
let critical = 0;
let high = 0;
let total = 0;
for (const result of results) {
if (!Array.isArray(result?.Vulnerabilities)) continue;
for (const vulnerability of result.Vulnerabilities) {
total += 1;
switch (String(vulnerability?.Severity || '').toUpperCase()) {
case 'CRITICAL': critical += 1; break;
case 'HIGH': high += 1; break;
default: break;
}
}
}
return { label, state: 'available', artifactId, critical, high, total };
} catch (error) {
core.warning(`${label} report could not be read: ${error.message}`);
return { label, state: 'invalid', artifactId, critical: 0, high: 0, total: 0 };
}
}
const reports = [
readReport(
'Standard',
'standard',
'container-vulnerability-standard.json',
process.env.STANDARD_ARTIFACT_ID || '',
),
readReport(
'UBI9',
'ubi9',
'container-vulnerability-ubi9.json',
process.env.UBI9_ARTIFACT_ID || '',
),
];
const comments = await github.paginate(github.rest.issues.listComments, {
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pullNumber,
per_page: 100,
});
const existing = comments.find(comment =>
comment.user?.type === 'Bot'
&& comment.body?.includes(marker)
);
const findingCount = reports.reduce((sum, report) => sum + report.total, 0);
const complete = reports.every(report => report.state === 'available');
if (complete && findingCount === 0 && !existing) {
core.info('No vulnerabilities found; no PR comment is needed');
return;
}
let heading;
let explanation;
if (findingCount > 0) {
heading = `⚠️ **Container vulnerability scan** — ${findingCount} finding${findingCount === 1 ? '' : 's'}`;
explanation = 'Core CI reports these findings in advisory mode. Review the JSON reports before merging.';
} else if (complete) {
heading = '✅ **Container vulnerability scan** — Passed';
explanation = 'Previously reported findings are no longer present.';
} else {
heading = '❔ **Container vulnerability scan** — Report incomplete';
explanation = 'The latest run did not produce both readable reports. Check the workflow run for details.';
}
function status(report) {
if (report.state === 'unavailable') return '❔ Unavailable';
if (report.state === 'invalid') return '❌ Invalid report';
return report.total > 0 ? '⚠️ Findings' : '✅ Clear';
}
function value(report, key) {
return report.state === 'available' ? String(report[key]) : '—';
}
const rows = reports.map(report =>
`| ${report.label} | ${value(report, 'critical')} | ${value(report, 'high')} | ${value(report, 'total')} | ${status(report)} |`
);
const run = context.payload.workflow_run;
const links = [`[View workflow run](${run.html_url})`];
for (const report of reports) {
if (/^\d+$/.test(report.artifactId || '')) {
links.push(
`[${report.label} JSON report](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${run.id}/artifacts/${report.artifactId})`,
);
}
}
const body = [
marker,
heading,
'',
explanation,
'',
'| Image | Critical | High | Total | Status |',
'|---|---:|---:|---:|---|',
...rows,
'',
links.join(' · '),
'',
`<sub>Updated from CI run attempt ${run.run_attempt}.</sub>`,
].join('\n');
const params = { owner: context.repo.owner, repo: context.repo.repo };
if (existing) {
await github.rest.issues.updateComment({
...params,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
...params,
issue_number: pullNumber,
body,
});
}