-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcmd-scan-create.mts
More file actions
623 lines (571 loc) · 19.1 KB
/
cmd-scan-create.mts
File metadata and controls
623 lines (571 loc) · 19.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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
import path from 'node:path'
import { joinAnd } from '@socketsecurity/registry/lib/arrays'
import { logger } from '@socketsecurity/registry/lib/logger'
import { handleCreateNewScan } from './handle-create-new-scan.mts'
import { outputCreateNewScan } from './output-create-new-scan.mts'
import { reachabilityFlags } from './reachability-flags.mts'
import { suggestOrgSlug } from './suggest-org-slug.mts'
import { suggestTarget } from './suggest_target.mts'
import { validateReachabilityTarget } from './validate-reachability-target.mts'
import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts'
import { commonFlags, outputFlags } from '../../flags.mts'
import { checkCommandInput } from '../../utils/check-input.mts'
import { cmdFlagValueToArray } from '../../utils/cmd.mts'
import { determineOrgSlug } from '../../utils/determine-org-slug.mts'
import { getEcosystemChoicesForMeow } from '../../utils/ecosystem.mts'
import { getOutputKind } from '../../utils/get-output-kind.mts'
import {
detectDefaultBranch,
getRepoName,
gitBranch,
} from '../../utils/git.mts'
import { meowOrExit } from '../../utils/meow-with-subcommands.mts'
import {
getFlagApiRequirementsOutput,
getFlagListOutput,
} from '../../utils/output-formatting.mts'
import { hasDefaultApiToken } from '../../utils/sdk.mts'
import { readOrDefaultSocketJsonUp } from '../../utils/socket-json.mts'
import { socketDashboardLink } from '../../utils/terminal-link.mts'
import { detectManifestActions } from '../manifest/detect-manifest-actions.mts'
import type { REPORT_LEVEL } from './types.mts'
import type { MeowFlags } from '../../flags.mts'
import type { PURL_Type } from '../../utils/ecosystem.mts'
import type {
CliCommandConfig,
CliCommandContext,
} from '../../utils/meow-with-subcommands.mts'
export const CMD_NAME = 'create'
const description = 'Create a new Socket scan and report'
const hidden = false
const generalFlags: MeowFlags = {
...commonFlags,
...outputFlags,
autoManifest: {
type: 'boolean',
description:
'Run `socket manifest auto` before collecting manifest files. This is necessary for languages like Scala, Gradle, and Kotlin, See `socket manifest auto --help`.',
},
branch: {
type: 'string',
default: '',
description: 'Branch name',
shortFlag: 'b',
},
commitHash: {
type: 'string',
default: '',
description: 'Commit hash',
shortFlag: 'ch',
},
commitMessage: {
type: 'string',
default: '',
description: 'Commit message',
shortFlag: 'm',
},
committers: {
type: 'string',
default: '',
description: 'Committers',
shortFlag: 'c',
},
cwd: {
type: 'string',
default: '',
description: 'working directory, defaults to process.cwd()',
},
defaultBranch: {
type: 'boolean',
default: false,
description:
'Set the default branch of the repository to the branch of this full-scan. Should only need to be done once, for example for the "main" or "master" branch.',
},
interactive: {
type: 'boolean',
default: true,
description:
'Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, defaulting them to cancel/no.',
},
pullRequest: {
type: 'number',
default: 0,
description: 'Pull request number',
shortFlag: 'pr',
},
org: {
type: 'string',
default: '',
description:
'Force override the organization slug, overrides the default org from config',
},
reach: {
type: 'boolean',
default: false,
description: 'Run tier 1 full application reachability analysis',
},
readOnly: {
type: 'boolean',
default: false,
description:
'Similar to --dry-run except it can read from remote, stops before it would create an actual report',
},
repo: {
type: 'string',
shortFlag: 'r',
description: 'Repository name',
},
workspace: {
type: 'string',
default: '',
description:
'The workspace in the Socket Organization that the repository is in to associate with the full scan.',
},
report: {
type: 'boolean',
description:
'Wait for the scan creation to complete, then basically run `socket scan report` on it',
},
reportLevel: {
type: 'string',
default: constants.REPORT_LEVEL_ERROR,
description: `Which policy level alerts should be reported (default '${constants.REPORT_LEVEL_ERROR}')`,
},
setAsAlertsPage: {
type: 'boolean',
default: true,
description:
'When true and if this is the "default branch" then this Scan will be the one reflected on your alerts page. See help for details. Defaults to true.',
aliases: ['pendingHead'],
},
tmp: {
type: 'boolean',
default: false,
description:
'Set the visibility (true/false) of the scan in your dashboard.',
shortFlag: 't',
},
}
export const cmdScanCreate = {
description,
hidden,
run,
}
async function run(
argv: string[] | readonly string[],
importMeta: ImportMeta,
{ parentName }: CliCommandContext,
): Promise<void> {
const config: CliCommandConfig = {
commandName: CMD_NAME,
description,
hidden,
flags: {
...generalFlags,
...reachabilityFlags,
},
help: command => `
Usage
$ ${command} [options] [TARGET...]
API Token Requirements
${getFlagApiRequirementsOutput(`${parentName}:${CMD_NAME}`)}
Options
${getFlagListOutput(generalFlags)}
Reachability Options (when --reach is used)
${getFlagListOutput(reachabilityFlags)}
Uploads the specified dependency manifest files for Go, Gradle, JavaScript,
Kotlin, Python, and Scala. Files like "package.json" and "${REQUIREMENTS_TXT}".
If any folder is specified, the ones found in there recursively are uploaded.
Details on TARGET:
- Defaults to the current dir (cwd) if none given
- Multiple targets can be specified
- If a target is a file, only that file is checked
- If it is a dir, the dir is scanned for any supported manifest files
- Dirs MUST be within the current dir (cwd), you can use --cwd to change it
- Supports globbing such as "**/package.json", "**/${REQUIREMENTS_TXT}", etc.
- Ignores any file specified in your project's ".gitignore"
- Also a sensible set of default ignores from the "ignore-by-default" module
The --repo and --branch flags tell Socket to associate this Scan with that
repo/branch. The names will show up on your dashboard on the Socket website.
Note: for a first run you probably want to set --default-branch to indicate
the default branch name, like "main" or "master".
The ${socketDashboardLink('/org/YOURORG/alerts', '"alerts page"')} will show
the results from the last scan designated as the "pending head" on the branch
configured on Socket to be the "default branch". When creating a scan the
--set-as-alerts-page flag will default to true to update this. You can prevent
this by using --no-set-as-alerts-page. This flag is ignored for any branch that
is not designated as the "default branch". It is disabled when using --tmp.
You can use \`socket scan setup\` to configure certain repo flag defaults.
Examples
$ ${command}
$ ${command} ./proj --json
$ ${command} --repo=test-repo --branch=main ./package.json
`,
}
const cli = meowOrExit({
argv,
config,
parentName,
importMeta,
})
const {
commitHash,
commitMessage,
committers,
cwd: cwdOverride,
defaultBranch,
interactive = true,
json,
markdown,
org: orgFlag,
pullRequest,
reach,
reachAnalysisMemoryLimit,
reachAnalysisTimeout,
reachConcurrency,
reachDebug,
reachDetailedAnalysisLogFile,
reachDisableAnalysisSplitting: _reachDisableAnalysisSplitting,
reachDisableAnalytics,
reachDisableExternalToolChecks,
reachEnableAnalysisSplitting,
reachLazyMode,
reachSkipCache,
reachUseOnlyPregeneratedSboms,
reachVersion,
readOnly,
reportLevel,
setAsAlertsPage: pendingHeadFlag,
tmp,
} = cli.flags as {
commitHash: string
commitMessage: string
committers: string
cwd: string
defaultBranch: boolean
interactive: boolean
json: boolean
markdown: boolean
org: string
pullRequest: number
readOnly: boolean
reportLevel: REPORT_LEVEL
setAsAlertsPage: boolean
tmp: boolean
// Reachability flags.
reach: boolean
reachAnalysisMemoryLimit: number
reachAnalysisTimeout: number
reachConcurrency: number
reachDebug: boolean
reachDetailedAnalysisLogFile: boolean
reachDisableAnalysisSplitting: boolean
reachDisableAnalytics: boolean
reachDisableExternalToolChecks: boolean
reachEnableAnalysisSplitting: boolean
reachLazyMode: boolean
reachSkipCache: boolean
reachUseOnlyPregeneratedSboms: boolean
reachVersion: string | undefined
}
// Validate ecosystem values.
const reachEcosystems: PURL_Type[] = []
const reachEcosystemsRaw = cmdFlagValueToArray(cli.flags['reachEcosystems'])
const validEcosystems = getEcosystemChoicesForMeow()
for (const ecosystem of reachEcosystemsRaw) {
if (!validEcosystems.includes(ecosystem)) {
throw new Error(
`Invalid ecosystem: "${ecosystem}". Valid values are: ${joinAnd(validEcosystems)}`,
)
}
reachEcosystems.push(ecosystem as PURL_Type)
}
const dryRun = !!cli.flags['dryRun']
let {
autoManifest,
branch: branchName,
repo: repoName,
report,
workspace,
} = cli.flags as {
autoManifest?: boolean | undefined
branch: string
repo: string
report?: boolean | undefined
workspace: string
}
let { 0: orgSlug } = await determineOrgSlug(
String(orgFlag || ''),
interactive,
dryRun,
)
const processCwd = process.cwd()
const cwd =
cwdOverride && cwdOverride !== '.' && cwdOverride !== processCwd
? path.resolve(processCwd, cwdOverride)
: processCwd
const sockJson = await readOrDefaultSocketJsonUp(cwd)
// Note: This needs meow booleanDefault=undefined.
if (typeof autoManifest !== 'boolean') {
if (sockJson.defaults?.scan?.create?.autoManifest !== undefined) {
autoManifest = sockJson.defaults.scan.create.autoManifest
logger.info(
`Using default --auto-manifest from ${SOCKET_JSON}:`,
autoManifest,
)
} else {
autoManifest = false
}
}
if (!branchName) {
if (sockJson.defaults?.scan?.create?.branch) {
branchName = sockJson.defaults.scan.create.branch
logger.info(`Using default --branch from ${SOCKET_JSON}:`, branchName)
} else {
branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd))
}
}
if (!repoName) {
if (sockJson.defaults?.scan?.create?.repo) {
repoName = sockJson.defaults.scan.create.repo
logger.info(`Using default --repo from ${SOCKET_JSON}:`, repoName)
} else {
repoName = await getRepoName(cwd)
}
}
if (!workspace && sockJson.defaults?.scan?.create?.workspace) {
workspace = sockJson.defaults.scan.create.workspace
logger.info(`Using default --workspace from ${SOCKET_JSON}:`, workspace)
}
if (typeof report !== 'boolean') {
if (sockJson.defaults?.scan?.create?.report !== undefined) {
report = sockJson.defaults.scan.create.report
logger.info(`Using default --report from ${SOCKET_JSON}:`, report)
} else {
report = false
}
}
// If we updated any inputs then we should print the command line to repeat
// the command without requiring user input, as a suggestion.
let updatedInput = false
// Accept zero or more paths. Default to cwd() if none given.
let targets = cli.input.length ? cli.input : []
if (!targets.length && !dryRun && interactive) {
targets = await suggestTarget()
updatedInput = true
}
// Fallback: if targets is still empty after the interactive prompt (e.g. the
// select() prompt silently fails in non-TTY environments like Jenkins CI
// because wrapPrompt swallows non-TypeError errors and returns undefined),
// default to '.' so that downstream validations don't fail with confusing
// "At least one TARGET (missing)" errors.
if (!targets.length && !dryRun) {
targets = ['.']
}
// We're going to need an api token to suggest data because those suggestions
// must come from data we already know. Don't error on missing api token yet.
// If the api-token is not set, ignore it for the sake of suggestions.
const hasApiToken = hasDefaultApiToken()
const outputKind = getOutputKind(json, markdown)
const pendingHead = tmp ? false : pendingHeadFlag
// If the current cwd is unknown and is used as a repo slug anyways, we will
// first need to register the slug before we can use it.
// Only do suggestions with an apiToken and when not in dryRun mode
if (hasApiToken && !dryRun && interactive) {
if (!orgSlug) {
const suggestion = await suggestOrgSlug()
if (suggestion === undefined) {
await outputCreateNewScan(
{
ok: false,
message: 'Canceled by user',
cause: 'Org selector was canceled by user',
},
{
interactive: false,
outputKind,
},
)
return
}
if (suggestion) {
orgSlug = suggestion
}
updatedInput = true
}
}
const detected = await detectManifestActions(sockJson, cwd)
if (detected.count > 0 && !autoManifest) {
logger.info(
`Detected ${detected.count} manifest targets we could try to generate. Please set the --auto-manifest flag if you want to include languages covered by \`socket manifest auto\` in the Scan.`,
)
}
if (updatedInput && orgSlug && targets.length) {
logger.info(
'Note: You can invoke this command next time to skip the interactive questions:',
)
logger.error('```')
logger.error(
` socket scan create [other flags...] ${orgSlug} ${targets.join(' ')}`,
)
logger.error('```')
logger.error('')
logger.info(
`You can also run \`socket scan setup\` to persist these flag defaults to a ${SOCKET_JSON} file.`,
)
logger.error('')
}
const reachExcludePaths = cmdFlagValueToArray(cli.flags['reachExcludePaths'])
// Validation helpers for better readability.
const hasReachEcosystems = reachEcosystems.length > 0
const hasReachExcludePaths = reachExcludePaths.length > 0
const isUsingNonDefaultMemoryLimit =
reachAnalysisMemoryLimit !==
reachabilityFlags['reachAnalysisMemoryLimit']?.default
const isUsingNonDefaultTimeout =
reachAnalysisTimeout !== reachabilityFlags['reachAnalysisTimeout']?.default
const isUsingNonDefaultConcurrency =
reachConcurrency !== reachabilityFlags['reachConcurrency']?.default
const isUsingNonDefaultAnalytics =
reachDisableAnalytics !==
reachabilityFlags['reachDisableAnalytics']?.default
const isUsingNonDefaultVersion =
reachVersion !== reachabilityFlags['reachVersion']?.default
const isUsingAnyReachabilityFlags =
hasReachEcosystems ||
hasReachExcludePaths ||
isUsingNonDefaultAnalytics ||
isUsingNonDefaultConcurrency ||
isUsingNonDefaultMemoryLimit ||
isUsingNonDefaultTimeout ||
isUsingNonDefaultVersion ||
reachEnableAnalysisSplitting ||
reachLazyMode ||
reachSkipCache ||
reachUseOnlyPregeneratedSboms
// Validate target constraints when --reach is enabled.
const reachTargetValidation = reach
? await validateReachabilityTarget(targets, cwd)
: {
isDirectory: false,
isInsideCwd: false,
isValid: true,
targetExists: false,
}
const wasValidInput = checkCommandInput(
outputKind,
{
nook: true,
test: !!orgSlug,
message: 'Org name by default setting, --org, or auto-discovered',
fail: 'missing',
},
{
test: !!targets.length,
message: 'At least one TARGET (e.g. `.` or `./package.json`)',
fail: 'missing',
},
{
nook: true,
test: !json || !markdown,
message: 'The json and markdown flags cannot be both set, pick one',
fail: 'omit one',
},
{
nook: true,
test: dryRun || hasApiToken,
message: 'This command requires a Socket API token for access',
fail: 'try `socket login`',
},
{
nook: true,
test: !defaultBranch || !!branchName,
message: 'When --default-branch is set, --branch is mandatory',
fail: 'missing branch name',
},
{
nook: true,
test: !pendingHead || !!branchName,
message: 'When --pending-head is set, --branch is mandatory',
fail: 'missing branch name',
},
{
nook: true,
test: reach || !isUsingAnyReachabilityFlags,
message: 'Reachability analysis flags require --reach to be enabled',
fail: 'add --reach flag to use --reach-* options',
},
{
nook: true,
test: !reach || reachTargetValidation.isValid,
message:
'Reachability analysis requires exactly one target directory when --reach is enabled',
fail: 'provide exactly one directory path',
},
{
nook: true,
test: !reach || reachTargetValidation.isDirectory,
message:
'Reachability analysis target must be a directory when --reach is enabled',
fail: 'provide a directory path, not a file',
},
{
nook: true,
test: !reach || reachTargetValidation.targetExists,
message: 'Target directory must exist when --reach is enabled',
fail: 'provide an existing directory path',
},
{
nook: true,
test: !reach || reachTargetValidation.isInsideCwd,
message:
'Target directory must be inside the current working directory when --reach is enabled',
fail: 'provide a path inside the working directory',
},
)
if (!wasValidInput) {
return
}
if (dryRun) {
logger.log(constants.DRY_RUN_BAILING_NOW)
return
}
await handleCreateNewScan({
autoManifest: Boolean(autoManifest),
branchName: branchName as string,
commitHash: (commitHash && String(commitHash)) || '',
commitMessage: (commitMessage && String(commitMessage)) || '',
committers: (committers && String(committers)) || '',
cwd,
defaultBranch: Boolean(defaultBranch),
interactive: Boolean(interactive),
orgSlug,
outputKind,
pendingHead: Boolean(pendingHead),
pullRequest: Number(pullRequest),
reach: {
reachAnalysisMemoryLimit: Number(reachAnalysisMemoryLimit),
reachAnalysisTimeout: Number(reachAnalysisTimeout),
reachConcurrency: Number(reachConcurrency),
reachDebug: Boolean(reachDebug),
reachDetailedAnalysisLogFile: Boolean(reachDetailedAnalysisLogFile),
reachDisableAnalytics: Boolean(reachDisableAnalytics),
reachDisableExternalToolChecks: Boolean(reachDisableExternalToolChecks),
reachEcosystems,
reachEnableAnalysisSplitting: Boolean(reachEnableAnalysisSplitting),
reachExcludePaths,
reachLazyMode: Boolean(reachLazyMode),
reachSkipCache: Boolean(reachSkipCache),
reachUseOnlyPregeneratedSboms: Boolean(reachUseOnlyPregeneratedSboms),
reachVersion,
runReachabilityAnalysis: Boolean(reach),
},
readOnly: Boolean(readOnly),
repoName,
report,
reportLevel,
targets,
tmp: Boolean(tmp),
workspace: (workspace && String(workspace)) || '',
})
}