forked from anchore/scan-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
335 lines (295 loc) · 9.19 KB
/
index.js
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
const cache = require("@actions/tool-cache");
const core = require("@actions/core");
const exec = require("@actions/exec");
const fs = require("fs");
const path = require("path");
const stream = require("stream");
const { GRYPE_VERSION } = require("./GrypeVersion");
const exeSuffix = process.platform == "win32" ? ".exe" : "";
const grypeBinary = "grype" + exeSuffix;
const grypeVersion = core.getInput("grype-version") || GRYPE_VERSION;
async function downloadGrypeWindowsWorkaround(version) {
const versionNoV = version.replace(/^v/, "");
// example URL: https://github.com/anchore/grype/releases/download/v0.79.2/grype_0.79.2_windows_amd64.zip
const url = `https://github.com/anchore/grype/releases/download/${version}/grype_${versionNoV}_windows_amd64.zip`;
core.info(`Downloading grype from ${url}`);
const zipPath = await cache.downloadTool(url);
core.debug(`Zip saved to ${zipPath}`);
const toolDir = await cache.extractZip(zipPath);
core.debug(`Zip extracted to ${toolDir}`);
core.debug(`Grype path is ${path.join(toolDir, grypeBinary)}`);
return path.join(toolDir, grypeBinary);
}
function isWindows() {
return process.platform == "win32";
}
async function downloadGrype(version) {
let url = `https://raw.githubusercontent.com/anchore/grype/main/install.sh`;
core.debug(`Installing ${version}`);
if (isWindows()) {
// caller expects directory to add to path and join with executable name
const exeFilePath = await downloadGrypeWindowsWorkaround(version);
core.debug(`Grype saved to ${exeFilePath}`);
return path.dirname(exeFilePath);
}
// TODO: when grype starts supporting unreleased versions, support it here
// Download the installer, and run
const installPath = await cache.downloadTool(url);
let cmd = `sh ${installPath} -d -b ${installPath}_grype ${version}`;
await exec.exec(cmd);
let grypePath = `${installPath}_grype/${grypeBinary}`;
// Cache the downloaded file
return cache.cacheFile(grypePath, grypeBinary, grypeBinary, version);
}
async function installGrype(version) {
let grypePath = cache.find(grypeBinary, version);
if (!grypePath) {
// Not found, install it
grypePath = await downloadGrype(version);
}
// Add tool to path for this and future actions to use
core.addPath(grypePath);
return `${grypePath}/${grypeBinary}`;
}
// Determines if multiple arguments are defined
function multipleDefined(...args) {
let defined = false;
for (const a of args) {
if (defined && a) {
return true;
}
if (a) {
defined = true;
}
}
return false;
}
function sourceInput() {
var image = core.getInput("image");
var path = core.getInput("path");
var sbom = core.getInput("sbom");
if (multipleDefined(image, path, sbom)) {
throw new Error(
"The following options are mutually exclusive: image, path, sbom",
);
}
if (image) {
return image;
}
if (sbom) {
return "sbom:" + sbom;
}
if (!path) {
// Default to the CWD
path = ".";
}
return "dir:" + path;
}
async function run() {
try {
core.debug(new Date().toTimeString());
// Grype accepts several input options, initially this action is supporting both `image` and `path`, so
// a check must happen to ensure one is selected at least, and then return it
const source = sourceInput();
const failBuild = core.getInput("fail-build") || "true";
const outputFormat = core.getInput("output-format") || "sarif";
const severityCutoff = core.getInput("severity-cutoff") || "medium";
const onlyFixed = core.getInput("only-fixed") || "false";
const addCpesIfNone = core.getInput("add-cpes-if-none") || "false";
const byCve = core.getInput("by-cve") || "false";
const vex = core.getInput("vex") || "";
const out = await runScan({
source,
failBuild,
severityCutoff,
onlyFixed,
outputFormat,
addCpesIfNone,
byCve,
vex,
});
Object.keys(out).map((key) => {
core.setOutput(key, out[key]);
});
} catch (error) {
core.setFailed(error.message);
}
}
async function runScan({
source,
failBuild,
severityCutoff,
onlyFixed,
outputFormat,
addCpesIfNone,
byCve,
vex,
}) {
const out = {};
const env = {
...process.env,
GRYPE_CHECK_FOR_APP_UPDATE: "false",
};
const registryUser = core.getInput("registry-username");
const registryPass = core.getInput("registry-password");
if (registryUser || registryPass) {
env.GRYPE_REGISTRY_AUTH_USERNAME = registryUser;
env.GRYPE_REGISTRY_AUTH_PASSWORD = registryPass;
if (!registryUser || !registryPass) {
core.warning(
"WARNING: registry-username and registry-password must be specified together",
);
}
}
const SEVERITY_LIST = ["negligible", "low", "medium", "high", "critical"];
const FORMAT_LIST = ["sarif", "json", "table"];
let cmdArgs = [];
if (core.isDebug()) {
cmdArgs.push(`-vv`);
}
failBuild = failBuild.toLowerCase() === "true";
onlyFixed = onlyFixed.toLowerCase() === "true";
addCpesIfNone = addCpesIfNone.toLowerCase() === "true";
byCve = byCve.toLowerCase() === "true";
cmdArgs.push("-o", outputFormat);
if (
!SEVERITY_LIST.some(
(item) =>
typeof severityCutoff.toLowerCase() === "string" &&
item === severityCutoff.toLowerCase(),
)
) {
throw new Error(
`Invalid severity-cutoff value is set to ${severityCutoff} - please ensure you are choosing either negligible, low, medium, high, or critical`,
);
}
if (
!FORMAT_LIST.some(
(item) =>
typeof outputFormat.toLowerCase() === "string" &&
item === outputFormat.toLowerCase(),
)
) {
throw new Error(
`Invalid output-format value is set to ${outputFormat} - please ensure you are choosing either json or sarif`,
);
}
core.debug(`Installing grype version ${grypeVersion}`);
await installGrype(grypeVersion);
core.debug("Source: " + source);
core.debug("Fail Build: " + failBuild);
core.debug("Severity Cutoff: " + severityCutoff);
core.debug("Only Fixed: " + onlyFixed);
core.debug("Add Missing CPEs: " + addCpesIfNone);
core.debug("Orient by CVE: " + byCve);
core.debug("Output Format: " + outputFormat);
core.debug("Creating options for GRYPE analyzer");
// Run the grype analyzer
let cmdOutput = "";
let cmd = `${grypeBinary}`;
if (severityCutoff !== "") {
cmdArgs.push("--fail-on");
cmdArgs.push(severityCutoff.toLowerCase());
}
if (onlyFixed === true) {
cmdArgs.push("--only-fixed");
}
if (addCpesIfNone === true) {
cmdArgs.push("--add-cpes-if-none");
}
if (byCve === true) {
cmdArgs.push("--by-cve");
}
if (vex) {
cmdArgs.push("--vex");
cmdArgs.push(vex);
}
cmdArgs.push(source);
// This /dev/null writable stream is required so the entire Grype output
// is not written to the GitHub action log. the listener below
// will actually capture the output
const outStream = new stream.Writable({
write(buffer, encoding, next) {
next();
},
});
const exitCode = await core.group(`${cmd} output...`, async () => {
core.info(`Executing: ${cmd} ` + cmdArgs.join(" "));
return exec.exec(cmd, cmdArgs, {
env,
ignoreReturnCode: true,
outStream,
listeners: {
stdout(buffer) {
cmdOutput += buffer.toString();
},
stderr(buffer) {
core.info(buffer.toString());
},
debug(message) {
core.debug(message);
},
},
});
});
if (core.isDebug()) {
core.debug("Grype output:");
core.debug(cmdOutput);
}
switch (outputFormat) {
case "sarif": {
const SARIF_FILE = "./results.sarif";
fs.writeFileSync(SARIF_FILE, cmdOutput);
out.sarif = SARIF_FILE;
break;
}
case "json": {
const REPORT_FILE = "./results.json";
fs.writeFileSync(REPORT_FILE, cmdOutput);
out.json = REPORT_FILE;
break;
}
default: // e.g. table
core.info(cmdOutput);
}
// If there is a non-zero exit status code there are a couple of potential reporting paths
if (exitCode > 0) {
if (!severityCutoff) {
// There was a non-zero exit status but it wasn't because of failing severity, this must be
// a grype problem
core.warning("grype had a non-zero exit status when running");
} else if (failBuild === true) {
core.setFailed(
`Failed minimum severity level. Found vulnerabilities with level '${severityCutoff}' or higher`,
);
} else {
// There is a non-zero exit status code with severity cut off, although there is still a chance this is grype
// that is broken, it will most probably be a failed severity. Using warning here will make it bubble up in the
// Actions UI
core.warning(
`Failed minimum severity level. Found vulnerabilities with level '${severityCutoff}' or higher`,
);
}
}
return out;
}
module.exports = {
run,
runScan,
installGrype,
};
if (require.main === module) {
const entrypoint = core.getInput("run");
switch (entrypoint) {
case "download-grype": {
installGrype(grypeVersion).then((path) => {
core.info(`Downloaded Grype to: ${path}`);
core.setOutput("cmd", path);
});
break;
}
default: {
run().then();
}
}
}