/
index.ts
executable file
·502 lines (444 loc) · 14.4 KB
/
index.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
#!/usr/bin/env node
import 'source-map-support/register';
import * as Debug from 'debug';
import * as pathLib from 'path';
const camelCase = require('lodash.camelcase');
// import args as a first internal module
import { args as argsLib, Args, ArgsOptions } from './args';
// parse args as a first thing; argsLib modifies global namespace
// therefore it is better to do it as a first thing to prevent bugs
// when modules use this global setting during their require phase
// TODO(code): remove once https://app.stepsize.com/issue/c2f6253e-7240-436f-943c-23a897558156/2-http-libraries-in-cli is solved
const globalArgs = argsLib(process.argv);
// assert supported node runtime version
import * as runtime from './runtime';
// require analytics as soon as possible to start measuring execution time
import * as analytics from '../lib/analytics';
import * as alerts from '../lib/alerts';
import * as sln from '../lib/sln';
import { TestCommandResult } from './commands/types';
import { copy } from './copy';
import spinner = require('../lib/spinner');
import errors = require('../lib/errors/legacy-errors');
import ansiEscapes = require('ansi-escapes');
import { isPathToPackageFile } from '../lib/detect';
import { updateCheck } from '../lib/updater';
import {
MissingTargetFileError,
FileFlagBadInputError,
OptionMissingErrorError,
UnsupportedOptionCombinationError,
ExcludeFlagBadInputError,
CustomError,
} from '../lib/errors';
import stripAnsi from 'strip-ansi';
import { ExcludeFlagInvalidInputError } from '../lib/errors/exclude-flag-invalid-input';
import { modeValidation } from './modes';
import { JsonFileOutputBadInputError } from '../lib/errors/json-file-output-bad-input-error';
import { saveJsonToFileCreatingDirectoryIfRequired } from '../lib/json-file-output';
import {
Options,
TestOptions,
MonitorOptions,
SupportedUserReachableFacingCliArgs,
} from '../lib/types';
import { SarifFileOutputEmptyError } from '../lib/errors/empty-sarif-output-error';
import { InvalidDetectionDepthValue } from '../lib/errors/invalid-detection-depth-value';
import { getIacOrgSettings } from './commands/test/iac-local-execution/org-settings/get-iac-org-settings';
import { isFeatureFlagSupportedForOrg } from '../lib/feature-flags';
const debug = Debug('snyk');
const EXIT_CODES = {
VULNS_FOUND: 1,
ERROR: 2,
NO_SUPPORTED_MANIFESTS_FOUND: 3,
};
async function runCommand(args: Args) {
const commandResult = await args.method(...args.options._);
const res = analytics.addDataAndSend({
args: args.options._,
command: args.command,
org: args.options.org,
});
if (!commandResult) {
return;
}
const result = commandResult.toString();
if (result && !args.options.quiet) {
if (args.options.copy) {
copy(result);
console.log('Result copied to clipboard');
} else {
console.log(result);
}
}
// also save the json (in error.json) to file if option is set
if (args.command === 'test') {
const jsonResults = (commandResult as TestCommandResult).getJsonResult();
await saveResultsToFile(args.options, 'json', jsonResults);
const sarifResults = (commandResult as TestCommandResult).getSarifResult();
await saveResultsToFile(args.options, 'sarif', sarifResults);
}
return res;
}
async function handleError(args, error) {
spinner.clearAll();
let command = 'bad-command';
let exitCode = EXIT_CODES.ERROR;
const noSupportedManifestsFound = error.message?.includes(
'Could not detect supported target files in',
);
if (noSupportedManifestsFound) {
exitCode = EXIT_CODES.NO_SUPPORTED_MANIFESTS_FOUND;
}
const vulnsFound = error.code === 'VULNS';
if (vulnsFound) {
// this isn't a bad command, so we won't record it as such
command = args.command;
exitCode = EXIT_CODES.VULNS_FOUND;
}
if (args.options.debug && !args.options.json) {
const output = vulnsFound ? error.message : error.stack;
console.log(output);
} else if (
args.options.json &&
!(error instanceof UnsupportedOptionCombinationError)
) {
console.log(stripAnsi(error.json || error.stack));
} else {
if (!args.options.quiet) {
const result = errors.message(error);
if (args.options.copy) {
copy(result);
console.log('Result copied to clipboard');
} else {
if (`${error.code}`.indexOf('AUTH_') === 0) {
// remove the last few lines
const erase = ansiEscapes.eraseLines(4);
process.stdout.write(erase);
}
console.log(result);
}
}
}
await saveResultsToFile(args.options, 'json', error.jsonStringifiedResults);
await saveResultsToFile(args.options, 'sarif', error.sarifStringifiedResults);
const analyticsError = vulnsFound
? {
stack: error.jsonNoVulns,
code: error.code,
message: 'Vulnerabilities found',
}
: {
stack: error.stack,
code: error.code,
message: error.message,
};
if (!vulnsFound && !error.stack) {
// log errors that are not error objects
analytics.add('error', true);
analytics.add('command', args.command);
} else {
analytics.add('error-message', analyticsError.message);
// Note that error.stack would also contain the error message
// (see https://nodejs.org/api/errors.html#errors_error_stack)
analytics.add('error', analyticsError.stack);
analytics.add('error-code', error.code);
analytics.add('command', args.command);
}
const res = analytics.addDataAndSend({
args: args.options._,
command,
org: args.options.org,
});
return { res, exitCode };
}
function getFullPath(filepathFragment: string): string {
if (pathLib.isAbsolute(filepathFragment)) {
return filepathFragment;
} else {
const fullPath = pathLib.join(process.cwd(), filepathFragment);
return fullPath;
}
}
async function saveJsonResultsToFile(
stringifiedJson: string,
jsonOutputFile: string,
) {
if (!jsonOutputFile) {
console.error('empty jsonOutputFile');
return;
}
if (jsonOutputFile.constructor.name !== String.name) {
console.error('--json-output-file should be a filename path');
return;
}
await saveJsonToFileCreatingDirectoryIfRequired(
jsonOutputFile,
stringifiedJson,
);
}
function checkRuntime() {
if (!runtime.isSupported(process.versions.node)) {
console.error(
`Node.js version ${process.versions.node} is an unsupported Node.js ` +
`runtime! Supported runtime range is '${runtime.supportedRange}'`,
);
console.error(
'Please upgrade your Node.js runtime. The last version of Snyk CLI that supports Node.js v8 is v1.454.0.',
);
process.exit(EXIT_CODES.ERROR);
}
}
// Throw error if user specifies package file name as part of path,
// and if user specifies multiple paths and used project-name option.
function checkPaths(args) {
let count = 0;
for (const path of args.options._) {
if (typeof path === 'string' && isPathToPackageFile(path)) {
throw MissingTargetFileError(path);
} else if (typeof path === 'string') {
if (++count > 1 && args.options['project-name']) {
throw new UnsupportedOptionCombinationError([
'multiple paths',
'project-name',
]);
}
}
}
}
type AllSupportedCliOptions = Options & MonitorOptions & TestOptions;
async function main() {
updateCheck();
checkRuntime();
let res;
let failed = false;
let exitCode = EXIT_CODES.ERROR;
try {
modeValidation(globalArgs);
// TODO: fix this, we do transformation to options and teh type doesn't reflect it
validateUnsupportedOptionCombinations(
(globalArgs.options as unknown) as AllSupportedCliOptions,
);
// IaC only: used for rolling out the experimental flow
// modify args if experimental flag not provided, based on feature flag
// this can be removed once experimental becomes the default
if (
globalArgs.options['iac'] &&
globalArgs.command === 'test' &&
!globalArgs.options['experimental']
) {
const iacOrgSettings = await getIacOrgSettings();
const experimentalFlowEnabled = await isFeatureFlagSupportedForOrg(
camelCase('experimental-local-exec-iac'),
iacOrgSettings.meta.org,
);
globalArgs.options['experimental'] = !!experimentalFlowEnabled.ok;
}
if (globalArgs.options['app-vulns'] && globalArgs.options['json']) {
throw new UnsupportedOptionCombinationError([
'Application vulnerabilities is currently not supported with JSON output. ' +
'Please try using —app-vulns only to get application vulnerabilities, or ' +
'—json only to get your image vulnerabilties, excluding the application ones.',
]);
}
if (globalArgs.options['group-issues'] && globalArgs.options['iac']) {
throw new UnsupportedOptionCombinationError([
'--group-issues is currently not supported for Snyk IaC.',
]);
}
if (
globalArgs.options['group-issues'] &&
!globalArgs.options['json'] &&
!globalArgs.options['json-file-output']
) {
throw new UnsupportedOptionCombinationError([
'JSON output is required to use --group-issues, try adding --json.',
]);
}
if (
globalArgs.options.file &&
typeof globalArgs.options.file === 'string' &&
(globalArgs.options.file as string).match(/\.sln$/)
) {
if (globalArgs.options['project-name']) {
throw new UnsupportedOptionCombinationError([
'file=*.sln',
'project-name',
]);
}
sln.updateArgs(globalArgs);
} else if (typeof globalArgs.options.file === 'boolean') {
throw new FileFlagBadInputError();
}
if (
typeof globalArgs.options.detectionDepth !== 'undefined' &&
(globalArgs.options.detectionDepth <= 0 ||
Number.isNaN(globalArgs.options.detectionDepth))
) {
throw new InvalidDetectionDepthValue();
}
validateUnsupportedSarifCombinations(globalArgs);
validateOutputFile(
globalArgs.options,
'json',
new JsonFileOutputBadInputError(),
);
validateOutputFile(
globalArgs.options,
'sarif',
new SarifFileOutputEmptyError(),
);
checkPaths(globalArgs);
res = await runCommand(globalArgs);
} catch (error) {
failed = true;
const response = await handleError(globalArgs, error);
res = response.res;
exitCode = response.exitCode;
}
if (!globalArgs.options.json) {
console.log(alerts.displayAlerts());
}
if (!process.env.TAP && failed) {
debug('Exit code: ' + exitCode);
process.exitCode = exitCode;
}
return res;
}
const cli = main().catch((e) => {
console.error('Something unexpected went wrong: ', e.stack);
console.error('Exit code: ' + EXIT_CODES.ERROR);
process.exit(EXIT_CODES.ERROR);
});
if (module.parent) {
// eslint-disable-next-line id-blacklist
module.exports = cli;
}
function validateUnsupportedOptionCombinations(
options: AllSupportedCliOptions,
): void {
const unsupportedAllProjectsCombinations: {
[name: string]: SupportedUserReachableFacingCliArgs;
} = {
'project-name': 'project-name',
file: 'file',
yarnWorkspaces: 'yarn-workspaces',
packageManager: 'package-manager',
docker: 'docker',
allSubProjects: 'all-sub-projects',
};
const unsupportedYarnWorkspacesCombinations: {
[name: string]: SupportedUserReachableFacingCliArgs;
} = {
'project-name': 'project-name',
file: 'file',
packageManager: 'package-manager',
docker: 'docker',
allSubProjects: 'all-sub-projects',
};
if (options.scanAllUnmanaged && options.file) {
throw new UnsupportedOptionCombinationError(['file', 'scan-all-unmanaged']);
}
if (options.allProjects) {
for (const option in unsupportedAllProjectsCombinations) {
if (options[option]) {
throw new UnsupportedOptionCombinationError([
unsupportedAllProjectsCombinations[option],
'all-projects',
]);
}
}
}
if (options.yarnWorkspaces) {
for (const option in unsupportedYarnWorkspacesCombinations) {
if (options[option]) {
throw new UnsupportedOptionCombinationError([
unsupportedAllProjectsCombinations[option],
'yarn-workspaces',
]);
}
}
}
if (options.exclude) {
if (!(options.allProjects || options.yarnWorkspaces)) {
throw new OptionMissingErrorError('--exclude', [
'--yarn-workspaces',
'--all-projects',
]);
}
if (typeof options.exclude !== 'string') {
throw new ExcludeFlagBadInputError();
}
if (options.exclude.indexOf(pathLib.sep) > -1) {
throw new ExcludeFlagInvalidInputError();
}
}
}
function validateUnsupportedSarifCombinations(args) {
if (args.options['json-file-output'] && args.command !== 'test') {
throw new UnsupportedOptionCombinationError([
args.command,
'json-file-output',
]);
}
if (args.options['sarif'] && args.command !== 'test') {
throw new UnsupportedOptionCombinationError([args.command, 'sarif']);
}
if (args.options['sarif'] && args.options['json']) {
throw new UnsupportedOptionCombinationError([
args.command,
'sarif',
'json',
]);
}
if (args.options['sarif-file-output'] && args.command !== 'test') {
throw new UnsupportedOptionCombinationError([
args.command,
'sarif-file-output',
]);
}
if (
args.options['sarif'] &&
args.options['docker'] &&
!args.options['file']
) {
throw new OptionMissingErrorError('sarif', ['--file']);
}
if (
args.options['sarif-file-output'] &&
args.options['docker'] &&
!args.options['file']
) {
throw new OptionMissingErrorError('sarif-file-output', ['--file']);
}
}
async function saveResultsToFile(
options: ArgsOptions,
outputType: string,
jsonResults: string,
) {
const flag = `${outputType}-file-output`;
const outputFile = options[flag];
if (outputFile && jsonResults) {
const outputFileStr = outputFile as string;
const fullOutputFilePath = getFullPath(outputFileStr);
await saveJsonResultsToFile(stripAnsi(jsonResults), fullOutputFilePath);
}
}
function validateOutputFile(
options: ArgsOptions,
outputType: string,
error: CustomError,
) {
const fileOutputValue = options[`${outputType}-file-output`];
if (fileOutputValue === undefined) {
return;
}
if (!fileOutputValue || typeof fileOutputValue !== 'string') {
throw error;
}
// On Windows, seems like quotes get passed in
if (fileOutputValue === "''" || fileOutputValue === '""') {
throw error;
}
}