-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathperform-reachability-analysis.mts
More file actions
328 lines (297 loc) · 11.1 KB
/
Copy pathperform-reachability-analysis.mts
File metadata and controls
328 lines (297 loc) · 11.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
import { randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { logger } from '@socketsecurity/registry/lib/logger'
import constants from '../../constants.mts'
import { handleApiCall } from '../../utils/api.mts'
import { isAutoManifestConfigEmpty } from '../../utils/auto-manifest-config.mts'
import { extractTier1ReachabilityScanId } from '../../utils/coana.mts'
import { spawnCoanaDlx } from '../../utils/dlx.mts'
import { hasEnterpriseOrgPlan } from '../../utils/organization.mts'
import { setupSdk } from '../../utils/sdk.mts'
import { socketDevLink } from '../../utils/terminal-link.mts'
import { fetchOrganization } from '../organization/fetch-organization-list.mts'
import type { CResult } from '../../types.mts'
import type { AutoManifestConfig } from '../../utils/auto-manifest-config.mts'
import type { PURL_Type } from '../../utils/ecosystem.mts'
import type { Spinner } from '@socketsecurity/registry/lib/spinner'
export type ReachabilityOptions = {
autoManifestConfig?: AutoManifestConfig | undefined
excludePaths: string[]
reachAnalysisMemoryLimit: number
reachAnalysisTimeout: number
reachConcurrency: number
reachContinueOnAnalysisErrors: boolean
reachContinueOnInstallErrors: boolean
reachContinueOnMissingLockFiles: boolean
reachContinueOnNoSourceFiles: boolean
reachDebug: boolean
reachDetailedAnalysisLogFile: boolean
reachDisableExternalToolChecks: boolean
reachDisableAnalytics: boolean
reachEcosystems: PURL_Type[]
reachEnableAnalysisSplitting: boolean
reachExcludePaths: string[]
reachLazyMode: boolean
reachSkipCache: boolean
reachUseOnlyPregeneratedSboms: boolean
reachVersion: string | undefined
}
export type ReachabilityAnalysisOptions = {
branchName?: string | undefined
cwd?: string | undefined
orgSlug?: string | undefined
outputPath?: string | undefined
packagePaths?: string[] | undefined
reachabilityOptions: ReachabilityOptions
repoName?: string | undefined
spinner?: Spinner | undefined
target: string
uploadManifests?: boolean | undefined
}
export type ReachabilityAnalysisResult = {
reachabilityReport: string
tier1ReachabilityScanId: string | undefined
}
export async function performReachabilityAnalysis(
options?: ReachabilityAnalysisOptions | undefined,
): Promise<CResult<ReachabilityAnalysisResult>> {
const {
branchName,
cwd = process.cwd(),
orgSlug,
outputPath,
packagePaths,
reachabilityOptions,
repoName,
spinner,
target,
uploadManifests = true,
} = { __proto__: null, ...options } as ReachabilityAnalysisOptions
// Determine the analysis target - make it relative to cwd if absolute.
let analysisTarget = target
if (path.isAbsolute(analysisTarget)) {
analysisTarget = path.relative(cwd, analysisTarget) || '.'
}
// Check if user has enterprise plan for reachability analysis.
const orgsCResult = await fetchOrganization()
if (!orgsCResult.ok) {
const httpCode = (orgsCResult.data as { code?: number } | undefined)?.code
if (httpCode === constants.HTTP_STATUS_UNAUTHORIZED) {
return {
ok: false,
message: 'Authentication failed',
cause:
'Your API token appears to be invalid, expired, or revoked. Please check your token and try again.',
}
}
return {
ok: false,
message: 'Unable to verify plan permissions',
cause:
'Failed to fetch organization information to verify enterprise plan access',
}
}
const { organizations } = orgsCResult.data
if (!hasEnterpriseOrgPlan(organizations)) {
return {
ok: false,
message: 'Tier 1 Reachability analysis requires an enterprise plan',
cause: `Please ${socketDevLink('upgrade your plan', '/pricing')}. This feature is only available for organizations with an enterprise plan.`,
}
}
const wasSpinning = !!spinner?.isSpinning
let tarHash: string | undefined
if (uploadManifests && orgSlug && packagePaths) {
// Setup SDK for uploading manifests
const sockSdkCResult = await setupSdk()
if (!sockSdkCResult.ok) {
return sockSdkCResult
}
const sockSdk = sockSdkCResult.data
spinner?.start('Uploading manifests for reachability analysis...')
// Ensure uploaded manifest files are relative to analysis target as coana resolves SBOM manifest files relative to this path
// NOTE: previously stripped any `.socket.facts.json` from packagePaths
// here to avoid uploading leftover post-reachability output. With the
// producer flow (`socket manifest gradle --facts`) those files are
// legitimate INPUT to compute-artifacts, so we now upload them. Stale
// facts files are cleaned up downstream — see the post-success
// deletion in handle-create-new-scan.mts.
const uploadCResult = await handleApiCall(
sockSdk.uploadManifestFiles(
orgSlug,
packagePaths,
path.resolve(cwd, analysisTarget),
),
{
description: 'upload manifests',
spinner,
},
)
spinner?.stop()
if (!uploadCResult.ok) {
if (wasSpinning) {
spinner.start()
}
return uploadCResult
}
tarHash = (uploadCResult.data as { tarHash?: string })?.tarHash
if (!tarHash) {
if (wasSpinning) {
spinner.start()
}
return {
ok: false,
message: 'Failed to get manifest tar hash',
cause: 'Server did not return a tar hash for the uploaded manifests',
}
}
spinner?.start()
spinner?.success(`Manifests uploaded successfully. Tar hash: ${tarHash}`)
}
spinner?.start()
spinner?.infoAndStop('Running reachability analysis with Coana...')
const outputFilePath = outputPath || constants.DOT_SOCKET_DOT_FACTS_JSON
// Coana reads `--auto-manifest-config` from a JSON file, so write the resolved
// per-ecosystem build-tool config (mapped from socket.json) to a temp file and
// pass its absolute path. Cleaned up in the finally below.
let autoManifestConfigPath: string | undefined
const { autoManifestConfig } = reachabilityOptions
if (autoManifestConfig && !isAutoManifestConfigEmpty(autoManifestConfig)) {
autoManifestConfigPath = path.join(
tmpdir(),
`socket-auto-manifest-config-${randomUUID()}.json`,
)
await fs.writeFile(
autoManifestConfigPath,
JSON.stringify(autoManifestConfig),
'utf8',
)
}
// Build Coana arguments.
const coanaArgs = [
'run',
analysisTarget,
'--output-dir',
path.dirname(outputFilePath),
'--socket-mode',
outputFilePath,
'--disable-report-submission',
...(reachabilityOptions.reachAnalysisTimeout
? ['--analysis-timeout', `${reachabilityOptions.reachAnalysisTimeout}`]
: []),
...(reachabilityOptions.reachAnalysisMemoryLimit
? ['--memory-limit', `${reachabilityOptions.reachAnalysisMemoryLimit}`]
: []),
...(reachabilityOptions.reachConcurrency
? ['--concurrency', `${reachabilityOptions.reachConcurrency}`]
: []),
...(reachabilityOptions.reachContinueOnAnalysisErrors
? ['--reach-continue-on-analysis-errors']
: []),
...(reachabilityOptions.reachContinueOnInstallErrors
? ['--reach-continue-on-install-errors']
: []),
...(reachabilityOptions.reachContinueOnMissingLockFiles
? ['--reach-continue-on-missing-lock-files']
: []),
...(reachabilityOptions.reachContinueOnNoSourceFiles
? ['--reach-continue-on-no-source-files']
: []),
...(reachabilityOptions.reachDebug ? ['--debug'] : []),
...(reachabilityOptions.reachDetailedAnalysisLogFile
? ['--print-analysis-log-file']
: []),
...(reachabilityOptions.reachDisableAnalytics
? ['--disable-analytics-sharing']
: []),
...(reachabilityOptions.reachDisableExternalToolChecks
? ['--disable-external-tool-checks']
: []),
...(reachabilityOptions.reachEnableAnalysisSplitting
? []
: ['--disable-analysis-splitting']),
...(tarHash
? ['--run-without-docker', '--manifests-tar-hash', tarHash]
: []),
// Empty reachEcosystems implies scanning all ecosystems.
...(reachabilityOptions.reachEcosystems.length
? ['--purl-types', ...reachabilityOptions.reachEcosystems]
: []),
...(reachabilityOptions.reachExcludePaths.length
? ['--exclude-dirs', ...reachabilityOptions.reachExcludePaths]
: []),
...(reachabilityOptions.reachLazyMode ? ['--lazy-mode'] : []),
...(reachabilityOptions.reachSkipCache ? ['--skip-cache-usage'] : []),
...(reachabilityOptions.reachUseOnlyPregeneratedSboms
? ['--use-only-pregenerated-sboms']
: []),
// Hand the per-ecosystem build-tool config (mapped from socket.json) to
// Coana's reach-time resolution, as a temp JSON file path.
...(autoManifestConfigPath
? ['--auto-manifest-config', autoManifestConfigPath]
: []),
]
// Build environment variables.
const coanaEnv: Record<string, string> = {}
// do not pass default repo and branch name to coana to avoid mixing
// buckets (cached configuration) from projects that are likely very different.
if (repoName && repoName !== constants.SOCKET_DEFAULT_REPOSITORY) {
coanaEnv['SOCKET_REPO_NAME'] = repoName
}
if (branchName && branchName !== constants.SOCKET_DEFAULT_BRANCH) {
coanaEnv['SOCKET_BRANCH_NAME'] = branchName
}
try {
// Run Coana with the manifests tar hash.
const coanaResult = await spawnCoanaDlx(coanaArgs, orgSlug, {
coanaVersion: reachabilityOptions.reachVersion,
cwd,
env: coanaEnv,
spinner,
stdio: 'inherit',
})
if (wasSpinning) {
spinner.start()
}
if (!coanaResult.ok) {
const coanaVersion =
reachabilityOptions.reachVersion ||
constants.ENV.INLINED_SOCKET_CLI_COANA_TECH_CLI_VERSION
logger.error(
`Coana reachability analysis failed. Version: ${coanaVersion}, target: ${analysisTarget}, cwd: ${cwd}`,
)
if (coanaResult.message) {
logger.error(`Details: ${coanaResult.message}`)
}
return coanaResult
}
// Coana writes the facts file relative to the scan `cwd` (it is spawned
// with `cwd` above), so resolve the read path against `cwd` too. Reading
// the bare relative path would resolve against `process.cwd()` and miss
// the file whenever `cwd !== process.cwd()` (e.g. `--cwd <dir>`), silently
// dropping the tier 1 scan id and skipping finalize downstream.
const resolvedReportPath = path.resolve(cwd, outputFilePath)
return {
ok: true,
data: {
// Use the actual output filename for the scan. Keep this `cwd`-relative
// so the upload (which relativizes against `cwd`) and the post-success
// unlink (`path.resolve(cwd, reachabilityReport)`) keep working.
reachabilityReport: outputFilePath,
tier1ReachabilityScanId:
extractTier1ReachabilityScanId(resolvedReportPath),
},
}
} finally {
// The run no longer needs the temp config file; best-effort cleanup.
if (autoManifestConfigPath) {
try {
await fs.unlink(autoManifestConfigPath)
} catch {
// File may already be gone or unwritable.
}
}
}
}