-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathinfrastructure.ts
More file actions
633 lines (584 loc) · 22 KB
/
infrastructure.ts
File metadata and controls
633 lines (584 loc) · 22 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/**
* API Client Infrastructure
*
* Shared helpers, types, constants, and raw request functions used by
* all domain-specific API modules. This is the foundation layer that
* other modules in `src/lib/api/` import from.
*/
import { parseSentryLinkHeader } from "@sentry/api";
// biome-ignore lint/performance/noNamespaceImport: Sentry SDK recommends namespace import
import * as Sentry from "@sentry/node-core/light";
import type { z } from "zod";
import { extractRequiredScopes } from "../api-scope.js";
import { getActiveEnvVarName, isEnvTokenActive } from "../db/auth.js";
import { getEnv } from "../env.js";
import { ApiError, AuthError, stringifyUnknown } from "../errors.js";
import { logger } from "../logger.js";
import { resolveOrgRegion } from "../region.js";
import {
getApiBaseUrl,
getDefaultSdkConfig,
getSdkConfig,
} from "../sentry-client.js";
/**
* Enrich a 403 Forbidden error detail with actionable guidance.
*
* "Your organization has disabled this feature for members" is an org-level
* policy (Organization.flags.disable_member_project_creation), not a token
* scope or auth problem. We return targeted guidance and skip the generic
* scope/re-auth enrichment entirely — suggesting re-authentication for this
* error would be actively wrong and has caused user confusion (CLI-SERVER-E).
*
* All other 403s fall through to the existing logic:
* - env-var tokens → suggest checking token scopes
* - OAuth tokens → suggest re-authentication
*/
function enrich403Detail(rawDetail: string | undefined): string {
// Org-level policy — re-auth and token scope advice do not apply here.
if (rawDetail?.includes("disabled this feature")) {
return [
rawDetail,
"",
"This is an org-level policy setting, not an auth issue.",
"You need org:admin/manager/owner role, or team:admin role on the team.",
].join("\n ");
}
const lines: string[] = [];
if (rawDetail) {
lines.push(rawDetail, "");
}
if (isEnvTokenActive()) {
const scopes = extractRequiredScopes(rawDetail);
if (scopes.length > 0) {
lines.push(
`Your ${getActiveEnvVarName()} token is missing the required scope(s) '${scopes.join("', '")}'.`
);
} else {
lines.push(
`Your ${getActiveEnvVarName()} token may lack the required scope for this operation.`
);
}
lines.push(
"Check token scopes at: https://sentry.io/settings/account/api/auth-tokens/"
);
} else {
lines.push(
"You may not have access to this resource.",
"Re-authenticate with: sentry auth login"
);
}
return lines.join("\n ");
}
/**
* Enrich a 401 Unauthorized error detail with actionable guidance.
*
* 401 means the token is missing, invalid, or expired — the identity cannot
* be determined at all. Distinct from 403 (identity known, lacks permission).
* Scope hints do not apply; the fix is always to re-authenticate or regenerate
* the token.
*
* The Sentry API returns distinct `detail` strings we can branch on:
* `"Token expired"` when the token is past its expiry date, `"Invalid token"`
* when it is not found or malformed. We use this to give a more precise message
* for env-var token users.
*
* For OAuth users the token lifecycle is transparent — `sentry-client.ts`
* intercepts 401s and refreshes automatically. A 401 that reaches this function
* means refresh failed and the user needs to re-authenticate via the browser.
*
* @see https://github.com/getsentry/sentry/blob/934f1473f198a62f9268d7140b80cd9ca1e59bb9/src/sentry/api/authentication.py#L536-L539
*/
function enrich401Detail(rawDetail: string | undefined): string {
const lines: string[] = [];
if (rawDetail) {
lines.push(rawDetail, "");
}
if (isEnvTokenActive()) {
const expired = rawDetail?.toLowerCase().includes("expired");
lines.push(
`Your ${getActiveEnvVarName()} token ${expired ? "has expired" : "is not recognized or has been revoked"}.`,
"Create a new token at: https://sentry.io/settings/account/api/auth-tokens/"
);
} else {
lines.push(
"Not authenticated or your session has expired.",
"Re-authenticate with: sentry auth login"
);
}
return lines.join("\n ");
}
/**
* Select and apply status-specific detail enrichment.
*
* Extracted from {@link throwApiError} and {@link throwRawApiError} to keep
* their cognitive complexity within the linter limit. 403 and 401 get
* actionable guidance; all other statuses pass the raw detail through.
*
* `hasUsableDetail` controls whether the raw detail string is forwarded to
* the enrichment functions — passing `undefined` when false lets them render
* without a noisy `{"detail":null}` prefix.
*/
function enrichDetail(
status: number,
detail: string | undefined,
hasUsableDetail: boolean
): string | undefined {
if (status === 403) {
return enrich403Detail(hasUsableDetail ? detail : undefined);
}
if (status === 401) {
return enrich401Detail(hasUsableDetail ? detail : undefined);
}
return detail;
}
/**
* Parse Sentry's RFC 5988 Link response header to extract pagination cursors.
*
* Sentry Link header format:
* `<url>; rel="next"; results="true"; cursor="1735689600000:0:0"`
*
* Thin alias over `@sentry/api`'s `parseSentryLinkHeader` — the SDK ships the
* canonical parser. We keep the `parseLinkHeader` name because multiple call
* sites import it under that name from the `api-client` barrel and because
* `unwrapPaginatedResult` below needs a local binding.
*/
export const parseLinkHeader = parseSentryLinkHeader;
/** Options for raw API requests to Sentry endpoints. */
export type ApiRequestOptions<T = unknown> = {
method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
body?: unknown;
/** Query parameters. String arrays create repeated keys (e.g., tags=1&tags=2) */
params?: Record<string, string | number | boolean | string[] | undefined>;
/** Optional Zod schema for runtime validation of response data */
schema?: z.ZodType<T>;
};
/**
* Throw an ApiError from a failed @sentry/api SDK response.
*
* @param error - The error object from the SDK (contains status code and detail)
* @param response - The raw Response object
* @param context - Human-readable context for the error message
*/
export function throwApiError(
error: unknown,
response: Response | undefined,
context: string
): never {
// Network-level failure: no HTTP response received (DNS, timeout, ECONNREFUSED, etc.)
if (!response) {
const cause =
error instanceof Error ? error.message : stringifyUnknown(error);
throw new ApiError(
`${context}: Network error`,
0,
`Unable to reach Sentry API. Cause: ${cause}\n\n Check your internet connection and try again.`
);
}
const status = response.status;
const rawDetail =
error && typeof error === "object" && "detail" in error
? (error as { detail: unknown }).detail
: undefined;
const hasUsableDetail = rawDetail !== null && rawDetail !== undefined;
// Enrichment functions (enrich403Detail, enrich401Detail) render better
// when rawDetail is undefined — they stand alone without a noisy `{}`
// prefix. For all other statuses, stringify the full error as a debug aid.
const detail = hasUsableDetail
? stringifyUnknown(rawDetail)
: stringifyUnknown(error);
const is403 = status === 403;
throw new ApiError(
`${context}: ${status} ${response.statusText ?? "Unknown"}`,
status,
enrichDetail(status, detail, hasUsableDetail),
undefined,
is403
);
}
/**
* Unwrap an @sentry/api SDK result, throwing ApiError on failure.
*
* When `throwOnError` is false (our default), the SDK catches errors from
* the fetch function and returns them in `{ error }`. This includes our
* AuthError from refreshToken(). We must re-throw known error types (AuthError,
* ApiError) directly so callers can distinguish auth failures from API errors.
*
* @param result - The result from an SDK function call
* @param context - Human-readable context for error messages
* @returns The data from the successful response
*/
export function unwrapResult<T>(
result: { data: T; error: undefined } | { data: undefined; error: unknown },
context: string
): T {
const { data, error } = result as {
data: unknown;
error: unknown;
response?: Response;
};
if (error !== undefined) {
// Preserve known error types that were caught by the SDK from our fetch function
if (error instanceof AuthError || error instanceof ApiError) {
throw error;
}
// The @sentry/api SDK always includes `response` on the returned object in
// the default "fields" responseStyle (see createClient request() in the SDK
// source — it spreads `{ request, response }` into every return value).
// The cast is typed as optional only because the SDK's TypeScript types omit
// `response` from the return type, not because it can be absent at runtime.
const response = (result as { response?: Response }).response;
throwApiError(error, response, context);
}
return data as T;
}
/**
* Unwrap an @sentry/api SDK result AND extract pagination from the Link header.
*
* Unlike {@link unwrapResult} which discards the Response, this preserves the
* Link header for cursor-based pagination. Use for SDK-backed paginated endpoints.
*
* @param result - The result from an SDK function call (includes `response`)
* @param context - Human-readable context for error messages
* @returns Data and optional next-page cursor
*/
export function unwrapPaginatedResult<T>(
result: { data: T; error: undefined } | { data: undefined; error: unknown },
context: string
): PaginatedResponse<T> {
const response = (result as { response?: Response }).response;
const data = unwrapResult(result, context);
const { nextCursor, prevCursor } = parseLinkHeader(
response?.headers.get("link") ?? null
);
const out: PaginatedResponse<T> = { data };
if (nextCursor !== undefined) {
out.nextCursor = nextCursor;
}
if (prevCursor !== undefined) {
out.prevCursor = prevCursor;
}
return out;
}
/**
* Build URLSearchParams from an options object, filtering out undefined values.
* Supports string arrays for repeated keys (e.g., { tags: ["a", "b"] } → tags=a&tags=b).
*
* @param params - Key-value pairs to convert to search params
* @returns URLSearchParams instance, or undefined if no valid params
* @internal Exported for testing
*/
export function buildSearchParams(
params?: Record<string, string | number | boolean | string[] | undefined>
): URLSearchParams | undefined {
if (!params) {
return;
}
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value === undefined) {
continue;
}
if (Array.isArray(value)) {
for (const item of value) {
searchParams.append(key, item);
}
} else {
searchParams.set(key, String(value));
}
}
return searchParams.toString() ? searchParams : undefined;
}
/**
* Get SDK config for an organization's region.
* Resolves the org's region URL and returns the config.
*/
export async function getOrgSdkConfig(orgSlug: string) {
const regionUrl = await resolveOrgRegion(orgSlug);
return getSdkConfig(regionUrl);
}
/**
* Maximum number of pages to follow when auto-paginating.
*
* Safety limit to prevent runaway pagination when the API returns an unexpectedly
* large number of pages. At API_MAX_PER_PAGE items/page this allows up to 5,000 items, which
* covers even the largest organizations. Override with SENTRY_MAX_PAGINATION_PAGES
* env var for edge cases.
*/
export const MAX_PAGINATION_PAGES = Math.max(
1,
Number(getEnv().SENTRY_MAX_PAGINATION_PAGES) || 50
);
/**
* Sentry API's maximum items per page.
* Requests for more items are silently capped server-side.
*/
export const API_MAX_PER_PAGE = 100;
/**
* Maximum concurrent API requests when fanning out across organizations or regions.
*
* Limits parallel calls (e.g., `getProject()` per org, `resolveEventInOrg()` per org,
* DSN key search per region) to prevent overwhelming the API for enterprise users
* with many organizations. For typical users with 1-5 orgs this has no effect.
*/
export const ORG_FANOUT_CONCURRENCY = 5;
/**
* Paginated API response with cursor metadata.
* More pages exist when `nextCursor` is defined.
*/
export type PaginatedResponse<T> = {
/** The response data */
data: T;
/** Cursor for fetching the next page (undefined if no more pages) */
nextCursor?: string;
/** Cursor for the previous page (undefined on the first page) */
prevCursor?: string;
};
/**
* Auto-paginate across multiple API pages, accumulating results up to `limit`.
*
* Calls `fetchPage` repeatedly until enough rows are collected or pages are
* exhausted. Caps at {@link MAX_PAGINATION_PAGES} to prevent runaway loops.
*
* The caller is responsible for baking `perPage` into the `fetchPage` closure
* (typically `Math.min(limit, API_MAX_PER_PAGE)`). This helper only manages
* cursor chaining and row accumulation.
*
* @param fetchPage - Async function that fetches a single page given a cursor
* @param limit - Total number of items to collect
* @param initialCursor - Optional starting cursor
* @returns Accumulated items with optional nextCursor from the last page
*/
export async function autoPaginate<T>(
fetchPage: (cursor: string | undefined) => Promise<PaginatedResponse<T[]>>,
limit: number,
initialCursor?: string
): Promise<PaginatedResponse<T[]>> {
// Fast path: single-page fetch when limit fits in one API page
if (limit <= API_MAX_PER_PAGE) {
return fetchPage(initialCursor);
}
// Multi-page: accumulate rows across pages up to the requested limit
const allRows: T[] = [];
let cursor: string | undefined = initialCursor;
for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) {
const result = await fetchPage(cursor);
allRows.push(...result.data);
if (allRows.length >= limit || !result.nextCursor) {
// Overshot — trim and drop nextCursor (cursor would skip items)
if (allRows.length > limit) {
return { data: allRows.slice(0, limit) };
}
return { data: allRows, nextCursor: result.nextCursor };
}
cursor = result.nextCursor;
}
// Safety limit reached — warn and return what we have, no nextCursor
logger.warn(
`Pagination limit reached (${MAX_PAGINATION_PAGES} pages, ${allRows.length} items). ` +
"Results may be incomplete."
);
return { data: allRows.slice(0, limit) };
}
/**
* Make an authenticated request to a specific Sentry region.
* Returns both parsed response data and raw headers for pagination support.
* Used for internal endpoints not covered by @sentry/api SDK functions.
*
* @param regionUrl - The region's base URL (e.g., https://us.sentry.io)
* @param endpoint - API endpoint path (e.g., "/users/me/regions/")
* @param options - Request options
* @returns Parsed data and response headers
*/
export async function apiRequestToRegion<T>(
regionUrl: string,
endpoint: string,
options: ApiRequestOptions<T> = {}
): Promise<{ data: T; headers: Headers }> {
const { method = "GET", body, params, schema } = options;
const config = getSdkConfig(regionUrl);
const searchParams = buildSearchParams(params);
const normalizedEndpoint = endpoint.startsWith("/")
? endpoint.slice(1)
: endpoint;
const queryString = searchParams ? `?${searchParams.toString()}` : "";
// getSdkConfig.baseUrl is the plain region URL; add /api/0/ for raw requests
const url = `${config.baseUrl}/api/0/${normalizedEndpoint}${queryString}`;
const fetchFn = config.fetch;
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
const response = await fetchFn(url, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
if (!response.ok) {
await throwRawApiError(response, endpoint);
}
// 204 No Content / 205 Reset Content have no body by spec — calling
// response.json() on them throws SyntaxError. Callers that expect a
// body on success receive a clear ApiError here instead of crashing
// downstream on `data.<field>`. Callers that expect 204 (e.g. the
// bulk mutate endpoint returns 204 when no IDs match) should catch
// this ApiError and handle it explicitly.
if (response.status === 204 || response.status === 205) {
throw new ApiError(
`API returned ${response.status} ${response.statusText} (no body)`,
response.status,
"The server returned no content — the request may have matched no records.",
endpoint
);
}
const data = await response.json();
if (schema) {
const result = schema.safeParse(data);
if (!result.success) {
// Attach structured Zod issues to the Sentry event so we can diagnose
// exactly which field(s) failed validation — the ApiError.detail string
// alone may not be visible in the Sentry issue overview.
Sentry.setContext("zod_validation", {
endpoint,
status: response.status,
issues: result.error.issues.slice(0, 10),
});
throw new ApiError(
`Unexpected response format from ${endpoint}`,
response.status,
result.error.message
);
}
return { data: result.data, headers: response.headers };
}
return { data: data as T, headers: response.headers };
}
/**
* Extract error detail from a failed HTTP response, attach diagnostic
* headers to the Sentry scope, and throw an enriched {@link ApiError}.
*
* Extracted from `apiRequestToRegion` to keep the main function's
* cognitive complexity under the lint threshold.
*/
async function throwRawApiError(
response: Response,
endpoint: string
): Promise<never> {
let detail: string | undefined;
try {
const text = await response.text();
try {
const parsed = JSON.parse(text) as { detail?: string };
// Enriched statuses (403, 401) pass undefined when there is no
// usable string detail so the enrichment renders without a noisy
// `{"detail":null}` prefix. Other statuses get the full JSON as
// a debug aid.
if (typeof parsed.detail === "string") {
detail = parsed.detail;
} else if (response.status !== 403 && response.status !== 401) {
detail = JSON.stringify(parsed);
}
} catch {
detail = text || undefined;
}
} catch {
detail = response.statusText;
}
// Attach a small allowlisted subset of response headers to the Sentry
// event as context. This lets us distinguish Sentry-app 4xx/5xx (which
// ship a `{"detail": "..."}` JSON body and `content-type: application/json`)
// from CDN / WAF / edge 4xx (Cloudflare / proxy) that return empty or HTML
// bodies — a gap that previously made empty-`detail` events like CLI-1AZ
// impossible to triage without user-side repro.
Sentry.setContext("api_response_headers", {
"content-type": response.headers.get("content-type"),
"content-length": response.headers.get("content-length"),
server: response.headers.get("server"),
"cf-ray": response.headers.get("cf-ray"),
"x-sentry-error": response.headers.get("x-sentry-error"),
"www-authenticate": response.headers.get("www-authenticate"),
});
const is403 = response.status === 403;
throw new ApiError(
`API request failed: ${response.status} ${response.statusText}`,
response.status,
enrichDetail(response.status, detail, detail !== undefined),
endpoint,
is403
);
}
/**
* Make an authenticated request to the default Sentry API.
*
* @param endpoint - API endpoint path (e.g., "/organizations/")
* @param options - Request options including method, body, query params, and validation schema
* @returns Parsed JSON response (validated if schema provided)
* @throws {AuthError} When not authenticated
* @throws {ApiError} On API errors
*/
export async function apiRequest<T>(
endpoint: string,
options: ApiRequestOptions<T> = {}
): Promise<T> {
const { data } = await apiRequestToRegion<T>(
getApiBaseUrl(),
endpoint,
options
);
return data;
}
/**
* Make a raw API request that returns full response details.
* Unlike apiRequest, this does not throw on non-2xx responses.
* Used by the 'sentry api' command for direct API access.
*
* @param endpoint - API endpoint path (e.g., "/organizations/")
* @param options - Request options including method, body, params, and custom headers
* @returns Response status, headers, and parsed body
* @throws {AuthError} Only on authentication failure (not on API errors)
*/
export async function rawApiRequest(
endpoint: string,
options: ApiRequestOptions & { headers?: Record<string, string> } = {}
): Promise<{ status: number; headers: Headers; body: unknown }> {
const { method = "GET", body, params, headers: customHeaders = {} } = options;
const config = getDefaultSdkConfig();
const searchParams = buildSearchParams(params);
const normalizedEndpoint = endpoint.startsWith("/")
? endpoint.slice(1)
: endpoint;
const queryString = searchParams ? `?${searchParams.toString()}` : "";
// getSdkConfig.baseUrl is the plain region URL; add /api/0/ for raw requests
const url = `${config.baseUrl}/api/0/${normalizedEndpoint}${queryString}`;
// Build request headers and body.
// String bodies: no Content-Type unless the caller explicitly provides one.
// Object bodies: application/json (auto-stringified).
const isStringBody = typeof body === "string";
const hasContentType = Object.keys(customHeaders).some(
(k) => k.toLowerCase() === "content-type"
);
const headers: Record<string, string> = { ...customHeaders };
if (!(isStringBody || hasContentType) && body !== undefined) {
headers["Content-Type"] = "application/json";
}
let requestBody: string | undefined;
if (body !== undefined) {
requestBody = isStringBody ? body : JSON.stringify(body);
}
const fetchFn = config.fetch;
const response = await fetchFn(url, {
method,
headers,
body: requestBody,
});
const text = await response.text();
let responseBody: unknown;
try {
responseBody = JSON.parse(text);
} catch {
responseBody = text;
}
return {
status: response.status,
headers: response.headers,
body: responseBody,
};
}