-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathhandle-create-new-scan.mts
More file actions
260 lines (230 loc) · 6.92 KB
/
handle-create-new-scan.mts
File metadata and controls
260 lines (230 loc) · 6.92 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
import path from 'node:path'
import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug'
import { logger } from '@socketsecurity/registry/lib/logger'
import { pluralize } from '@socketsecurity/registry/lib/words'
import { fetchCreateOrgFullScan } from './fetch-create-org-full-scan.mts'
import { fetchSupportedScanFileNames } from './fetch-supported-scan-file-names.mts'
import { finalizeTier1Scan } from './finalize-tier1-scan.mts'
import { handleScanReport } from './handle-scan-report.mts'
import { outputCreateNewScan } from './output-create-new-scan.mts'
import { performReachabilityAnalysis } from './perform-reachability-analysis.mts'
import constants from '../../constants.mts'
import { checkCommandInput } from '../../utils/check-input.mts'
import { getPackageFilesForScan } from '../../utils/path-resolve.mts'
import { readOrDefaultSocketJson } from '../../utils/socket-json.mts'
import { socketDocsLink } from '../../utils/terminal-link.mts'
import { detectManifestActions } from '../manifest/detect-manifest-actions.mts'
import { generateAutoManifest } from '../manifest/generate_auto_manifest.mts'
import type { ReachabilityOptions } from './perform-reachability-analysis.mts'
import type { REPORT_LEVEL } from './types.mts'
import type { OutputKind } from '../../types.mts'
import type { Remap } from '@socketsecurity/registry/lib/objects'
export type HandleCreateNewScanConfig = {
autoManifest: boolean
branchName: string
commitHash: string
commitMessage: string
committers: string
cwd: string
defaultBranch: boolean
interactive: boolean
orgSlug: string
pendingHead: boolean
pullRequest: number
outputKind: OutputKind
reach: Remap<
ReachabilityOptions & {
runReachabilityAnalysis: boolean
}
>
readOnly: boolean
repoName: string
report: boolean
reportLevel: REPORT_LEVEL
targets: string[]
tmp: boolean
}
export async function handleCreateNewScan({
autoManifest,
branchName,
commitHash,
commitMessage,
committers,
cwd,
defaultBranch,
interactive,
orgSlug,
outputKind,
pendingHead,
pullRequest,
reach,
readOnly,
repoName,
report,
reportLevel,
targets,
tmp,
}: HandleCreateNewScanConfig): Promise<void> {
debugFn('notice', `Creating new scan for ${orgSlug}/${repoName}`)
debugDir('inspect', {
autoManifest,
branchName,
commitHash,
defaultBranch,
interactive,
pendingHead,
pullRequest,
readOnly,
report,
reportLevel,
targets,
tmp,
})
if (autoManifest) {
logger.info('Auto-generating manifest files ...')
debugFn('notice', 'Auto-manifest mode enabled')
const sockJson = readOrDefaultSocketJson(cwd)
const detected = await detectManifestActions(sockJson, cwd)
debugDir('inspect', { detected })
await generateAutoManifest({
detected,
cwd,
outputKind,
verbose: false,
})
logger.info('Auto-generation finished. Proceeding with Scan creation.')
}
const { spinner } = constants
const supportedFilesCResult = await fetchSupportedScanFileNames({ spinner })
if (!supportedFilesCResult.ok) {
debugFn('warn', 'Failed to fetch supported scan file names')
debugDir('inspect', { supportedFilesCResult })
await outputCreateNewScan(supportedFilesCResult, {
interactive,
outputKind,
})
return
}
debugFn(
'notice',
`Fetched ${supportedFilesCResult.data['size']} supported file types`,
)
spinner.start('Searching for local files to include in scan...')
const supportedFiles = supportedFilesCResult.data
const packagePaths = await getPackageFilesForScan(targets, supportedFiles, {
cwd,
})
spinner.successAndStop(
`Found ${packagePaths.length} ${pluralize('file', packagePaths.length)} to include in scan.`,
)
const wasValidInput = checkCommandInput(outputKind, {
nook: true,
test: packagePaths.length > 0,
fail: `found no eligible files to scan. See supported manifest files at ${socketDocsLink('/docs/manifest-file-detection-in-socket', 'docs.socket.dev')}`,
message:
'TARGET (file/dir) must contain matching / supported file types for a scan',
})
if (!wasValidInput) {
debugFn('warn', 'No eligible files found to scan')
return
}
logger.success(
`Found ${packagePaths.length} local ${pluralize('file', packagePaths.length)}`,
)
debugDir('inspect', { packagePaths })
if (readOnly) {
logger.log('[ReadOnly] Bailing now')
debugFn('notice', 'Read-only mode, exiting early')
return
}
let scanPaths: string[] = packagePaths
let tier1ReachabilityScanId: string | undefined
// If reachability is enabled, perform reachability analysis.
if (reach.runReachabilityAnalysis) {
logger.error('')
logger.info('Starting reachability analysis...')
debugFn('notice', 'Reachability analysis enabled')
debugDir('inspect', { reachabilityOptions: reach })
spinner.start()
const reachResult = await performReachabilityAnalysis({
branchName,
cwd,
orgSlug,
packagePaths,
reachabilityOptions: reach,
repoName,
spinner,
target: targets[0]!,
})
spinner.stop()
if (!reachResult.ok) {
await outputCreateNewScan(reachResult, { interactive, outputKind })
return
}
logger.success('Reachability analysis completed successfully')
const reachabilityReport = reachResult.data?.reachabilityReport
scanPaths = [
...packagePaths.filter(
// Ensure the .socket.facts.json isn't duplicated in case it happened
// to be in the scan folder before the analysis was run.
p =>
path.basename(p).toLowerCase() !==
constants.DOT_SOCKET_DOT_FACTS_JSON,
),
...(reachabilityReport ? [reachabilityReport] : []),
]
tier1ReachabilityScanId = reachResult.data?.tier1ReachabilityScanId
}
const fullScanCResult = await fetchCreateOrgFullScan(
scanPaths,
orgSlug,
{
commitHash,
commitMessage,
committers,
pullRequest,
repoName,
branchName,
},
{
cwd,
defaultBranch,
pendingHead,
tmp,
},
)
const scanId = fullScanCResult.ok ? fullScanCResult.data?.id : undefined
if (reach && scanId && tier1ReachabilityScanId) {
await finalizeTier1Scan(tier1ReachabilityScanId, scanId)
}
if (report && fullScanCResult.ok) {
if (scanId) {
await handleScanReport({
filepath: '-',
fold: constants.FOLD_SETTING_VERSION,
includeLicensePolicy: true,
orgSlug,
outputKind,
reportLevel,
scanId,
short: false,
})
} else {
await outputCreateNewScan(
{
ok: false,
message: 'Missing Scan ID',
cause: 'Server did not respond with a scan ID',
data: fullScanCResult.data,
},
{
interactive,
outputKind,
},
)
}
} else {
spinner.stop()
await outputCreateNewScan(fullScanCResult, { interactive, outputKind })
}
}