-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathperform-reachability-analysis.mts
More file actions
262 lines (233 loc) · 8.17 KB
/
perform-reachability-analysis.mts
File metadata and controls
262 lines (233 loc) · 8.17 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
import path from 'node:path'
import { logger } from '@socketsecurity/registry/lib/logger'
import constants from '../../constants.mts'
import { handleApiCall } from '../../utils/api.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 { PURL_Type } from '../../utils/ecosystem.mts'
import type { Spinner } from '@socketsecurity/registry/lib/spinner'
export type ReachabilityOptions = {
reachAnalysisMemoryLimit: number
reachAnalysisTimeout: number
reachConcurrency: number
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
// Exclude any .socket.facts.json files that happen to be in the scan
// folder before the analysis was run.
const filepathsToUpload = packagePaths.filter(
p =>
path.basename(p).toLowerCase() !== constants.DOT_SOCKET_DOT_FACTS_JSON,
)
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
const uploadCResult = await handleApiCall(
sockSdk.uploadManifestFiles(
orgSlug,
filepathsToUpload,
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
// 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.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']
: []),
]
// 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
}
// 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
}
return {
ok: true,
data: {
// Use the actual output filename for the scan.
reachabilityReport: outputFilePath,
tier1ReachabilityScanId: extractTier1ReachabilityScanId(outputFilePath),
},
}
}