-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathfetch-report-data.mts
More file actions
203 lines (178 loc) · 5.5 KB
/
Copy pathfetch-report-data.mts
File metadata and controls
203 lines (178 loc) · 5.5 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
import { debug, debugDir } from '@socketsecurity/lib-stable/debug/output'
import { getDefaultLogger } from '@socketsecurity/lib-stable/logger/default'
import { getDefaultSpinner } from '@socketsecurity/lib-stable/spinner/default'
import { formatErrorWithDetail } from '../../util/error/errors.mjs'
import {
handleApiCallNoSpinner,
queryApiSafeText,
} from '../../util/socket/api.mjs'
import { setupSdk } from '../../util/socket/sdk.mjs'
import type { CResult } from '../../types.mts'
import type { SocketArtifact } from '../../util/alert/artifact.mts'
import type { SetupSdkOptions } from '../../util/socket/sdk.mjs'
import type { SocketSdkSuccessResult } from '@socketsecurity/sdk-stable'
const logger = getDefaultLogger()
export type FetchScanData = {
includeLicensePolicy?: boolean | undefined
sdkOpts?: SetupSdkOptions | undefined
}
/**
* This fetches all the relevant pieces of data to generate a report, given a
* full scan ID.
*/
export async function fetchScanData(
orgSlug: string,
scanId: string,
options?: FetchScanData | undefined,
): Promise<
CResult<{
scan: SocketArtifact[]
securityPolicy: SocketSdkSuccessResult<'getOrgSecurityPolicy'>['data']
}>
> {
const { includeLicensePolicy, sdkOpts } = {
__proto__: null,
...options,
} as FetchScanData
const spinner = getDefaultSpinner()
const sockSdkCResult = await setupSdk(sdkOpts)
if (!sockSdkCResult.ok) {
return sockSdkCResult
}
const sockSdk = sockSdkCResult.data
let policyStatus = 'requested…'
let scanStatus = 'requested…'
let finishedFetching = false
function updateScan(status: string) {
scanStatus = status
updateProgress()
}
function updatePolicy(status: string) {
policyStatus = status
updateProgress()
}
function updateProgress() {
if (finishedFetching) {
spinner.stop()
logger.info(
`Scan result: ${scanStatus}. Security policy: ${policyStatus}.`,
)
} else {
spinner.start(
`Scan result: ${scanStatus}. Security policy: ${policyStatus}.`,
)
}
}
async function fetchScanResult(): Promise<CResult<SocketArtifact[]>> {
const result = await queryApiSafeText(
`orgs/${orgSlug}/full-scans/${encodeURIComponent(scanId)}${includeLicensePolicy ? '?include_license_details=true' : ''}`,
)
updateScan('response received')
if (!result.ok) {
return result
}
const ndJsonString = result.data
// This is nd-json; each line is a json object.
const lines = ndJsonString.split(/\r?\n/).filter(Boolean)
const data: SocketArtifact[] = []
for (let i = 0, { length } = lines; i < length; i += 1) {
const line = lines[i]!
try {
data.push(JSON.parse(line))
} catch (e) {
debug('Failed to parse report data line as JSON')
debugDir({ error: e, line })
updateScan('received invalid JSON response')
return {
__proto__: null,
ok: false,
message: 'Invalid Socket API response',
cause:
'The Socket API responded with at least one line that was not valid JSON. Please report if this persists.',
}
}
}
updateScan('success')
return { __proto__: null, ok: true, data }
}
async function fetchSecurityPolicy(): Promise<
CResult<SocketSdkSuccessResult<'getOrgSecurityPolicy'>['data']>
> {
const result = (await handleApiCallNoSpinner(
sockSdk.getOrgSecurityPolicy(orgSlug),
'GetOrgSecurityPolicy',
)) as CResult<SocketSdkSuccessResult<'getOrgSecurityPolicy'>['data']>
updatePolicy('received policy')
return result
}
updateProgress()
const results = await Promise.allSettled([
fetchScanResult().catch(e => {
updateScan('failure; unknown blocking error occurred')
return {
__proto__: null,
ok: false as const,
message: 'Socket API error',
cause:
formatErrorWithDetail('Error requesting scan', e) ||
'Error requesting scan: (no error message found)',
}
}),
fetchSecurityPolicy().catch(e => {
updatePolicy('failure; unknown blocking error occurred')
return {
__proto__: null,
ok: false as const,
message: 'Socket API error',
cause:
formatErrorWithDetail('Error requesting policy', e) ||
'Error requesting policy: (no error message found)',
}
}),
]).finally(() => {
finishedFetching = true
updateProgress()
})
const scan: CResult<SocketArtifact[]> =
results[0].status === 'fulfilled'
? results[0].value
: {
ok: false as const,
message: 'Unexpected error',
cause: 'Promise rejected unexpectedly',
}
const securityPolicy: CResult<
SocketSdkSuccessResult<'getOrgSecurityPolicy'>['data']
> =
results[1].status === 'fulfilled'
? results[1].value
: {
ok: false as const,
message: 'Unexpected error',
cause: 'Promise rejected unexpectedly',
}
if (!scan.ok) {
return scan
}
if (!securityPolicy.ok) {
return securityPolicy
}
/* c8 ignore start - defensive: scan.data is always SocketArtifact[] from the loop above */
if (!Array.isArray(scan.data)) {
return {
__proto__: null,
ok: false,
message: 'Failed to fetch',
cause: 'Was unable to fetch scan result, bailing',
}
}
/* c8 ignore stop */
return {
__proto__: null,
ok: true,
data: {
scan: scan.data satisfies SocketArtifact[],
securityPolicy: securityPolicy.data,
},
}
}