/
resolve-test-facts.ts
363 lines (319 loc) · 10.2 KB
/
resolve-test-facts.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
import { Options, PolicyOptions } from '../types';
import { spinner } from '../../lib/spinner';
import {
Ecosystem,
ScanResult,
TestResult,
FileSignaturesDetails,
} from './types';
import {
CreateDepGraphResponse,
GetIssuesResponse,
FileHashes,
Attributes,
} from './unmanaged/types';
import {
requestTestPollingToken,
pollingTestWithTokenUntilDone,
createDepGraph,
getDepGraph,
getIssues,
} from '../polling/polling-test';
import { extractAndApplyPluginAnalytics } from './plugin-analytics';
import { findAndLoadPolicy } from '../policy';
import { filterIgnoredIssues } from './policy';
import { IssueDataUnmanaged, Issue } from '../snyk-test/legacy';
import { hasFeatureFlag } from '../feature-flags';
import {
convertDepGraph,
convertMapCasing,
convertToCamelCase,
getSelf,
} from './unmanaged/utils';
import { sleep } from '../common';
import { SEVERITY } from '../snyk-test/common';
export async function resolveAndTestFacts(
ecosystem: Ecosystem,
scans: {
[dir: string]: ScanResult[];
},
options: Options & PolicyOptions,
): Promise<[TestResult[], string[]]> {
const unmanagedDepsOverride = process.env.USE_UNMANAGED_DEPS;
const featureFlagEnabled = await hasFeatureFlag(
'snykNewUnmanagedTest',
options,
);
return featureFlagEnabled || unmanagedDepsOverride?.toLowerCase() === 'true'
? resolveAndTestFactsUnmanagedDeps(scans, options)
: resolveAndTestFactsRegistry(ecosystem, scans, options);
}
async function getOrgDefaultContext(): Promise<string> {
return (await getSelf())?.data.attributes.default_org_context;
}
async function submitHashes(
hashes: FileHashes,
orgId: string,
): Promise<string> {
const response: CreateDepGraphResponse = await createDepGraph(hashes, orgId);
return response.data.id;
}
async function pollDepGraphAttributes(
id: string,
orgId: string,
): Promise<Attributes> {
const minIntervalMs = 2000;
const maxIntervalMs = 20000;
let totalElaspedTime = 0;
let attempts = 1;
const maxElapsedTime = 1800000; // 30 mins in ms
// Loop until we receive a response that is not in progress,
// or we receive something else than http status code 200.
while (totalElaspedTime <= maxElapsedTime) {
const graph = await getDepGraph(id, orgId);
if (graph.data.attributes.in_progress) {
const pollInterval = Math.min(minIntervalMs * attempts, maxIntervalMs);
await sleep(pollInterval);
totalElaspedTime += pollInterval;
attempts++;
continue;
}
return graph.data.attributes;
}
throw new Error('max retries reached');
}
async function fetchIssues(
start_time,
dep_graph_data,
component_details,
target_severity: SEVERITY,
orgId: string,
) {
const response: GetIssuesResponse = await getIssues(
{
dep_graph: dep_graph_data,
start_time,
component_details,
target_severity,
},
orgId,
);
const issues = response.data.result.issues.map((issue) => {
const converted = convertToCamelCase<Issue>(issue);
converted.fixInfo = convertToCamelCase(converted.fixInfo);
return converted;
});
const issuesData = convertMapCasing<{
[issueId: string]: IssueDataUnmanaged;
}>(response.data.result.issues_data);
const depGraphData = convertDepGraph(response.data.result.dep_graph);
const dependencyCount = response.data.result.dep_graph.graph.nodes.find(
(graphNode) => {
return graphNode.node_id === 'root-node';
},
)?.deps?.length;
const depsFilePaths = response.data.result.deps_file_paths;
const fileSignaturesDetails = convertMapCasing<FileSignaturesDetails>(
response.data.result.file_signatures_details,
);
return {
issues,
issuesData,
depGraphData,
dependencyCount,
depsFilePaths,
fileSignaturesDetails,
};
}
export async function resolveAndTestFactsUnmanagedDeps(
scans: {
[dir: string]: ScanResult[];
},
options: Options & PolicyOptions,
): Promise<[TestResult[], string[]]> {
const results: any[] = [];
const errors: string[] = [];
const packageManager = 'Unmanaged (C/C++)';
const displayTargetFile = '';
const orgId = options.org || (await getOrgDefaultContext()) || '';
const target_severity: SEVERITY = options.severityThreshold || SEVERITY.LOW;
if (orgId === '') {
errors.push('organisation-id missing');
return [results, errors];
}
for (const [path, scanResults] of Object.entries(scans)) {
await spinner(`Resolving and Testing fileSignatures in ${path}`);
for (const scanResult of scanResults) {
try {
const id = await submitHashes(
{ hashes: scanResult?.facts[0]?.data },
orgId,
);
if (scanResult.analytics) {
extractAndApplyPluginAnalytics(scanResult.analytics, id);
}
const {
start_time,
dep_graph_data,
component_details,
} = await pollDepGraphAttributes(id, orgId);
const {
issues,
issuesData,
depGraphData,
dependencyCount,
depsFilePaths,
fileSignaturesDetails,
} = await fetchIssues(
start_time,
dep_graph_data,
component_details,
target_severity,
orgId,
);
const issuesMap: Map<string, Issue> = new Map();
issues.forEach((i) => {
issuesMap[i.issueId] = i;
});
const vulnerabilities: IssueDataUnmanaged[] = [];
for (const issuesDataKey in issuesData) {
const pkgCoordinate = `${issuesMap[issuesDataKey]?.pkgName}@${issuesMap[issuesDataKey]?.pkgVersion}`;
const issueData = issuesData[issuesDataKey];
issueData.from = [pkgCoordinate];
issueData.name = pkgCoordinate;
issueData.packageManager = packageManager;
issueData.version = issuesMap[issuesDataKey]?.pkgVersion;
issueData.upgradePath = [false];
issueData.isPatchable = false;
vulnerabilities.push(issueData);
}
const policy = await findAndLoadPolicy(path, 'cpp', options);
const [issuesFiltered, issuesDataFiltered] = filterIgnoredIssues(
issues,
issuesData,
policy,
);
extractAndApplyPluginAnalytics([
{
name: 'packageManager',
data: depGraphData?.pkgManager?.name ?? '',
},
{
name: 'unmanagedDependencyCount',
data: depGraphData?.pkgs.length ?? 0,
},
{
name: 'unmanagedIssuesCount',
data: issues.length ?? 0,
},
]);
results.push({
issues: issuesFiltered,
issuesData: issuesDataFiltered,
depGraphData,
depsFilePaths,
fileSignaturesDetails,
vulnerabilities,
path,
dependencyCount,
packageManager,
displayTargetFile,
});
} catch (error) {
const hasStatusCodeError = error.code >= 400 && error.code <= 500;
if (hasStatusCodeError) {
errors.push(error.message);
continue;
}
const failedPath = path ? `in ${path}` : '.';
errors.push(`Could not test dependencies ${failedPath}`);
}
}
}
spinner.clearAll();
return [results, errors];
}
export async function resolveAndTestFactsRegistry(
ecosystem: Ecosystem,
scans: {
[dir: string]: ScanResult[];
},
options: Options & PolicyOptions,
): Promise<[TestResult[], string[]]> {
const results: any[] = [];
const errors: string[] = [];
const packageManager = 'Unmanaged (C/C++)';
const displayTargetFile = '';
for (const [path, scanResults] of Object.entries(scans)) {
await spinner(`Resolving and Testing fileSignatures in ${path}`);
for (const scanResult of scanResults) {
try {
const res = await requestTestPollingToken(options, true, scanResult);
if (scanResult.analytics) {
extractAndApplyPluginAnalytics(scanResult.analytics, res.token);
}
const { maxAttempts, pollInterval } = res.pollingTask;
const attemptsCount = 0;
const response = await pollingTestWithTokenUntilDone(
res.token,
ecosystem,
options,
pollInterval,
attemptsCount,
maxAttempts,
);
const policy = await findAndLoadPolicy(path, 'cpp', options);
const [issues, issuesData] = filterIgnoredIssues(
response.issues,
response.issuesData,
policy,
);
const issuesMap: Map<string, Issue> = new Map();
response.issues.forEach((i) => {
issuesMap[i.issueId] = i;
});
const vulnerabilities: IssueDataUnmanaged[] = [];
for (const issuesDataKey in response.issuesData) {
if (issuesMap[issuesDataKey]) {
const issueData = response.issuesData[issuesDataKey];
const pkgCoordinate = `${issuesMap[issuesDataKey].pkgName}@${issuesMap[issuesDataKey].pkgVersion}`;
issueData.from = [pkgCoordinate];
issueData.name = pkgCoordinate;
issueData.packageManager = packageManager;
issueData.version = issuesMap[issuesDataKey]?.pkgVersion;
issueData.upgradePath = [false];
issueData.isPatchable = false;
vulnerabilities.push(issueData);
}
}
const dependencyCount = response?.depGraphData?.graph?.nodes?.find(
(graphNode) => {
return graphNode.nodeId === 'root-node';
},
)?.deps?.length;
results.push({
issues,
issuesData,
depGraphData: response?.depGraphData,
depsFilePaths: response?.depsFilePaths,
fileSignaturesDetails: response?.fileSignaturesDetails,
vulnerabilities,
path,
dependencyCount,
packageManager,
displayTargetFile,
});
} catch (error) {
const hasStatusCodeError = error.code >= 400 && error.code <= 500;
if (hasStatusCodeError) {
errors.push(error.message);
continue;
}
const failedPath = path ? `in ${path}` : '.';
errors.push(`Could not test dependencies ${failedPath}`);
}
}
}
spinner.clearAll();
return [results, errors];
}