-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathresponse-builder.ts
More file actions
472 lines (428 loc) · 14.1 KB
/
response-builder.ts
File metadata and controls
472 lines (428 loc) · 14.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
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
import { legacy } from "@snyk/dep-graph";
import { StaticAnalysis } from "./analyzer/types";
import * as facts from "./facts";
// Module that provides functions to collect and build response after all
// analyses' are done.
import { instructionDigest } from "./dockerfile";
import { DockerFileAnalysis, DockerFilePackages } from "./dockerfile/types";
import { OCIDistributionMetadata } from "./extractor/oci-distribution-metadata";
import * as types from "./types";
import { truncateAdditionalFacts } from "./utils";
import { PLUGIN_VERSION } from "./version";
export { buildResponse };
async function buildResponse(
depsAnalysis: StaticAnalysis & {
depTree: types.DepTree;
packageFormat: string;
},
dockerfileAnalysis: DockerFileAnalysis | undefined,
excludeBaseImageVulns: boolean,
names?: string[],
ociDistributionMetadata?: OCIDistributionMetadata,
options?: Partial<types.PluginOptions>,
): Promise<types.PluginResponse> {
const deps = depsAnalysis.depTree.dependencies;
// Expand dockerfile packages and auto detected user instructions if
// they are provided. These objects are mutated in place, ensuring the
// expanded packages are used in the subsequent steps and fact building.
if (dockerfileAnalysis?.dockerfilePackages) {
getUserInstructionDeps(dockerfileAnalysis.dockerfilePackages, deps);
}
if (depsAnalysis.autoDetectedUserInstructions?.dockerfilePackages) {
getUserInstructionDeps(
depsAnalysis.autoDetectedUserInstructions.dockerfilePackages,
deps,
);
}
const dockerfilePkgs =
dockerfileAnalysis?.dockerfilePackages ??
depsAnalysis.autoDetectedUserInstructions?.dockerfilePackages;
if (dockerfilePkgs) {
const finalDeps = excludeBaseImageDeps(
deps,
dockerfilePkgs,
excludeBaseImageVulns,
);
annotateLayerIds(finalDeps, dockerfilePkgs);
depsAnalysis.depTree.dependencies = finalDeps;
}
/** This must be called after all final changes to the DependencyTree. */
const depGraph = await legacy.depTreeToGraph(
depsAnalysis.depTree,
depsAnalysis.packageFormat,
);
const additionalFacts: types.Fact[] = [];
const hashes = depsAnalysis.binaries;
if (hashes && hashes.length > 0) {
const keyBinariesHashesFact: facts.KeyBinariesHashesFact = {
type: "keyBinariesHashes",
data: hashes,
};
additionalFacts.push(keyBinariesHashesFact);
}
if (depsAnalysis.baseRuntimes && depsAnalysis.baseRuntimes.length > 0) {
const baseRuntimesFact: facts.BaseRuntimesFact = {
type: "baseRuntimes",
data: depsAnalysis.baseRuntimes,
};
additionalFacts.push(baseRuntimesFact);
}
if (dockerfileAnalysis !== undefined) {
const dockerfileAnalysisFact: facts.DockerfileAnalysisFact = {
type: "dockerfileAnalysis",
data: dockerfileAnalysis,
};
additionalFacts.push(dockerfileAnalysisFact);
}
if (depsAnalysis.imageId) {
const imageIdFact: facts.ImageIdFact = {
type: "imageId",
data: depsAnalysis.imageId,
};
additionalFacts.push(imageIdFact);
}
if (depsAnalysis.imageLayers && depsAnalysis.imageLayers.length > 0) {
const imageLayersFact: facts.ImageLayersFact = {
type: "imageLayers",
data: depsAnalysis.imageLayers,
};
additionalFacts.push(imageLayersFact);
}
if (depsAnalysis.imageLabels) {
const imageLabels: facts.ImageLabels = {
type: "imageLabels",
data: depsAnalysis.imageLabels,
};
additionalFacts.push(imageLabels);
}
if (depsAnalysis.containerConfig) {
const containerConfigFact: facts.ContainerConfigFact = {
type: "containerConfig",
data: {
...(depsAnalysis.containerConfig.User !== undefined && {
user: depsAnalysis.containerConfig.User,
}),
...(depsAnalysis.containerConfig.ExposedPorts !== undefined && {
exposedPorts: depsAnalysis.containerConfig.ExposedPorts
? Object.keys(depsAnalysis.containerConfig.ExposedPorts)
: null,
}),
...(depsAnalysis.containerConfig.Env !== undefined && {
env: depsAnalysis.containerConfig.Env,
}),
...(depsAnalysis.containerConfig.Entrypoint !== undefined && {
entrypoint: depsAnalysis.containerConfig.Entrypoint,
}),
...(depsAnalysis.containerConfig.Cmd !== undefined && {
cmd: depsAnalysis.containerConfig.Cmd,
}),
...(depsAnalysis.containerConfig.Volumes !== undefined && {
volumes: depsAnalysis.containerConfig.Volumes
? Object.keys(depsAnalysis.containerConfig.Volumes)
: null,
}),
...(depsAnalysis.containerConfig.WorkingDir !== undefined && {
workingDir: depsAnalysis.containerConfig.WorkingDir,
}),
...(depsAnalysis.containerConfig.StopSignal !== undefined && {
stopSignal: depsAnalysis.containerConfig.StopSignal,
}),
...(depsAnalysis.containerConfig.ArgsEscaped !== undefined && {
argsEscaped: depsAnalysis.containerConfig.ArgsEscaped,
}),
},
};
additionalFacts.push(containerConfigFact);
}
if (depsAnalysis.history && depsAnalysis.history.length > 0) {
const historyFact: facts.HistoryFact = {
type: "history",
data: depsAnalysis.history.map((entry) => ({
...(entry.created !== undefined && { created: entry.created }),
...(entry.author !== undefined && { author: entry.author }),
...(entry.created_by !== undefined && { createdBy: entry.created_by }),
...(entry.comment !== undefined && { comment: entry.comment }),
...(entry.empty_layer !== undefined && {
emptyLayer: entry.empty_layer,
}),
})),
};
additionalFacts.push(historyFact);
}
if (depsAnalysis.imageCreationTime) {
const imageCreationTimeFact: facts.ImageCreationTimeFact = {
type: "imageCreationTime",
data: depsAnalysis.imageCreationTime,
};
additionalFacts.push(imageCreationTimeFact);
}
if (
depsAnalysis.rootFsLayers &&
Array.isArray(depsAnalysis.rootFsLayers) &&
depsAnalysis.rootFsLayers.length > 0
) {
const rootFsFact: facts.RootFsFact = {
type: "rootFs",
data: depsAnalysis.rootFsLayers,
};
additionalFacts.push(rootFsFact);
}
if (depsAnalysis.depTree.targetOS.prettyName) {
const imageOsReleasePrettyNameFact: facts.ImageOsReleasePrettyNameFact = {
type: "imageOsReleasePrettyName",
data: depsAnalysis.depTree.targetOS.prettyName,
};
additionalFacts.push(imageOsReleasePrettyNameFact);
}
const manifestFiles =
depsAnalysis.manifestFiles.length > 0
? depsAnalysis.manifestFiles
: undefined;
if (manifestFiles) {
const imageManifestFilesFact: facts.ImageManifestFilesFact = {
type: "imageManifestFiles",
data: manifestFiles,
};
additionalFacts.push(imageManifestFilesFact);
}
const autoDetectedPackages =
depsAnalysis.autoDetectedUserInstructions?.dockerfilePackages;
const autoDetectedLayers =
depsAnalysis.autoDetectedUserInstructions?.dockerfileLayers;
if (
autoDetectedPackages &&
Object.keys(autoDetectedPackages).length > 0 &&
autoDetectedLayers &&
Object.keys(autoDetectedLayers).length > 0
) {
const autoDetectedUserInstructionsFact: facts.AutoDetectedUserInstructionsFact =
{
type: "autoDetectedUserInstructions",
data: {
dockerfileLayers: autoDetectedLayers,
dockerfilePackages: autoDetectedPackages,
},
};
additionalFacts.push(autoDetectedUserInstructionsFact);
}
const applicationDependenciesScanResults: types.ScanResult[] = (
depsAnalysis.applicationDependenciesScanResults || []
).map((appDepsScanResult) => {
if (depsAnalysis.imageId) {
const imageIdFact: facts.ImageIdFact = {
type: "imageId",
data: depsAnalysis.imageId,
};
appDepsScanResult.facts.push(imageIdFact);
}
if (names && names.length > 0) {
const imageNamesFact: facts.ImageNamesFact = {
type: "imageNames",
data: { names },
};
appDepsScanResult.facts.push(imageNamesFact);
}
if (ociDistributionMetadata) {
const metadataFact: facts.OCIDistributionMetadataFact = {
type: "ociDistributionMetadata",
data: ociDistributionMetadata,
};
appDepsScanResult.facts.push(metadataFact);
}
const appPluginVersionFact: facts.PluginVersionFact = {
type: "pluginVersion",
data: PLUGIN_VERSION,
};
appDepsScanResult.facts.push(appPluginVersionFact);
return {
...appDepsScanResult,
target: {
image: depGraph.rootPkg.name,
},
...(options &&
options["target-reference"] && {
targetReference: options["target-reference"],
}),
};
});
const args =
depsAnalysis.platform !== undefined
? { platform: depsAnalysis.platform }
: undefined;
const depGraphFact: facts.DepGraphFact = {
type: "depGraph",
data: depGraph,
};
if (names) {
if (names.length > 0) {
const imageNameInfo = { names };
const imageNamesFact: facts.ImageNamesFact = {
type: "imageNames",
data: imageNameInfo,
};
additionalFacts.push(imageNamesFact);
}
}
if (ociDistributionMetadata) {
const metadataFact: facts.OCIDistributionMetadataFact = {
type: "ociDistributionMetadata",
data: ociDistributionMetadata,
};
additionalFacts.push(metadataFact);
}
if (depsAnalysis.platform) {
const platformFact: facts.PlatformFact = {
type: "platform",
data: depsAnalysis.platform,
};
additionalFacts.push(platformFact);
}
const pluginVersionFact: facts.PluginVersionFact = {
type: "pluginVersion",
data: PLUGIN_VERSION,
};
additionalFacts.push(pluginVersionFact);
if (options?.parameterWarnings && options.parameterWarnings.length > 0) {
const pluginWarningsFact: facts.PluginWarningsFact = {
type: "pluginWarnings",
data: {
parameterChecks: options.parameterWarnings,
},
};
additionalFacts.push(pluginWarningsFact);
}
const scanResults: types.ScanResult[] = [
{
facts: [depGraphFact, ...additionalFacts],
target: {
image: depGraph.rootPkg.name,
},
identity: {
type: depGraph.pkgManager.name,
args,
},
...(options &&
options["target-reference"] && {
targetReference: options["target-reference"] ?? depGraph.rootPkg.name,
}),
},
...applicationDependenciesScanResults,
];
const truncatedScanResults = scanResults.map((result) => ({
...result,
facts: truncateAdditionalFacts(result.facts || []),
}));
return {
scanResults: truncatedScanResults,
};
}
/**
* Expands the provided dockerfile packages to include transitive dependencies.
* Transitive dependencies are keyed by their source segments.
*
* @important
* mutates the provided `dockerfilePackages` object.
*
* @warning
* **Known Issue:** In some scenarios, this function can cause over-attribution of
* dependencies to the dockerfile because the `dockerfilePackages` object is mutated
* while iterating. This behavior is retained for downstream compatibility.
*
* @param dockerfilePackages - The dockerfile packages to expand.
* @param dependencies - The dependencies of the image.
* @returns The expanded dockerfile packages.
*/
function getUserInstructionDeps(
dockerfilePackages: DockerFilePackages,
dependencies: {
[depName: string]: types.DepTreeDep;
},
): DockerFilePackages {
for (const dependencyName in dependencies) {
if (dependencies.hasOwnProperty(dependencyName)) {
const sourceOrName = dependencyName.split("/")[0];
const dockerfilePackage = dockerfilePackages[sourceOrName];
if (dockerfilePackage) {
for (const dep of collectDeps(dependencies[dependencyName])) {
dockerfilePackages[dep.split("/")[0]] = { ...dockerfilePackage };
}
}
}
}
return dockerfilePackages;
}
function collectDeps(pkg) {
// ES5 doesn't have Object.values, so replace with Object.keys() and map()
return pkg.dependencies
? Object.keys(pkg.dependencies)
.map((name) => pkg.dependencies[name])
.reduce((allDeps, pkg) => {
return [...allDeps, ...collectDeps(pkg)];
}, Object.keys(pkg.dependencies))
: [];
}
/**
* Excludes base image dependencies from the dependency tree if excludeBaseImageVulns is true.
*
* @param deps - The dependencies of the image.
* @param dockerfilePkgs - The expanded packages attributed to the Dockerfile.
* @param excludeBaseImageVulns - Whether to exclude base image dependencies.
* @returns The dependencies of the image.
*/
function excludeBaseImageDeps(
deps: {
[depName: string]: types.DepTreeDep;
},
dockerfilePkgs: DockerFilePackages | undefined,
excludeBaseImageVulns: boolean,
) {
if (!excludeBaseImageVulns || !dockerfilePkgs) {
return deps;
}
return Object.keys(deps)
.filter((depName) => {
if (dockerfilePkgs[depName] !== undefined) {
return true;
}
const source = depName.split("/")[0];
return dockerfilePkgs[source] !== undefined;
})
.reduce((extractedDeps, depName) => {
extractedDeps[depName] = deps[depName];
return extractedDeps;
}, {});
}
/**
* Annotates the dependencies with the layer ID of the Dockerfile
* instruction that installed them.
*
* @important
* mutates the provided `deps` object.
*
* @param deps - The dependencies of the image.
* @param dockerfilePkgs - The expanded packages attributed to the Dockerfile.
*/
function annotateLayerIds(
deps: {
[depName: string]: types.DepTreeDep;
},
dockerfilePkgs: DockerFilePackages | undefined,
) {
if (!dockerfilePkgs) {
return;
}
for (const dep of Object.keys(deps)) {
const pkg = deps[dep];
const pkgSource = dep.split("/")[0];
const dockerfilePkg = dockerfilePkgs[dep] || dockerfilePkgs[pkgSource];
if (dockerfilePkg) {
pkg.labels = {
...(pkg.labels || {}),
dockerLayerId: instructionDigest(dockerfilePkg.instruction),
};
}
if (pkg.dependencies) {
annotateLayerIds(pkg.dependencies, dockerfilePkgs);
}
}
}