-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
479 lines (391 loc) · 12.5 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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
const { spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
const { parse, stringify } = require("@yarnpkg/lockfile");
const yaml = require("js-yaml");
const { argv } = require("yargs");
const LARGE_BUFFER = 1024 * 1024 * 1024 * 20;
const DEFAULT_RETRIES = 2;
let MAX_RETRIES;
let PRESERVE_INTEGRITY = false;
const catchAndRetry = async (fn) => {
for (let retries = 0; retries < MAX_RETRIES; retries++) {
try {
return await fn();
} catch (e) {
console.log("An error was thrown while executing the previous command.");
console.error(e);
}
if (retries < MAX_RETRIES - 1) {
console.log("Retrying...");
}
}
console.log("Exiting...");
process.exit(1);
};
const exec = (command, args = [], overrideOptions = {}) => {
let stdout = "";
let stderr = "";
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
stdio: "pipe",
encoding: "utf8",
maxBuffer: LARGE_BUFFER,
...overrideOptions,
});
if (child.stdout) {
child.stdout.on("data", (data) => (stdout = `${stdout}${data}`));
}
if (child.stderr) {
child.stderr.on("data", (data) => (stderr = `${stderr}${data}`));
}
child.on("error", (error) => reject({ error }));
child.on("close", (code) => resolve({ code, stdout, stderr }));
});
};
const toVersionless = (str) => str.replace(/(.*)\@.*/, "$1");
const toDependencies = (
currentDependencies,
{ from: [_, ...dependencies] },
) => [...currentDependencies, ...dependencies.map(toVersionless)];
const unique = (arr) => Array.from(new Set([...arr]));
const yarnInstall = async ({ force = false } = { force: false }) =>
await exec(
"yarn",
[
"install",
"--ignore-engines",
"--ignore-platform",
...(force ? ["--force"] : []),
],
{
stdio: "inherit",
},
);
const npmInstall = async ({ force = false } = { force: false }) =>
await exec("npm", ["install", ...(force ? ["--force"] : [])], {
stdio: "inherit",
});
/**
* updateYarnLock
*
* Updates a Yarn `yarn.lock` to resolve vulnerabilities with dependencies.
*
* @param { lockFileName, depsToForceUpdate } config The lockfile and dependencies to update.
*/
const updateYarnLock = async ({ lockFileName, depsToForceUpdate }) => {
console.log(
`[SNYKER: STEP 4]: Deleting vulnerable paths from '${lockFileName}' file.`,
);
const yarnLock = fs.readFileSync(lockFileName, "utf8");
const { object } = parse(yarnLock);
const updatedYarnLock = Object.entries(object).reduce(
(currentJson, [dependencyName, dependencyMetadata]) =>
depsToForceUpdate.includes(toVersionless(dependencyName))
? currentJson
: { ...currentJson, [dependencyName]: dependencyMetadata },
{},
);
fs.writeFileSync(lockFileName, stringify(updatedYarnLock));
console.log(
"[SNYKER: STEP 5]: Running 'yarn install --force' to force sub-dependency updates.\n",
);
const out = await yarnInstall({ force: true });
if (out.code !== 0) {
throw out;
}
};
/**
* In order to avoid the ~2018 EINTEGRITY error nightmare, we also force all deps
* installed prior to npm 5.0 to be updated.
*/
const shaPatch = ({ integrity, ...rest }) => ({
...rest,
...(!integrity || (integrity.startsWith("sha1-") && !PRESERVE_INTEGRITY)
? {}
: { integrity }),
});
/**
* updatePackageLock
*
* Updates a NPM `package-lock.json` to resolve vulnerabilities with dependencies.
*
* @param { lockFileName, depsToForceUpdate } config The lockfile and dependencies to update.
*/
const updatePackageLock = async ({ lockFileName, depsToForceUpdate }) => {
console.log(
`[SNYKER: STEP 4]: Deleting vulnerable paths from '${lockFileName}' file.`,
);
const packageLock = fs.readFileSync(lockFileName, "utf8");
const object = JSON.parse(packageLock);
const updatedPackageLock = {
...object,
packages: Object.entries(object.packages).reduce(
(currentJson, [dependencyName, dependencyMetadata]) =>
depsToForceUpdate.includes(toVersionless(dependencyName))
? currentJson
: { ...currentJson, [dependencyName]: shaPatch(dependencyMetadata) },
{},
),
};
fs.writeFileSync(
lockFileName,
JSON.stringify(updatedPackageLock, undefined, 2),
);
console.log(
"[SNYKER: STEP 5]: Running 'npm install' to force sub-dependency updates.\n",
);
const out = await npmInstall({ force: true });
if (out.code !== 0) {
throw out;
}
};
const created = new Date();
created.setUTCHours(0, 0, 0, 0);
const updateSnykPolicyWithIgnores = (vulnerabilityIds) => {
const snykPolicyFile = fs.existsSync(".snyk")
? fs.readFileSync(".snyk", "utf8")
: "ignore: {}\npatch: {}";
const policy = yaml.load(snykPolicyFile);
const expires = new Date(created.getTime() + 30 * 24 * 60 * 60 * 1000);
const updatedPolicy = {
...policy,
ignore: {
...policy.ignore,
...Object.fromEntries(
vulnerabilityIds.map((vulnerabilityId) => [
vulnerabilityId,
[
{
"*": {
// REF: https://github.com/snyk/cli/blob/main/src/cli/commands/ignore.ts#L59
reason: "None Given",
// REF: https://github.com/snyk/cli/blob/main/src/cli/commands/ignore.ts#L55
expires,
// REF: https://github.com/snyk/cli/blob/main/src/cli/commands/ignore.ts#L80
created,
},
},
],
]),
),
},
};
const updatedPolicyFile = yaml.dump(updatedPolicy);
fs.writeFileSync(".snyk", updatedPolicyFile);
};
const updateSnykPolicyPatches = (patchablePackages) => {
const snykPolicyFile = fs.existsSync(".snyk")
? fs.readFileSync(".snyk", "utf8")
: "ignore: {}\npatch: {}";
const policy = yaml.load(snykPolicyFile);
const updatedPolicy = {
...policy,
patch: patchablePackages.reduce(
(currentPatch, { id, from }) => ({
...currentPatch,
[id]: [
...(currentPatch[id] || []),
{
[from.slice(1).map(toVersionless).join(" > ")]: {
patched: new Date().toISOString(),
},
},
],
}),
{},
),
};
const updatedPolicyFile = yaml.dump(updatedPolicy);
fs.writeFileSync(".snyk", updatedPolicyFile);
};
const dynamicPolicyKeys = ["expires"];
const updateSnykPolicyWithPersistedVulnerabilityData = (originalPolicy) => {
const snykPolicyFile = fs.existsSync(".snyk")
? fs.readFileSync(".snyk", "utf8")
: "ignore: {}\npatch: {}";
const policy = yaml.load(snykPolicyFile);
const updatedPolicy = {
...policy,
ignore: Object.entries(policy.ignore).reduce(
(currentIgnore, [id, vulnerablePaths]) => {
const originalVulnerablePaths = originalPolicy.ignore[id] || [];
let originalMetadata = {};
if (originalVulnerablePaths.length && originalVulnerablePaths[0]["*"]) {
originalMetadata = Object.entries(
originalVulnerablePaths[0]["*"],
).reduce((metadata, [key, value]) => {
if (dynamicPolicyKeys.includes(key)) {
return metadata;
}
return {
...metadata,
[key]: value,
};
}, {});
}
return {
...currentIgnore,
[id]: [
{
"*": {
...vulnerablePaths[0]["*"],
...originalMetadata,
},
},
],
};
},
{},
),
};
const updatedPolicyFile = yaml.dump(updatedPolicy);
fs.writeFileSync(".snyk", updatedPolicyFile);
};
const snykAuthCheck = (snykPayload) =>
snykPayload.startsWith("MissingApiTokenError");
const snyker = async () => {
console.log("[SNYKER: STARTING]");
MAX_RETRIES = argv.retries || DEFAULT_RETRIES;
PRESERVE_INTEGRITY = argv["preserve-integrity"] || false;
// We need to determine whether we're using Yarn or NPM
// Prioritise "lockfile" flag, then check for yarn.lock, then package-lock.json
// If none of these files exist, default to yarn.lock
const lockFileName =
argv.lockfile ||
["yarn.lock", "package-lock.json"].find((file) =>
fs.existsSync(path.join(process.cwd(), file)),
) ||
"yarn.lock";
const isYarn = lockFileName === "yarn.lock";
console.log(
`[SNYKER: STEP 1]: Ensuring lockfile '${lockFileName}' is up to date.\n`,
);
await catchAndRetry(async () => {
const out = await (isYarn ? yarnInstall : npmInstall)({ force: true });
if (out.code !== 0) {
throw out;
}
});
console.log("\n[SNYKER: STEP 2]: Deleting '.snyk' file.");
/**
* We need to make sure that we persist any metadata about when vulnerabilities
* were first reported etc. so we cache the original policy file before removing
* it.
*/
const snykPolicyFile = fs.existsSync(".snyk")
? fs.readFileSync(".snyk", "utf8")
: "ignore: {}\npatch: {}";
const originalPolicy = yaml.load(snykPolicyFile);
try {
fs.unlinkSync(".snyk");
} catch (_) {}
console.log("[SNYKER: STEP 3]: Getting vulnerable paths from Snyk.");
const depsToForceUpdate = await catchAndRetry(async () => {
const { stdout: snykTestOut } = await exec("npx", [
"snyk",
"test",
"--dev",
"--json",
"--ignore-policy",
"--strict-out-of-sync=true",
`--file=${lockFileName}`,
"--prune-repeated-dependencies",
]);
if (snykAuthCheck(snykTestOut)) {
console.log(
"\nMissingApiTokenError: `snyk` requires an authenticated account. Please run `snyk auth` and try again.\n\nRestoring Original Snyk Policy.",
);
fs.writeFileSync(".snyk", yaml.dump(originalPolicy));
process.exit(1);
}
const { vulnerabilities, error } = JSON.parse(snykTestOut);
if (error) {
throw error;
}
return unique(vulnerabilities.reduce(toDependencies, []));
});
await catchAndRetry(
async () =>
await (isYarn ? updateYarnLock : updatePackageLock)({
lockFileName,
depsToForceUpdate,
}),
);
console.log(
"\n[SNYKER: STEP 6]: Getting remaining vulnerable paths from Snyk.",
);
const finalVulnerabilities = await catchAndRetry(async () => {
const { stdout: finalSnykTestOut } = await exec("npx", [
"snyk",
"test",
"--dev",
"--json",
"--ignore-policy",
"--strict-out-of-sync=true",
`--file=${lockFileName}`,
"--prune-repeated-dependencies",
]);
if (snykAuthCheck(finalSnykTestOut)) {
console.log(
"\nMissingApiTokenError: `snyk` requires an authenticated account. Please run `snyk auth` and try again.\n\nRestoring Original Snyk Policy.",
);
fs.writeFileSync(".snyk", yaml.dump(originalPolicy));
process.exit(1);
}
const { vulnerabilities: finalVulnerabilities, error } =
JSON.parse(finalSnykTestOut);
if (error) {
throw error;
}
return finalVulnerabilities;
});
if (finalVulnerabilities.length) {
const upgradablePackages = [];
const patchablePackages = [];
const vulnerabilityIds = [];
for (const {
id,
from,
isUpgradable,
isPatchable,
upgradePath,
} of finalVulnerabilities) {
vulnerabilityIds.push(id);
if (isUpgradable) {
upgradablePackages.push(upgradePath.filter(Boolean)[0]);
}
if (isPatchable) {
patchablePackages.push({ id, from });
}
}
console.log("[SNYKER: STEP 7]: Ignoring remaining vulnerabilities:\n");
const uniqueVulnerabilityIds = unique(vulnerabilityIds);
uniqueVulnerabilityIds.forEach((id) => console.log(`\t- ${id}`));
updateSnykPolicyWithIgnores(uniqueVulnerabilityIds);
// Intentional newline
console.log();
if (upgradablePackages.length) {
const installCommand = isYarn ? "yarn upgrade" : "npm install";
const upgradablePackagesStr = unique(upgradablePackages).reduce(
(str, upgradablePackage) => `${str} ${upgradablePackage}`,
"",
);
console.log(
`[SNYKER: RECOMMENDATION]: ${installCommand}${upgradablePackagesStr}`,
);
}
if (patchablePackages.length) {
console.log("[SNYKER: STEP 8]: Applying available patches:\n");
unique(patchablePackages.map(({ id }) => id)).forEach((id) =>
console.log(`\t- ${id}`),
);
// Intentional newline
console.log();
updateSnykPolicyPatches(patchablePackages);
}
}
updateSnykPolicyWithPersistedVulnerabilityData(originalPolicy);
console.log("[SNYKER: COMPLETE]");
};
module.exports = snyker;