-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapi-client.test.ts
More file actions
1856 lines (1581 loc) · 59.2 KB
/
api-client.test.ts
File metadata and controls
1856 lines (1581 loc) · 59.2 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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* API Client Tests
*
* Tests for the Sentry API client 401 retry behavior and utility functions.
* Uses manual fetch mocking to avoid polluting the module cache.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
API_MAX_PER_PAGE,
buildSearchParams,
getLogs,
listIssuesPaginated,
listRepositoriesPaginated,
listTeamsPaginated,
listTraceLogs,
listTransactions,
rawApiRequest,
} from "../../src/lib/api-client.js";
import { DEFAULT_SENTRY_URL } from "../../src/lib/constants.js";
import { setAuthToken } from "../../src/lib/db/auth.js";
import { setOrgRegion, setOrgRegions } from "../../src/lib/db/regions.js";
import { useTestConfigDir } from "../helpers.js";
useTestConfigDir("test-api-");
let originalFetch: typeof globalThis.fetch;
/**
* Tracks requests made during a test
*/
type RequestLog = {
url: string;
method: string;
authorization: string | null;
isRetry: boolean;
};
beforeEach(async () => {
// Set required env var for OAuth refresh
process.env.SENTRY_CLIENT_ID = "test-client-id";
// Save original fetch
originalFetch = globalThis.fetch;
// Set up initial auth token with a refresh token so 401 retry can get a new token
await setAuthToken("initial-token", 3600, "test-refresh-token");
});
afterEach(() => {
// Restore original fetch
globalThis.fetch = originalFetch;
});
/**
* Creates a mock fetch that handles API requests.
* Uses rawApiRequest which goes to control silo (no region resolution needed).
*
* The `apiRequestHandler` is called for each API request.
*/
function createMockFetch(
requests: RequestLog[],
apiRequestHandler: (
req: Request,
requestCount: number
) => Response | Promise<Response>,
options: {
oauthHandler?: (req: Request) => Response | Promise<Response>;
} = {}
): typeof globalThis.fetch {
let apiRequestCount = 0;
return async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push({
url: req.url,
method: req.method,
authorization: req.headers.get("Authorization"),
isRetry: req.headers.get("x-sentry-cli-retry") === "1",
});
// OAuth token refresh endpoint
if (req.url.includes("/oauth/token/")) {
if (options.oauthHandler) {
return options.oauthHandler(req);
}
return new Response(
JSON.stringify({
access_token: "refreshed-token",
token_type: "Bearer",
expires_in: 3600,
refresh_token: "new-refresh-token",
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
}
// API requests - delegate to handler
apiRequestCount += 1;
return apiRequestHandler(req, apiRequestCount);
};
}
describe("401 retry behavior", () => {
// Note: These tests use rawApiRequest which goes to control silo (sentry.io)
// and supports 401 retry with token refresh.
// Clear preload SENTRY_AUTH_TOKEN so the DB-stored token is used.
let savedAuthToken: string | undefined;
beforeEach(() => {
savedAuthToken = process.env.SENTRY_AUTH_TOKEN;
delete process.env.SENTRY_AUTH_TOKEN;
});
afterEach(() => {
if (savedAuthToken !== undefined) {
process.env.SENTRY_AUTH_TOKEN = savedAuthToken;
}
});
test("retries request with new token on 401 response", async () => {
const requests: RequestLog[] = [];
globalThis.fetch = createMockFetch(requests, (_req, requestCount) => {
// First request: return 401
if (requestCount === 1) {
return new Response(JSON.stringify({ detail: "Unauthorized" }), {
status: 401,
headers: { "Content-Type": "application/json" },
});
}
// Retry request: return success
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
});
const result = await rawApiRequest("/test-endpoint/");
// Verify successful result from retry
expect(result.status).toBe(200);
expect(result.body).toEqual({ ok: true });
// Verify request sequence:
// 1. Initial API request with initial-token -> 401
// 2. OAuth refresh request
// 3. Retry API request with refreshed-token -> 200
const apiRequests = requests.filter((r) =>
r.url.includes("/test-endpoint")
);
const oauthRequests = requests.filter((r) =>
r.url.includes("/oauth/token/")
);
expect(apiRequests).toHaveLength(2);
expect(oauthRequests).toHaveLength(1);
// First request with initial token
expect(apiRequests[0].authorization).toBe("Bearer initial-token");
expect(apiRequests[0].isRetry).toBe(false);
// Retry request with new token
expect(apiRequests[1].authorization).toBe("Bearer refreshed-token");
expect(apiRequests[1].isRetry).toBe(true);
});
test("does not retry on non-401 errors", async () => {
const requests: RequestLog[] = [];
globalThis.fetch = createMockFetch(requests, () => {
// Return 403 (not 401) - this should not trigger retry
return new Response(JSON.stringify({ detail: "Forbidden" }), {
status: 403,
headers: { "Content-Type": "application/json" },
});
});
// rawApiRequest doesn't throw on error responses, it returns the status
const result = await rawApiRequest("/test-endpoint/");
expect(result.status).toBe(403);
// Should only have initial API request, no retry
const apiRequests = requests.filter((r) =>
r.url.includes("/test-endpoint")
);
expect(apiRequests).toHaveLength(1);
expect(apiRequests[0].isRetry).toBe(false);
// No OAuth refresh should have been attempted
const oauthRequests = requests.filter((r) =>
r.url.includes("/oauth/token/")
);
expect(oauthRequests).toHaveLength(0);
});
test("does not retry infinitely on repeated 401s", async () => {
const requests: RequestLog[] = [];
globalThis.fetch = createMockFetch(requests, () => {
// Always return 401 for API requests
return new Response(JSON.stringify({ detail: "Unauthorized" }), {
status: 401,
headers: { "Content-Type": "application/json" },
});
});
// rawApiRequest doesn't throw, returns status
const result = await rawApiRequest("/test-endpoint/");
expect(result.status).toBe(401);
// Should have exactly 2 API requests (initial + one retry, no infinite loop)
const apiRequests = requests.filter((r) =>
r.url.includes("/test-endpoint")
);
expect(apiRequests).toHaveLength(2);
expect(apiRequests[0].isRetry).toBe(false);
expect(apiRequests[1].isRetry).toBe(true);
// OAuth refresh should have been called once (after first 401)
const oauthRequests = requests.filter((r) =>
r.url.includes("/oauth/token/")
);
expect(oauthRequests).toHaveLength(1);
});
test("does not retry for manual API tokens (no refresh token)", async () => {
// Manual API tokens have no expiry and no refresh token
await setAuthToken("manual-api-token"); // No expiry, no refresh token
const requests: RequestLog[] = [];
globalThis.fetch = createMockFetch(requests, () => {
// Always return 401
return new Response(JSON.stringify({ detail: "Unauthorized" }), {
status: 401,
headers: { "Content-Type": "application/json" },
});
});
// rawApiRequest doesn't throw, returns status
const result = await rawApiRequest("/test-endpoint/");
expect(result.status).toBe(401);
// Should have exactly 1 API request - no retry since token can't be refreshed
const apiRequests = requests.filter((r) =>
r.url.includes("/test-endpoint")
);
expect(apiRequests).toHaveLength(1);
expect(apiRequests[0].isRetry).toBe(false);
// No OAuth refresh should have been attempted (no refresh token available)
const oauthRequests = requests.filter((r) =>
r.url.includes("/oauth/token/")
);
expect(oauthRequests).toHaveLength(0);
});
});
describe("buildSearchParams", () => {
test("returns undefined for undefined input", () => {
expect(buildSearchParams(undefined)).toBeUndefined();
});
test("returns undefined for empty object", () => {
expect(buildSearchParams({})).toBeUndefined();
});
test("returns undefined when all values are undefined", () => {
expect(buildSearchParams({ a: undefined, b: undefined })).toBeUndefined();
});
test("builds params from simple key-value pairs", () => {
const result = buildSearchParams({ status: "resolved", limit: 10 });
expect(result).toBeDefined();
expect(result?.get("status")).toBe("resolved");
expect(result?.get("limit")).toBe("10");
});
test("skips undefined values", () => {
const result = buildSearchParams({
status: "resolved",
query: undefined,
limit: 10,
});
expect(result).toBeDefined();
expect(result?.get("status")).toBe("resolved");
expect(result?.get("limit")).toBe("10");
expect(result?.has("query")).toBe(false);
});
test("handles boolean values", () => {
const result = buildSearchParams({ active: true, archived: false });
expect(result).toBeDefined();
expect(result?.get("active")).toBe("true");
expect(result?.get("archived")).toBe("false");
});
test("handles string arrays as repeated keys", () => {
const result = buildSearchParams({ tags: ["error", "warning", "info"] });
expect(result).toBeDefined();
// URLSearchParams.getAll returns all values for repeated keys
expect(result?.getAll("tags")).toEqual(["error", "warning", "info"]);
// toString shows repeated keys
expect(result?.toString()).toBe("tags=error&tags=warning&tags=info");
});
test("handles mixed simple values and arrays", () => {
const result = buildSearchParams({
status: "unresolved",
tags: ["critical", "backend"],
limit: 25,
});
expect(result).toBeDefined();
expect(result?.get("status")).toBe("unresolved");
expect(result?.getAll("tags")).toEqual(["critical", "backend"]);
expect(result?.get("limit")).toBe("25");
});
test("handles empty array", () => {
const result = buildSearchParams({ tags: [] });
// Empty array produces no entries, so result should be undefined
expect(result).toBeUndefined();
});
});
describe("rawApiRequest", () => {
test("sends GET request without body", async () => {
const requests: Request[] = [];
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
return new Response(JSON.stringify([{ id: 1 }]), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
const result = await rawApiRequest("organizations/");
expect(result.status).toBe(200);
expect(result.body).toEqual([{ id: 1 }]);
expect(requests).toHaveLength(1);
expect(requests[0].method).toBe("GET");
});
test("sends POST request with JSON object body", async () => {
const requests: Request[] = [];
let capturedBody: string | undefined;
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
capturedBody = await req.text();
return new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
const result = await rawApiRequest("issues/123/", {
method: "POST",
body: { status: "resolved" },
});
expect(result.status).toBe(200);
expect(result.body).toEqual({ success: true });
expect(requests[0].method).toBe("POST");
expect(capturedBody).toBe('{"status":"resolved"}');
});
test("sends PUT request with string body", async () => {
const requests: Request[] = [];
let capturedBody: string | undefined;
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
capturedBody = await req.text();
return new Response(JSON.stringify({ updated: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
const result = await rawApiRequest("issues/123/", {
method: "PUT",
body: '{"status":"resolved"}',
});
expect(result.status).toBe(200);
expect(result.body).toEqual({ updated: true });
expect(requests[0].method).toBe("PUT");
// String body should be sent as-is
expect(capturedBody).toBe('{"status":"resolved"}');
// No Content-Type header set by default for string bodies
// (user can provide via custom headers if needed)
expect(requests[0].headers.get("Content-Type")).toBeNull();
});
test("string body with explicit Content-Type header", async () => {
const requests: Request[] = [];
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
return new Response(JSON.stringify({}), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
await rawApiRequest("issues/123/", {
method: "PUT",
body: "plain text content",
headers: { "Content-Type": "text/plain" },
});
// User-provided Content-Type should be used
expect(requests[0].headers.get("Content-Type")).toBe("text/plain");
});
test("string body with lowercase content-type header (case-insensitive)", async () => {
const requests: Request[] = [];
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
return new Response(JSON.stringify({}), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
await rawApiRequest("issues/123/", {
method: "PUT",
body: "<xml>content</xml>",
headers: { "content-type": "text/xml" },
});
// Lowercase content-type should be detected and preserved (case-insensitive check)
expect(requests[0].headers.get("Content-Type")).toBe("text/xml");
});
test("string body with mixed case Content-TYPE header", async () => {
const requests: Request[] = [];
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
return new Response(JSON.stringify({}), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
await rawApiRequest("issues/123/", {
method: "PUT",
body: "some data",
headers: { "CONTENT-TYPE": "application/octet-stream" },
});
// Mixed case Content-TYPE should be detected and preserved
expect(requests[0].headers.get("Content-Type")).toBe(
"application/octet-stream"
);
});
test("sends request with query params", async () => {
const requests: Request[] = [];
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
return new Response(JSON.stringify([]), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
await rawApiRequest("issues/", {
params: { status: "resolved", limit: "10" },
});
const url = new URL(requests[0].url);
expect(url.searchParams.get("status")).toBe("resolved");
expect(url.searchParams.get("limit")).toBe("10");
});
test("sends request with custom headers", async () => {
const requests: Request[] = [];
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
return new Response(JSON.stringify({}), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
await rawApiRequest("issues/", {
headers: { "X-Custom-Header": "test-value" },
});
expect(requests[0].headers.get("X-Custom-Header")).toBe("test-value");
});
test("custom headers merged with string body (no default Content-Type)", async () => {
const requests: Request[] = [];
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
return new Response(JSON.stringify({}), {
status: 200,
headers: { "Content-Type": "application/json" },
});
};
await rawApiRequest("issues/123/", {
method: "PUT",
body: '{"status":"resolved"}',
headers: { "X-Custom": "value" },
});
// Custom headers should be present, but no Content-Type for string bodies
expect(requests[0].headers.get("X-Custom")).toBe("value");
expect(requests[0].headers.get("Content-Type")).toBeNull();
});
test("returns non-JSON response body as string", async () => {
globalThis.fetch = async () =>
new Response("Plain text response", {
status: 200,
headers: { "Content-Type": "text/plain" },
});
const result = await rawApiRequest("some-endpoint/");
expect(result.status).toBe(200);
expect(result.body).toBe("Plain text response");
});
test("returns error status without throwing", async () => {
globalThis.fetch = async () =>
new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
const result = await rawApiRequest("nonexistent/");
expect(result.status).toBe(404);
expect(result.body).toEqual({ detail: "Not found" });
});
test("includes response headers", async () => {
globalThis.fetch = async () =>
new Response(JSON.stringify({}), {
status: 200,
headers: {
"Content-Type": "application/json",
"X-Request-Id": "abc123",
},
});
const result = await rawApiRequest("test/");
expect(result.headers.get("X-Request-Id")).toBe("abc123");
});
});
describe("findProjectsBySlug", () => {
test("returns matching projects from multiple orgs", async () => {
// Import dynamically inside test to allow mocking
const { findProjectsBySlug } = await import("../../src/lib/api-client.js");
const requests: Request[] = [];
// Mock the regions endpoint first, then org/project requests
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
requests.push(req);
const url = req.url;
// Regions endpoint - return single region to simplify test
if (url.includes("/users/me/regions/")) {
return new Response(
JSON.stringify({
regions: [{ name: "us", url: "https://us.sentry.io" }],
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// Organizations list
if (url.includes("/organizations/") && !url.includes("/projects/")) {
return new Response(
JSON.stringify([
{ id: "1", slug: "acme", name: "Acme Corp" },
{ id: "2", slug: "beta", name: "Beta Inc" },
]),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// getProject for acme/frontend - found
if (url.includes("/projects/acme/frontend/")) {
return new Response(
JSON.stringify({ id: "101", slug: "frontend", name: "Frontend" }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// getProject for beta/frontend - found
if (url.includes("/projects/beta/frontend/")) {
return new Response(
JSON.stringify({
id: "201",
slug: "frontend",
name: "Beta Frontend",
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// Default - not found
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
const { projects, orgs } = await findProjectsBySlug("frontend");
expect(projects).toHaveLength(2);
expect(projects[0].slug).toBe("frontend");
expect(projects[0].orgSlug).toBe("acme");
expect(projects[1].slug).toBe("frontend");
expect(projects[1].orgSlug).toBe("beta");
expect(orgs).toHaveLength(2);
});
test("returns empty array when no projects match", async () => {
const { findProjectsBySlug } = await import("../../src/lib/api-client.js");
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const url = req.url;
// Regions endpoint
if (url.includes("/users/me/regions/")) {
return new Response(
JSON.stringify({
regions: [{ name: "us", url: "https://us.sentry.io" }],
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// Organizations list
if (url.includes("/organizations/") && !url.includes("/projects/")) {
return new Response(
JSON.stringify([{ id: "1", slug: "acme", name: "Acme Corp" }]),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// getProject - not found (404)
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
const { projects } = await findProjectsBySlug("nonexistent");
expect(projects).toHaveLength(0);
});
test("skips orgs where user lacks access (403)", async () => {
const { findProjectsBySlug } = await import("../../src/lib/api-client.js");
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const url = req.url;
// Regions endpoint
if (url.includes("/users/me/regions/")) {
return new Response(
JSON.stringify({
regions: [{ name: "us", url: "https://us.sentry.io" }],
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// Organizations list
if (url.includes("/organizations/") && !url.includes("/projects/")) {
return new Response(
JSON.stringify([
{ id: "1", slug: "acme", name: "Acme Corp" },
{ id: "2", slug: "restricted", name: "Restricted Org" },
]),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// getProject for acme/frontend - success
if (url.includes("/projects/acme/frontend/")) {
return new Response(
JSON.stringify({ id: "101", slug: "frontend", name: "Frontend" }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// getProject for restricted/frontend - 403 forbidden
if (url.includes("/projects/restricted/frontend/")) {
return new Response(JSON.stringify({ detail: "Forbidden" }), {
status: 403,
headers: { "Content-Type": "application/json" },
});
}
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
// Should not throw, should just skip the restricted org
const { projects } = await findProjectsBySlug("frontend");
expect(projects).toHaveLength(1);
expect(projects[0].orgSlug).toBe("acme");
});
test("resolves numeric project ID when slug differs", async () => {
const { findProjectsBySlug } = await import("../../src/lib/api-client.js");
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const url = req.url;
// Regions endpoint
if (url.includes("/users/me/regions/")) {
return new Response(
JSON.stringify({
regions: [{ name: "us", url: "https://us.sentry.io" }],
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// Organizations list
if (url.includes("/organizations/") && !url.includes("/projects/")) {
return new Response(
JSON.stringify([{ id: "1", slug: "acme", name: "Acme Corp" }]),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// getProject for acme/7275560680 - API resolves by numeric ID,
// returns project with a different slug
if (url.includes("/projects/acme/7275560680/")) {
return new Response(
JSON.stringify({
id: "7275560680",
slug: "frontend",
name: "Frontend",
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
// Numeric ID should resolve even though returned slug differs
const { projects } = await findProjectsBySlug("7275560680");
expect(projects).toHaveLength(1);
expect(projects[0].slug).toBe("frontend");
expect(projects[0].orgSlug).toBe("acme");
});
test("rejects non-numeric input when returned slug differs", async () => {
const { findProjectsBySlug } = await import("../../src/lib/api-client.js");
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const url = req.url;
if (url.includes("/users/me/regions/")) {
return new Response(
JSON.stringify({
regions: [{ name: "us", url: "https://us.sentry.io" }],
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
if (url.includes("/organizations/") && !url.includes("/projects/")) {
return new Response(
JSON.stringify([{ id: "1", slug: "acme", name: "Acme Corp" }]),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
// API returns project with different slug (coincidental ID match)
if (url.includes("/projects/acme/wrong-slug/")) {
return new Response(
JSON.stringify({ id: "999", slug: "actual-slug", name: "Actual" }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
// Non-numeric input with slug mismatch should be rejected
const { projects } = await findProjectsBySlug("wrong-slug");
expect(projects).toHaveLength(0);
});
test("uses cached orgs to skip listOrganizations API calls", async () => {
const { findProjectsBySlug } = await import("../../src/lib/api-client.js");
// Seed org_regions cache with full org data (slug, id, name, region)
// so listOrganizations() returns from cache without HTTP calls.
setOrgRegions([
{
slug: "acme",
regionUrl: DEFAULT_SENTRY_URL,
orgId: "42",
orgName: "Acme Corp",
},
]);
const requests: string[] = [];
// @ts-expect-error - partial mock
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const url = req.url;
requests.push(url);
// getProject for acme/frontend — success
if (url.includes("/projects/acme/frontend/")) {
return new Response(
JSON.stringify({ id: "101", slug: "frontend", name: "Frontend" }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
const { projects } = await findProjectsBySlug("frontend");
// Found via cached orgs
expect(projects).toHaveLength(1);
expect(projects[0].slug).toBe("frontend");
expect(projects[0].orgSlug).toBe("acme");
// The expensive listOrganizations API calls were skipped
expect(requests.some((r) => r.includes("/users/me/regions/"))).toBe(false);
expect(
requests.some(
(r) => r.includes("/organizations/") && !r.includes("/projects/")
)
).toBe(false);
});
});
describe("resolveEventInOrg", () => {
const sampleEvent = {
id: "abc123",
eventID: "abc123def456",
groupID: "12345",
projectID: "67890",
message: "Something went wrong",
title: "Error",
location: null,
user: null,
tags: [],
platform: "node",
dateReceived: "2026-01-01T00:00:00Z",
contexts: null,
size: 100,
entries: [],
dist: null,
sdk: {},
context: null,
packages: {},
type: "error",
metadata: null,
errors: [],
occurrence: null,
_meta: {},
};
test("returns resolved event when found in org", async () => {
const { resolveEventInOrg } = await import("../../src/lib/api-client.js");
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const url = req.url;
if (url.includes("/users/me/regions/")) {
return new Response(
JSON.stringify({
regions: [{ name: "us", url: "https://us.sentry.io" }],
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
if (url.includes("/eventids/abc123def456/")) {
return new Response(
JSON.stringify({
organizationSlug: "acme",
projectSlug: "frontend",
groupId: "12345",
eventId: "abc123def456",
event: sampleEvent,
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
const result = await resolveEventInOrg("acme", "abc123def456");
expect(result).not.toBeNull();
expect(result?.org).toBe("acme");
expect(result?.project).toBe("frontend");
expect(result?.event.eventID).toBe("abc123def456");
});
test("returns null when event not found in org", async () => {
const { resolveEventInOrg } = await import("../../src/lib/api-client.js");
globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const url = req.url;
if (url.includes("/users/me/regions/")) {
return new Response(
JSON.stringify({
regions: [{ name: "us", url: "https://us.sentry.io" }],
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response(JSON.stringify({ detail: "Not Found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
};
const result = await resolveEventInOrg("acme", "notfound000000");
expect(result).toBeNull();
});
});
describe("findEventAcrossOrgs", () => {
const sampleEvent = {
id: "abc123",
eventID: "abc123def456",
groupID: "12345",
projectID: "67890",
message: "Something went wrong",
title: "Error",
location: null,
user: null,