-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathauthHandler.test.ts
More file actions
754 lines (589 loc) · 23.8 KB
/
Copy pathauthHandler.test.ts
File metadata and controls
754 lines (589 loc) · 23.8 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
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createUnauthorizedHandler, getBaseUrl, openLoginPopup, checkAuthStatus, decodeJwtPayload } from '../authHandler';
// Helper to create a mock JWT token with a given payload
function createMockJwt(payload: Record<string, unknown>): string {
const header = btoa(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
const payloadStr = btoa(JSON.stringify(payload));
const signature = 'mock-signature';
return `${header}.${payloadStr}.${signature}`;
}
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;
// Mock window.open
const mockWindowOpen = vi.fn();
global.window.open = mockWindowOpen;
// Mock window.location
const mockLocation = {
origin: 'https://example.com',
reload: vi.fn(),
href: '',
};
Object.defineProperty(window, 'location', {
value: mockLocation,
writable: true,
});
describe('authHandler', () => {
beforeEach(() => {
vi.clearAllMocks();
mockLocation.href = '';
});
afterEach(() => {
vi.clearAllTimers();
});
describe('getBaseUrl', () => {
it('should extract base URL from agent card URL', () => {
const agentCardUrl = 'https://app.example.com/api/agents/assistant/.well-known/agent-card.json';
expect(getBaseUrl(agentCardUrl)).toBe('https://app.example.com');
});
it('should return window.location.origin for invalid URL', () => {
const invalidUrl = 'not-a-valid-url';
expect(getBaseUrl(invalidUrl)).toBe('https://example.com');
});
it('should return window.location.origin when no URL provided', () => {
expect(getBaseUrl()).toBe('https://example.com');
});
});
describe('decodeJwtPayload', () => {
it('should decode a valid JWT payload', () => {
const payload = { sub: 'user123', name: 'John Doe', exp: 1234567890 };
const token = createMockJwt(payload);
const result = decodeJwtPayload(token);
expect(result.sub).toBe('user123');
expect(result.name).toBe('John Doe');
expect(result.exp).toBe(1234567890);
});
it('should decode JWT with special characters in payload', () => {
// Use ASCII-compatible special characters since btoa() doesn't handle UTF-8
const payload = { name: "John O'Brien", email: 'test+special@example.com', path: '/api/v1?query=value&other=123' };
const token = createMockJwt(payload);
const result = decodeJwtPayload(token);
expect(result.name).toBe("John O'Brien");
expect(result.email).toBe('test+special@example.com');
expect(result.path).toBe('/api/v1?query=value&other=123');
});
it('should handle base64url encoding with - and _ characters', () => {
// Create a token with base64url characters (- and _)
const header = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9'; // standard header
const payload = { sub: 'user-123_abc', name: 'Test User' };
const payloadBase64 = btoa(JSON.stringify(payload)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const token = `${header}.${payloadBase64}.signature`;
const result = decodeJwtPayload(token);
expect(result.sub).toBe('user-123_abc');
expect(result.name).toBe('Test User');
});
it('should throw error for invalid JWT format (less than 3 parts)', () => {
expect(() => decodeJwtPayload('invalid.token')).toThrow('Invalid JWT format');
});
it('should throw error for invalid JWT format (more than 3 parts)', () => {
expect(() => decodeJwtPayload('a.b.c.d')).toThrow('Invalid JWT format');
});
it('should throw error for empty string', () => {
expect(() => decodeJwtPayload('')).toThrow('Invalid JWT format');
});
it('should decode JWT with nested objects in payload', () => {
const payload = {
sub: 'user123',
claims: { role: 'admin', permissions: ['read', 'write'] },
};
const token = createMockJwt(payload);
const result = decodeJwtPayload(token);
expect(result.sub).toBe('user123');
expect(result.claims).toEqual({ role: 'admin', permissions: ['read', 'write'] });
});
it('should decode JWT with standard claims', () => {
const payload = {
iss: 'https://issuer.example.com',
sub: 'user123',
aud: 'client-app',
exp: 9999999999,
iat: 1234567890,
};
const token = createMockJwt(payload);
const result = decodeJwtPayload(token);
expect(result.iss).toBe('https://issuer.example.com');
expect(result.sub).toBe('user123');
expect(result.aud).toBe('client-app');
expect(result.exp).toBe(9999999999);
expect(result.iat).toBe(1234567890);
});
});
describe('checkAuthStatus', () => {
it('should return true and username when user is authenticated', async () => {
const mockToken = createMockJwt({ name: 'John Doe', sub: 'user123', exp: 9999999999 });
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve([{ provider_name: 'aad', user_id: 'test@example.com', access_token: mockToken }]),
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: true, isEasyAuthConfigured: true, error: null, username: 'John Doe' });
expect(mockFetch).toHaveBeenCalledWith('https://example.com/.auth/me', {
method: 'GET',
credentials: 'include',
redirect: 'manual',
});
});
it('should return undefined username when name claim is missing', async () => {
const mockToken = createMockJwt({ sub: 'user123', exp: 9999999999 });
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve([{ provider_name: 'aad', user_id: 'test@example.com', access_token: mockToken }]),
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: true, isEasyAuthConfigured: true, error: null, username: undefined });
});
it('should return false when user is not authenticated (empty array)', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve([]),
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: false, isEasyAuthConfigured: true, error: null, username: undefined });
});
it('should handle invalid JWT token gracefully', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve([{ provider_name: 'aad', access_token: 'invalid-token' }]),
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: true, isEasyAuthConfigured: true, error: null, username: undefined });
});
it('should handle missing access_token gracefully', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve([{ provider_name: 'aad', user_id: 'test@example.com' }]),
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: true, isEasyAuthConfigured: true, error: null, username: undefined });
});
it('should return isEasyAuthConfigured true and not authenticated when 401', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
type: 'basic',
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: false, isEasyAuthConfigured: true, error: null });
});
it('should return isEasyAuthConfigured true and not authenticated when 403', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 403,
type: 'basic',
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: false, isEasyAuthConfigured: true, error: null });
});
it('should return isEasyAuthConfigured true and not authenticated on opaqueredirect (302)', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 0,
type: 'opaqueredirect',
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: false, isEasyAuthConfigured: true, error: null });
});
it('should return false on network error', async () => {
const networkError = new Error('Network error');
mockFetch.mockRejectedValueOnce(networkError);
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: false, isEasyAuthConfigured: false, error: networkError });
});
it('should return isEasyAuthConfigured false when /.auth/me returns 404', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 404,
type: 'basic',
});
const result = await checkAuthStatus('https://example.com');
expect(result).toEqual({ isAuthenticated: false, isEasyAuthConfigured: false, error: null });
});
it('should return isEasyAuthConfigured true with error when 500 Internal Server Error', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 500,
type: 'basic',
});
const result = await checkAuthStatus('https://example.com');
expect(result.isAuthenticated).toBe(false);
expect(result.isEasyAuthConfigured).toBe(true);
expect(result.error).toBeInstanceOf(Error);
expect(result.error?.message).toBe('Failed to fetch authentication status');
});
it('should return isEasyAuthConfigured true with error when 503 Service Unavailable', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 503,
type: 'basic',
});
const result = await checkAuthStatus('https://example.com');
expect(result.isAuthenticated).toBe(false);
expect(result.isEasyAuthConfigured).toBe(true);
expect(result.error).toBeInstanceOf(Error);
expect(result.error?.message).toBe('Failed to fetch authentication status');
});
});
describe('openLoginPopup', () => {
it('should open login popup with correct URL using signInEndpoint', () => {
const mockPopup = { closed: false, close: vi.fn(), location: { href: '' } };
mockWindowOpen.mockReturnValueOnce(mockPopup);
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/aad',
postLoginRedirectUri: '/dashboard',
});
expect(mockWindowOpen).toHaveBeenCalledWith(
'https://example.com/.auth/login/aad?post_login_redirect_uri=%2Fdashboard',
'auth-login',
'width=600,height=700,popup=true'
);
});
it('should open login popup with different identity provider endpoint', () => {
const mockPopup = { closed: false, close: vi.fn(), location: { href: '' } };
mockWindowOpen.mockReturnValueOnce(mockPopup);
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/google',
});
expect(mockWindowOpen).toHaveBeenCalledWith(
'https://example.com/.auth/login/google',
'auth-login',
'width=600,height=700,popup=true'
);
});
it('should call onFailed when popup is blocked', () => {
mockWindowOpen.mockReturnValueOnce(null);
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/aad',
onFailed,
});
expect(onFailed).toHaveBeenCalled();
});
it('should allow login popup for a trusted Logic Apps domain on a different origin', () => {
const mockPopup = { closed: false, close: vi.fn(), location: { href: '' } };
mockWindowOpen.mockReturnValueOnce(mockPopup);
openLoginPopup({
baseUrl: 'https://contoso.logic.azure.com',
signInEndpoint: '/.auth/login/aad',
});
expect(mockWindowOpen).toHaveBeenCalledWith(
'https://contoso.logic.azure.com/.auth/login/aad',
'auth-login',
'width=600,height=700,popup=true'
);
});
it('should block login popup that redirects to an untrusted origin', () => {
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'https://evil.example.net',
signInEndpoint: '/.auth/login/aad',
onFailed,
});
expect(mockWindowOpen).not.toHaveBeenCalled();
expect(onFailed).toHaveBeenCalledWith(expect.any(Error));
});
it('should block a sign-in endpoint that escapes the base origin via userinfo', () => {
const onFailed = vi.fn();
// `${baseUrl}${signInEndpoint}` => https://example.com@evil.example.net/... (origin becomes evil.example.net)
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '@evil.example.net/.auth/login/aad',
onFailed,
});
expect(mockWindowOpen).not.toHaveBeenCalled();
expect(onFailed).toHaveBeenCalledWith(expect.any(Error));
});
it('should block a login popup URL that embeds userinfo even on a trusted host', () => {
const onFailed = vi.fn();
// Trusted host, but the embedded userinfo is a spoofing vector and must be rejected.
openLoginPopup({
baseUrl: 'https://user:pass@contoso.logic.azure.com',
signInEndpoint: '/.auth/login/aad',
onFailed,
});
expect(mockWindowOpen).not.toHaveBeenCalled();
expect(onFailed).toHaveBeenCalledWith(expect.any(Error));
});
it('should block a non-https login popup URL on a non-localhost host', () => {
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'http://contoso.logic.azure.com',
signInEndpoint: '/.auth/login/aad',
onFailed,
});
expect(mockWindowOpen).not.toHaveBeenCalled();
expect(onFailed).toHaveBeenCalledWith(expect.any(Error));
});
it('should block a malformed login popup URL', () => {
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'not-a-valid-url',
signInEndpoint: '/.auth/login/aad',
onFailed,
});
expect(mockWindowOpen).not.toHaveBeenCalled();
expect(onFailed).toHaveBeenCalledWith(expect.any(Error));
});
it('should call onSuccess when login succeeds and popup closes', async () => {
vi.useFakeTimers();
const mockToken = createMockJwt({ name: 'Test User', sub: 'user123' });
const mockPopup = { closed: false, close: vi.fn(), location: { href: '' } };
mockWindowOpen.mockReturnValueOnce(mockPopup);
mockFetch.mockResolvedValue({
ok: true,
json: () => Promise.resolve([{ provider_name: 'aad', access_token: mockToken }]),
});
const onSuccess = vi.fn();
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/aad',
onSuccess,
});
// Simulate popup being closed after successful login
mockPopup.closed = true;
// First interval tick to detect popup closed
await vi.advanceTimersByTimeAsync(500);
// Wait for the 500ms delay after popup close
await vi.advanceTimersByTimeAsync(500);
// Allow promises to resolve
await vi.runAllTimersAsync();
expect(onSuccess).toHaveBeenCalled();
vi.useRealTimers();
});
it('should keep polling when popup is still open and user is not yet authenticated', async () => {
vi.useFakeTimers();
const mockPopup = { closed: false, close: vi.fn() } as Record<string, unknown>;
Object.defineProperty(mockPopup, 'location', {
get: () => {
throw new DOMException('cross-origin');
},
configurable: true,
});
mockWindowOpen.mockReturnValueOnce(mockPopup);
// Initially return 401 (not authenticated, error: null)
mockFetch.mockResolvedValue({
ok: false,
status: 401,
type: 'basic',
});
const onSuccess = vi.fn();
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/aad',
onSuccess,
onFailed,
});
// Advance several polling ticks while popup is still open
await vi.advanceTimersByTimeAsync(500);
await vi.advanceTimersByTimeAsync(500);
await vi.advanceTimersByTimeAsync(500);
// Should NOT have called onFailed or onSuccess — popup is still open
expect(onFailed).not.toHaveBeenCalled();
expect(onSuccess).not.toHaveBeenCalled();
// Now simulate popup closing and auth succeeding
mockPopup.closed = true;
const mockToken = createMockJwt({ name: 'Test User', sub: 'user123' });
mockFetch.mockResolvedValue({
ok: true,
json: () => Promise.resolve([{ provider_name: 'aad', access_token: mockToken }]),
});
await vi.advanceTimersByTimeAsync(500);
await vi.advanceTimersByTimeAsync(500);
await vi.runAllTimersAsync();
expect(onSuccess).toHaveBeenCalled();
vi.useRealTimers();
});
it('should call onFailed when popup is closed and user is not authenticated', async () => {
vi.useFakeTimers();
const mockPopup = { closed: false, close: vi.fn() } as Record<string, unknown>;
Object.defineProperty(mockPopup, 'location', {
get: () => {
throw new DOMException('cross-origin');
},
configurable: true,
});
mockWindowOpen.mockReturnValueOnce(mockPopup);
mockFetch.mockResolvedValue({
ok: false,
status: 401,
type: 'basic',
});
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/aad',
onFailed,
});
// First tick triggers cross-origin detection (wasOnDifferentOrigin = true)
await vi.advanceTimersByTimeAsync(500);
// Close the popup
mockPopup.closed = true;
// Next tick detects popup closed + not authenticated
await vi.advanceTimersByTimeAsync(500);
await vi.advanceTimersByTimeAsync(500);
await vi.runAllTimersAsync();
expect(onFailed).toHaveBeenCalled();
const errorArg = onFailed.mock.calls[0][0];
expect(errorArg).toBeInstanceOf(Error);
expect(errorArg.message).toBe('Login cancelled or failed');
vi.useRealTimers();
});
it('should not crash when checkAuthStatus returns null error', async () => {
vi.useFakeTimers();
const mockPopup = { closed: true, close: vi.fn() } as Record<string, unknown>;
Object.defineProperty(mockPopup, 'location', {
get: () => {
throw new DOMException('cross-origin');
},
configurable: true,
});
mockWindowOpen.mockReturnValueOnce(mockPopup);
// 401 returns { isAuthenticated: false, error: null }
mockFetch.mockResolvedValue({
ok: false,
status: 401,
type: 'basic',
});
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/aad',
onFailed,
});
// Advance timers — should not throw TypeError
await vi.advanceTimersByTimeAsync(500);
await vi.advanceTimersByTimeAsync(500);
await vi.runAllTimersAsync();
expect(onFailed).toHaveBeenCalled();
const errorArg = onFailed.mock.calls[0][0];
expect(errorArg).toBeInstanceOf(Error);
vi.useRealTimers();
});
it('should call onSuccess after cross-origin navigation when authentication succeeds', async () => {
vi.useFakeTimers();
const mockPopup = { closed: false, close: vi.fn() } as Record<string, unknown>;
Object.defineProperty(mockPopup, 'location', {
get: () => {
throw new DOMException('cross-origin');
},
configurable: true,
});
mockWindowOpen.mockReturnValueOnce(mockPopup);
// First few ticks: 401 (not authenticated)
mockFetch.mockResolvedValue({
ok: false,
status: 401,
type: 'basic',
});
const onSuccess = vi.fn();
const onFailed = vi.fn();
openLoginPopup({
baseUrl: 'https://example.com',
signInEndpoint: '/.auth/login/aad',
onSuccess,
onFailed,
});
// First tick: cross-origin error sets wasOnDifferentOrigin
await vi.advanceTimersByTimeAsync(500);
// Second tick: polls auth, gets 401, popup still open — keeps polling
await vi.advanceTimersByTimeAsync(500);
expect(onSuccess).not.toHaveBeenCalled();
expect(onFailed).not.toHaveBeenCalled();
// Now auth succeeds (user completed login in popup)
const mockToken = createMockJwt({ name: 'Authenticated User', sub: 'user456' });
mockFetch.mockResolvedValue({
ok: true,
json: () => Promise.resolve([{ provider_name: 'aad', access_token: mockToken }]),
});
await vi.advanceTimersByTimeAsync(500);
await vi.runAllTimersAsync();
expect(onSuccess).toHaveBeenCalled();
expect(onFailed).not.toHaveBeenCalled();
const authInfo = onSuccess.mock.calls[0][0];
expect(authInfo.isAuthenticated).toBe(true);
expect(authInfo.username).toBe('Authenticated User');
vi.useRealTimers();
});
});
describe('createUnauthorizedHandler', () => {
it('should attempt token refresh on 401', async () => {
mockFetch.mockResolvedValueOnce({ ok: true });
const onRefreshSuccess = vi.fn();
const handler = createUnauthorizedHandler({
baseUrl: 'https://example.com',
onRefreshSuccess,
onLoginRequired: vi.fn(),
});
await handler();
expect(mockFetch).toHaveBeenCalledWith('https://example.com/.auth/refresh', {
method: 'GET',
credentials: 'same-origin',
});
expect(onRefreshSuccess).toHaveBeenCalled();
});
it('should call onLoginRequired when refresh fails', async () => {
mockFetch.mockResolvedValueOnce({ ok: false });
const onRefreshFailed = vi.fn();
const onLoginRequired = vi.fn();
const handler = createUnauthorizedHandler({
baseUrl: 'https://example.com',
onRefreshFailed,
onLoginRequired,
});
await handler();
expect(onRefreshFailed).toHaveBeenCalled();
expect(onLoginRequired).toHaveBeenCalled();
});
it('should call onLoginRequired when refresh throws an error', async () => {
mockFetch.mockRejectedValueOnce(new Error('Network error'));
const onRefreshFailed = vi.fn();
const onLoginRequired = vi.fn();
const handler = createUnauthorizedHandler({
baseUrl: 'https://example.com',
onRefreshFailed,
onLoginRequired,
});
await handler();
expect(onRefreshFailed).toHaveBeenCalled();
expect(onLoginRequired).toHaveBeenCalled();
});
it('should reload page when refresh succeeds', async () => {
mockFetch.mockResolvedValueOnce({ ok: true });
const handler = createUnauthorizedHandler({
baseUrl: 'https://example.com',
onLoginRequired: vi.fn(),
});
await handler();
expect(mockLocation.reload).toHaveBeenCalled();
});
it('should prevent multiple simultaneous auth attempts', async () => {
vi.useFakeTimers();
let resolvePromise: (value: { ok: boolean }) => void;
mockFetch.mockImplementation(
() =>
new Promise((resolve) => {
resolvePromise = resolve;
})
);
const handler = createUnauthorizedHandler({
baseUrl: 'https://example.com',
onLoginRequired: vi.fn(),
});
// Call handler multiple times
const promise1 = handler();
const promise2 = handler();
const promise3 = handler();
// Resolve the fetch
resolvePromise!({ ok: true });
await promise1;
await promise2;
await promise3;
// Should only make one fetch call
expect(mockFetch).toHaveBeenCalledTimes(1);
vi.useRealTimers();
});
});
});