/
remediation-based-format-issues.ts
539 lines (496 loc) · 14.3 KB
/
remediation-based-format-issues.ts
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import chalk from 'chalk';
import * as config from '../../../../lib/config';
import { TestOptions } from '../../../../lib/types';
import {
DependencyPins,
DependencyUpdates,
GroupedVuln,
IssueData,
LegalInstruction,
PatchRemediation,
PinRemediation,
REACHABILITY,
RemediationChanges,
SEVERITY,
UpgradeRemediation,
} from '../../../../lib/snyk-test/legacy';
import { SEVERITIES } from '../../../../lib/snyk-test/common';
import { formatLegalInstructions } from './legal-license-instructions';
import {
formatReachability,
formatReachablePaths,
} from './format-reachability';
import {
BasicVulnInfo,
SampleReachablePaths,
UpgradesByAffectedPackage,
} from './types';
// How many reachable paths to show in the output
const MAX_REACHABLE_PATHS = 2;
export function formatIssuesWithRemediation(
vulns: GroupedVuln[],
remediationInfo: RemediationChanges,
options: TestOptions,
): string[] {
const basicVulnInfo: {
[name: string]: BasicVulnInfo;
} = {};
const basicLicenseInfo: {
[name: string]: BasicVulnInfo;
} = {};
for (const vuln of vulns) {
const allReachablePaths: SampleReachablePaths = { pathCount: 0, paths: [] };
for (const issue of vuln.list) {
const issueReachablePaths = issue.reachablePaths?.reachablePaths || [];
for (const functionReachablePaths of issueReachablePaths) {
allReachablePaths.paths = allReachablePaths.paths.concat(
functionReachablePaths.callPaths,
);
allReachablePaths.pathCount += functionReachablePaths.callPaths.length;
}
}
const vulnData = {
title: vuln.title,
severity: vuln.severity,
isNew: vuln.isNew,
name: vuln.name,
type: vuln.metadata.type,
version: vuln.version,
fixedIn: vuln.fixedIn,
note: vuln.note,
legalInstructions: vuln.legalInstructionsArray,
paths: vuln.list.map((v) => v.from),
reachability: vuln.reachability,
sampleReachablePaths: allReachablePaths,
};
if (vulnData.type === 'license') {
basicLicenseInfo[vuln.metadata.id] = vulnData;
} else {
basicVulnInfo[vuln.metadata.id] = vulnData;
}
}
const results = [''];
let upgradeTextArray: string[];
if (remediationInfo.pin && Object.keys(remediationInfo.pin).length) {
const upgradesByAffected: UpgradesByAffectedPackage = {};
for (const topLevelPkg of Object.keys(remediationInfo.upgrade)) {
for (const targetPkgStr of remediationInfo.upgrade[topLevelPkg]
.upgrades) {
if (!upgradesByAffected[targetPkgStr]) {
upgradesByAffected[targetPkgStr] = [];
}
upgradesByAffected[targetPkgStr].push({
name: topLevelPkg,
version: remediationInfo.upgrade[topLevelPkg].upgradeTo,
});
}
}
upgradeTextArray = constructPinText(
remediationInfo.pin,
upgradesByAffected,
basicVulnInfo,
options,
);
const allVulnIds = new Set();
Object.keys(remediationInfo.pin).forEach((name) =>
remediationInfo.pin[name].vulns.forEach((vid) => allVulnIds.add(vid)),
);
remediationInfo.unresolved = remediationInfo.unresolved.filter(
(issue) => !allVulnIds.has(issue.id),
);
} else {
upgradeTextArray = constructUpgradesText(
remediationInfo.upgrade,
basicVulnInfo,
options,
);
}
if (upgradeTextArray.length > 0) {
results.push(upgradeTextArray.join('\n'));
}
const patchedTextArray = constructPatchesText(
remediationInfo.patch,
basicVulnInfo,
options,
);
if (patchedTextArray.length > 0) {
results.push(patchedTextArray.join('\n'));
}
const unfixableIssuesTextArray = constructUnfixableText(
remediationInfo.unresolved,
basicVulnInfo,
options,
);
if (unfixableIssuesTextArray.length > 0) {
results.push(unfixableIssuesTextArray.join('\n'));
}
const licenseIssuesTextArray = constructLicenseText(
basicLicenseInfo,
options,
);
if (licenseIssuesTextArray.length > 0) {
results.push(licenseIssuesTextArray.join('\n'));
}
return results;
}
export function getSeverityValue(severity: SEVERITY): number {
return SEVERITIES.find((s) => s.verboseName === severity)!.value;
}
function constructLicenseText(
basicLicenseInfo: {
[name: string]: BasicVulnInfo;
},
testOptions: TestOptions,
): string[] {
if (!(Object.keys(basicLicenseInfo).length > 0)) {
return [];
}
const licenseTextArray = [chalk.bold.green('\nLicense issues:')];
for (const id of Object.keys(basicLicenseInfo)) {
const licenseText = formatIssue(
id,
basicLicenseInfo[id].title,
basicLicenseInfo[id].severity,
basicLicenseInfo[id].isNew,
`${basicLicenseInfo[id].name}@${basicLicenseInfo[id].version}`,
basicLicenseInfo[id].paths,
testOptions,
basicLicenseInfo[id].note,
basicLicenseInfo[id].legalInstructions,
);
licenseTextArray.push('\n' + licenseText);
}
return licenseTextArray;
}
function constructPatchesText(
patches: {
[name: string]: PatchRemediation;
},
basicVulnInfo: {
[name: string]: BasicVulnInfo;
},
testOptions: TestOptions,
): string[] {
if (!(Object.keys(patches).length > 0)) {
return [];
}
const patchedTextArray = [chalk.bold.green('\nPatchable issues:')];
for (const id of Object.keys(patches)) {
if (!basicVulnInfo[id]) {
continue;
}
if (basicVulnInfo[id].type === 'license') {
continue;
}
// todo: add vulnToPatch package name
const packageAtVersion = `${basicVulnInfo[id].name}@${basicVulnInfo[id].version}`;
const patchedText = `\n Patch available for ${chalk.bold.whiteBright(
packageAtVersion,
)}\n`;
const thisPatchFixes = formatIssue(
id,
basicVulnInfo[id].title,
basicVulnInfo[id].severity,
basicVulnInfo[id].isNew,
`${basicVulnInfo[id].name}@${basicVulnInfo[id].version}`,
basicVulnInfo[id].paths,
testOptions,
basicVulnInfo[id].note,
);
patchedTextArray.push(patchedText + thisPatchFixes);
}
return patchedTextArray;
}
function thisUpgradeFixes(
vulnIds: string[],
basicVulnInfo: Record<string, BasicVulnInfo>,
testOptions: TestOptions,
) {
return vulnIds
.filter((id) => basicVulnInfo[id]) // basicVulnInfo only contains issues with the specified severity levels
.sort(
(a, b) =>
getSeverityValue(basicVulnInfo[a].severity) -
getSeverityValue(basicVulnInfo[b].severity),
)
.filter((id) => basicVulnInfo[id].type !== 'license')
.map((id) =>
formatIssue(
id,
basicVulnInfo[id].title,
basicVulnInfo[id].severity,
basicVulnInfo[id].isNew,
`${basicVulnInfo[id].name}@${basicVulnInfo[id].version}`,
basicVulnInfo[id].paths,
testOptions,
basicVulnInfo[id].note,
[],
basicVulnInfo[id].reachability,
basicVulnInfo[id].sampleReachablePaths,
),
)
.join('\n');
}
function processUpgrades(
sink: string[],
upgradesByDep: DependencyUpdates | DependencyPins,
deps: string[],
basicVulnInfo: Record<string, BasicVulnInfo>,
testOptions: TestOptions,
) {
for (const dep of deps) {
const data = upgradesByDep[dep];
const upgradeDepTo = data.upgradeTo;
const vulnIds =
(data as UpgradeRemediation).vulns || (data as PinRemediation).vulns;
const upgradeText = `\n Upgrade ${chalk.bold.whiteBright(
dep,
)} to ${chalk.bold.whiteBright(upgradeDepTo)} to fix\n`;
sink.push(
upgradeText + thisUpgradeFixes(vulnIds, basicVulnInfo, testOptions),
);
}
}
function constructUpgradesText(
upgrades: DependencyUpdates,
basicVulnInfo: {
[name: string]: BasicVulnInfo;
},
testOptions: TestOptions,
): string[] {
if (!(Object.keys(upgrades).length > 0)) {
return [];
}
const upgradeTextArray = [chalk.bold.green('\nIssues to fix by upgrading:')];
processUpgrades(
upgradeTextArray,
upgrades,
Object.keys(upgrades),
basicVulnInfo,
testOptions,
);
return upgradeTextArray;
}
function constructPinText(
pins: DependencyPins,
upgradesByAffected: UpgradesByAffectedPackage, // classical "remediation via top-level dep" upgrades
basicVulnInfo: Record<string, BasicVulnInfo>,
testOptions: TestOptions,
): string[] {
if (!Object.keys(pins).length) {
return [];
}
const upgradeTextArray: string[] = [];
upgradeTextArray.push(
chalk.bold.green('\nIssues to fix by upgrading dependencies:'),
);
// First, direct upgrades
const upgradeables = Object.keys(pins).filter(
(name) => !pins[name].isTransitive,
);
if (upgradeables.length) {
processUpgrades(
upgradeTextArray,
pins,
upgradeables,
basicVulnInfo,
testOptions,
);
}
// Second, pins
const pinables = Object.keys(pins).filter((name) => pins[name].isTransitive);
if (pinables.length) {
for (const pkgName of pinables) {
const data = pins[pkgName];
const vulnIds = data.vulns;
const upgradeDepTo = data.upgradeTo;
const upgradeText = `\n Pin ${chalk.bold.whiteBright(
pkgName,
)} to ${chalk.bold.whiteBright(upgradeDepTo)} to fix`;
upgradeTextArray.push(upgradeText);
upgradeTextArray.push(
thisUpgradeFixes(vulnIds, basicVulnInfo, testOptions),
);
// Finally, if we have some upgrade paths that fix the same issues, suggest them as well.
const topLevelUpgradesAlreadySuggested = new Set();
for (const vid of vulnIds) {
for (const topLevelPkg of upgradesByAffected[
pkgName + '@' + basicVulnInfo[vid].version
] || []) {
const setKey = `${topLevelPkg.name}\n${topLevelPkg.version}`;
if (!topLevelUpgradesAlreadySuggested.has(setKey)) {
topLevelUpgradesAlreadySuggested.add(setKey);
upgradeTextArray.push(
' The issues above can also be fixed by upgrading top-level dependency ' +
`${topLevelPkg.name} to ${topLevelPkg.version}`,
);
}
}
}
}
}
return upgradeTextArray;
}
function constructUnfixableText(
unresolved: IssueData[],
basicVulnInfo: Record<string, BasicVulnInfo>,
testOptions: TestOptions,
) {
if (!(unresolved.length > 0)) {
return [];
}
const unfixableIssuesTextArray = [
chalk.bold.white('\nIssues with no direct upgrade or patch:'),
];
for (const issue of unresolved) {
const issueInfo = basicVulnInfo[issue.id];
if (!issueInfo) {
// basicVulnInfo only contains issues with the specified severity levels
continue;
}
const extraInfo =
issue.fixedIn && issue.fixedIn.length
? `\n This issue was fixed in versions: ${chalk.bold(
issue.fixedIn.join(', '),
)}`
: '\n No upgrade or patch available';
unfixableIssuesTextArray.push(
formatIssue(
issue.id,
issue.title,
issue.severity,
issue.isNew,
`${issue.packageName}@${issue.version}`,
issueInfo.paths,
testOptions,
issueInfo.note,
[],
issue.reachability,
) + `${extraInfo}`,
);
}
if (unfixableIssuesTextArray.length === 1) {
// seems we still only have
// the initial section title, so nothing to return
return [];
}
return unfixableIssuesTextArray;
}
function printPath(path: string[]) {
return path.slice(1).join(' > ');
}
export function formatIssue(
id: string,
title: string,
severity: SEVERITY,
isNew: boolean,
vulnerableModule: string,
paths: string[][],
testOptions: TestOptions,
note: string | false,
legalInstructions?: LegalInstruction[],
reachability?: REACHABILITY,
sampleReachablePaths?: SampleReachablePaths,
): string {
const severitiesColourMapping = {
low: {
colorFunc(text) {
return chalk.blueBright(text);
},
},
medium: {
colorFunc(text) {
return chalk.yellowBright(text);
},
},
high: {
colorFunc(text) {
return chalk.redBright(text);
},
},
};
const newBadge = isNew ? ' (new)' : '';
const name = vulnerableModule ? ` in ${chalk.bold(vulnerableModule)}` : '';
let legalLicenseInstructionsText;
if (legalInstructions) {
legalLicenseInstructionsText = formatLegalInstructions(legalInstructions);
}
let reachabilityText = '';
if (reachability) {
reachabilityText = formatReachability(reachability);
}
let introducedBy = '';
if (
testOptions.showVulnPaths === 'some' &&
paths &&
paths.find((p) => p.length > 2)
) {
// In this mode, we show only one path by default, for compactness
const pathStr = printPath(paths[0]);
introducedBy =
paths.length === 1
? `\n introduced by ${pathStr}`
: `\n introduced by ${pathStr} and ${chalk.cyanBright(
'' + (paths.length - 1),
)} other path(s)`;
} else if (testOptions.showVulnPaths === 'all' && paths) {
introducedBy =
'\n introduced by:' +
paths
.slice(0, 1000)
.map((p) => '\n ' + printPath(p))
.join('');
if (paths.length > 1000) {
introducedBy += `\n and ${chalk.cyanBright(
'' + (paths.length - 1),
)} other path(s)`;
}
}
const reachableVia = formatReachablePaths(
sampleReachablePaths,
MAX_REACHABLE_PATHS,
reachablePathsTemplate,
);
return (
severitiesColourMapping[severity].colorFunc(
` ✗ ${chalk.bold(title)}${newBadge} [${titleCaseText(
severity,
)} Severity]`,
) +
reachabilityText +
`[${config.ROOT}/vuln/${id}]` +
name +
reachableVia +
introducedBy +
(legalLicenseInstructionsText
? `${chalk.bold(
'\n Legal instructions',
)}:\n ${legalLicenseInstructionsText}`
: '') +
(note ? `${chalk.bold('\n Note')}:\n ${note}` : '')
);
}
function titleCaseText(text) {
return text[0].toUpperCase() + text.slice(1);
}
function reachablePathsTemplate(
samplePaths: string[],
extraPathsCount: number,
): string {
if (samplePaths.length === 0 && extraPathsCount === 0) {
return '';
}
if (samplePaths.length === 0) {
return `\n reachable via at least ${extraPathsCount} paths`;
}
let reachableVia = '\n reachable via:\n';
for (const p of samplePaths) {
reachableVia += ` ${p}\n`;
}
if (extraPathsCount > 0) {
reachableVia += ` and at least ${chalk.cyanBright(
'' + extraPathsCount,
)} other path(s)`;
}
return reachableVia;
}