-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathapi.mts
More file actions
538 lines (484 loc) · 14.9 KB
/
api.mts
File metadata and controls
538 lines (484 loc) · 14.9 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
/**
* API utilities for Socket CLI.
* Provides consistent API communication with error handling and permissions management.
*
* Key Functions:
* - getDefaultApiBaseUrl: Get configured API endpoint
* - getErrorMessageForHttpStatusCode: User-friendly HTTP error messages
* - handleApiCall: Execute Socket SDK API calls with error handling
* - handleApiCallNoSpinner: Execute API calls without UI spinner
* - queryApi: Execute raw API queries with text response
*
* Error Handling:
* - Automatic permission requirement logging for 403 errors
* - Detailed error messages for common HTTP status codes
* - Integration with debug helpers for API response logging
*
* Configuration:
* - Respects SOCKET_CLI_API_BASE_URL environment variable
* - Falls back to configured apiBaseUrl or default API_V0_URL
*/
import { messageWithCauses } from 'pony-cause'
import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug'
import { logger } from '@socketsecurity/registry/lib/logger'
import { isNonEmptyString } from '@socketsecurity/registry/lib/strings'
import { getConfigValueOrUndef } from './config.mts'
import { debugApiRequest, debugApiResponse } from './debug.mts'
import constants, {
CONFIG_KEY_API_BASE_URL,
EMPTY_VALUE,
HTTP_STATUS_BAD_REQUEST,
HTTP_STATUS_FORBIDDEN,
HTTP_STATUS_INTERNAL_SERVER_ERROR,
HTTP_STATUS_NOT_FOUND,
HTTP_STATUS_UNAUTHORIZED,
} from '../constants.mts'
import { getRequirements, getRequirementsKey } from './requirements.mts'
import { getDefaultApiToken } from './sdk.mts'
import type { CResult } from '../types.mts'
import type { Spinner } from '@socketsecurity/registry/lib/spinner'
import type {
SocketSdkErrorResult,
SocketSdkOperations,
SocketSdkResult,
SocketSdkSuccessResult,
} from '@socketsecurity/sdk'
const NO_ERROR_MESSAGE = 'No error message returned'
export type CommandRequirements = {
permissions?: string[] | undefined
quota?: number | undefined
}
/**
* Get command requirements from requirements.json based on command path.
*/
function getCommandRequirements(
cmdPath?: string | undefined,
): CommandRequirements | undefined {
if (!cmdPath) {
return undefined
}
const requirements = getRequirements()
const key = getRequirementsKey(cmdPath)
return (requirements.api as any)[key] || undefined
}
/**
* Log required permissions for a command when encountering 403 errors.
*/
function logPermissionsFor403(cmdPath?: string | undefined): void {
const requirements = getCommandRequirements(cmdPath)
if (!requirements?.permissions?.length) {
return
}
logger.error('This command requires the following API permissions:')
for (const permission of requirements.permissions) {
logger.error(` - ${permission}`)
}
logger.error('Please ensure your API token has the required permissions.')
}
// The Socket API server that should be used for operations.
export function getDefaultApiBaseUrl(): string | undefined {
const baseUrl =
constants.ENV.SOCKET_CLI_API_BASE_URL ||
getConfigValueOrUndef(CONFIG_KEY_API_BASE_URL)
if (isNonEmptyString(baseUrl)) {
return baseUrl
}
const API_V0_URL = constants.API_V0_URL
return API_V0_URL
}
/**
* Get user-friendly error message for HTTP status codes.
*/
export async function getErrorMessageForHttpStatusCode(code: number) {
if (code === HTTP_STATUS_BAD_REQUEST) {
return 'One of the options passed might be incorrect'
}
if (code === HTTP_STATUS_FORBIDDEN || code === HTTP_STATUS_UNAUTHORIZED) {
return 'Your Socket API token may not have the required permissions for this command or you might be trying to access (data from) an organization that is not linked to the API token you are logged in with'
}
if (code === HTTP_STATUS_NOT_FOUND) {
return 'The requested Socket API endpoint was not found (404) or there was no result for the requested parameters. If unexpected, this could be a temporary problem caused by an incident or a bug in the CLI. If the problem persists please let us know.'
}
if (code === HTTP_STATUS_INTERNAL_SERVER_ERROR) {
return 'There was an unknown server side problem with your request. This ought to be temporary. Please let us know if this problem persists.'
}
return `Server responded with status code ${code}`
}
export type HandleApiCallOptions = {
description?: string | undefined
spinner?: Spinner | undefined
silence?: boolean | undefined
commandPath?: string | undefined
}
export type ApiCallResult<T extends SocketSdkOperations> = CResult<
SocketSdkSuccessResult<T>['data']
>
/**
* Handle Socket SDK API calls with error handling and permission logging.
*/
export async function handleApiCall<T extends SocketSdkOperations>(
value: Promise<SocketSdkResult<T>>,
options?: HandleApiCallOptions | undefined,
): Promise<ApiCallResult<T>> {
const {
commandPath,
description,
silence = false,
spinner,
} = {
__proto__: null,
...options,
} as HandleApiCallOptions
if (!silence) {
if (description) {
spinner?.start(`Requesting ${description} from API...`)
} else {
spinner?.start()
}
}
let sdkResult: SocketSdkResult<T>
try {
sdkResult = await value
if (!silence) {
spinner?.stop()
}
// Only log the message if spinner is provided (silence mode passes undefined).
if (description && !silence) {
const message = `Received Socket API response (after requesting ${description}).`
if (!silence) {
if (sdkResult.success) {
logger.success(message)
} else {
logger.info(message)
}
}
}
} catch (e) {
spinner?.stop()
const socketSdkErrorResult: ApiCallResult<T> = {
ok: false,
message: 'Socket API error',
cause: messageWithCauses(e as Error),
}
// Only log the message if spinner is provided (silence mode passes undefined).
if (description && !silence) {
logger.fail(`An error was thrown while requesting ${description}`)
}
debugDir('inspect', { socketSdkErrorResult })
return socketSdkErrorResult
}
// Note: TS can't narrow down the type of result due to generics.
if (sdkResult.success === false) {
const endpoint = description || 'Socket API'
debugApiResponse('API', endpoint, sdkResult.status as number)
debugDir('inspect', { sdkResult })
const errCResult = sdkResult as SocketSdkErrorResult<T>
const errStr = errCResult.error ? String(errCResult.error).trim() : ''
const message = errStr || NO_ERROR_MESSAGE
const reason = errCResult.cause || NO_ERROR_MESSAGE
const cause =
reason && message !== reason ? `${message} (reason: ${reason})` : message
const socketSdkErrorResult: ApiCallResult<T> = {
ok: false,
message: 'Socket API error',
cause,
data: {
code: sdkResult.status,
},
}
// Log required permissions for 403 errors when in a command context.
if (commandPath && sdkResult.status === 403) {
logPermissionsFor403(commandPath)
}
return socketSdkErrorResult
}
const socketSdkSuccessResult: ApiCallResult<T> = {
ok: true,
data: (sdkResult as SocketSdkSuccessResult<T>).data,
}
return socketSdkSuccessResult
}
export async function handleApiCallNoSpinner<T extends SocketSdkOperations>(
value: Promise<SocketSdkResult<T>>,
description: string,
): Promise<CResult<SocketSdkSuccessResult<T>['data']>> {
let sdkResult: SocketSdkResult<T>
try {
sdkResult = await value
} catch (e) {
debugFn('error', `API request failed: ${description}`)
debugDir('error', e)
const errStr = e ? String(e).trim() : ''
const message = 'Socket API error'
const rawCause = errStr || NO_ERROR_MESSAGE
const cause = message !== rawCause ? rawCause : ''
return {
ok: false,
message,
...(cause ? { cause } : {}),
}
}
// Note: TS can't narrow down the type of result due to generics
if (sdkResult.success === false) {
debugFn('error', `fail: ${description} bad response`)
debugDir('inspect', { sdkResult })
const sdkErrorResult = sdkResult as SocketSdkErrorResult<T>
const errStr = sdkErrorResult.error
? String(sdkErrorResult.error).trim()
: ''
const message = errStr || NO_ERROR_MESSAGE
const reason = sdkErrorResult.cause || NO_ERROR_MESSAGE
const cause =
reason && message !== reason ? `${message} (reason: ${reason})` : message
return {
ok: false,
message: 'Socket API error',
cause,
data: {
code: sdkResult.status,
},
}
} else {
const sdkSuccessResult = sdkResult as SocketSdkSuccessResult<T>
return {
ok: true,
data: sdkSuccessResult.data,
}
}
}
async function queryApi(path: string, apiToken: string) {
const baseUrl = getDefaultApiBaseUrl()
if (!baseUrl) {
throw new Error('Socket API base URL is not configured.')
}
const url = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`
const result = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
},
})
return result
}
/**
* Query Socket API endpoint and return text response with error handling.
*/
export async function queryApiSafeText(
path: string,
description?: string | undefined,
commandPath?: string | undefined,
): Promise<CResult<string>> {
const apiToken = getDefaultApiToken()
if (!apiToken) {
return {
ok: false,
message: 'Authentication Error',
cause:
'User must be authenticated to run this command. Run `socket login` and enter your Socket API token.',
}
}
const { spinner } = constants
if (description) {
spinner.start(`Requesting ${description} from API...`)
debugApiRequest('GET', path, constants.ENV.SOCKET_CLI_API_TIMEOUT)
}
let result
const startTime = Date.now()
try {
result = await queryApi(path, apiToken)
const duration = Date.now() - startTime
debugApiResponse(
'GET',
path,
result.status,
undefined,
duration,
Object.fromEntries(result.headers.entries()),
)
if (description) {
spinner.successAndStop(
`Received Socket API response (after requesting ${description}).`,
)
}
} catch (e) {
const duration = Date.now() - startTime
if (description) {
spinner.failAndStop(
`An error was thrown while requesting ${description}.`,
)
debugApiResponse('GET', path, undefined, e, duration)
}
debugFn('error', 'Query API request failed')
debugDir('error', e)
const errStr = e ? String(e).trim() : ''
const message = 'API request failed'
const rawCause = errStr || NO_ERROR_MESSAGE
const cause = message !== rawCause ? rawCause : ''
return {
ok: false,
message,
...(cause ? { cause } : {}),
}
}
if (!result.ok) {
const { status } = result
// Log required permissions for 403 errors when in a command context.
if (commandPath && status === 403) {
logPermissionsFor403(commandPath)
}
return {
ok: false,
message: 'Socket API error',
cause: `${result.statusText} (reason: ${await getErrorMessageForHttpStatusCode(status)})`,
data: {
code: status,
},
}
}
try {
const data = await result.text()
return {
ok: true,
data,
}
} catch (e) {
debugFn('error', 'Failed to read API response text')
debugDir('error', e)
return {
ok: false,
message: 'API request failed',
cause: 'Unexpected error reading response text',
}
}
}
/**
* Query Socket API endpoint and return parsed JSON response.
*/
export async function queryApiSafeJson<T>(
path: string,
description = '',
): Promise<CResult<T>> {
const result = await queryApiSafeText(path, description)
if (!result.ok) {
return result
}
try {
return {
ok: true,
data: JSON.parse(result.data) as T,
}
} catch (e) {
return {
ok: false,
message: 'Server returned invalid JSON',
cause: `Please report this. JSON.parse threw an error over the following response: \`${(result.data?.slice?.(0, 100) || EMPTY_VALUE).trim() + (result.data?.length > 100 ? '...' : '')}\``,
}
}
}
export type SendApiRequestOptions = {
method: 'POST' | 'PUT'
body?: unknown | undefined
description?: string | undefined
commandPath?: string | undefined
}
/**
* Send POST/PUT request to Socket API with JSON response handling.
*/
export async function sendApiRequest<T>(
path: string,
options?: SendApiRequestOptions | undefined,
): Promise<CResult<T>> {
const apiToken = getDefaultApiToken()
if (!apiToken) {
return {
ok: false,
message: 'Authentication Error',
cause:
'User must be authenticated to run this command. To log in, run the command `socket login` and enter your Socket API token.',
}
}
const baseUrl = getDefaultApiBaseUrl()
if (!baseUrl) {
return {
ok: false,
message: 'Configuration Error',
cause:
'Socket API endpoint is not configured. Please check your environment configuration.',
}
}
const { body, commandPath, description, method } = {
__proto__: null,
...options,
} as SendApiRequestOptions
const { spinner } = constants
if (description) {
spinner.start(`Requesting ${description} from API...`)
}
let result
try {
const fetchOptions = {
method,
headers: {
Authorization: `Basic ${btoa(`${apiToken}:`)}`,
'Content-Type': 'application/json',
},
...(body ? { body: JSON.stringify(body) } : {}),
}
result = await fetch(
`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${path}`,
fetchOptions,
)
if (description) {
spinner.successAndStop(
`Received Socket API response (after requesting ${description}).`,
)
}
} catch (e) {
if (description) {
spinner.failAndStop(
`An error was thrown while requesting ${description}.`,
)
}
debugFn('error', `API ${method} request failed`)
debugDir('error', e)
const errStr = e ? String(e).trim() : ''
const message = 'API request failed'
const rawCause = errStr || NO_ERROR_MESSAGE
const cause = message !== rawCause ? rawCause : ''
return {
ok: false,
message,
...(cause ? { cause } : {}),
}
}
if (!result.ok) {
const { status } = result
// Log required permissions for 403 errors when in a command context.
if (commandPath && status === 403) {
logPermissionsFor403(commandPath)
}
return {
ok: false,
message: 'Socket API error',
cause: `${result.statusText} (reason: ${await getErrorMessageForHttpStatusCode(status)})`,
data: {
code: status,
},
}
}
try {
const data = await result.json()
return {
ok: true,
data: data as T,
}
} catch (e) {
debugFn('error', 'Failed to parse API response JSON')
debugDir('error', e)
return {
ok: false,
message: 'API request failed',
cause: 'Unexpected error parsing response JSON',
}
}
}