forked from thunder-id/javascript-sdks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThunderIDJavaScriptClient.test.ts
More file actions
548 lines (441 loc) · 20.4 KB
/
Copy pathThunderIDJavaScriptClient.test.ts
File metadata and controls
548 lines (441 loc) · 20.4 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
// Copyright 2026 The ThunderID Authors
// SPDX-License-Identifier: Apache-2.0
import {describe, expect, it, vi, beforeEach, afterEach} from 'vitest';
import type {Storage} from '../models/store';
import ThunderIDJavaScriptClient from '../ThunderIDJavaScriptClient';
vi.mock('../IsomorphicCrypto', () => ({
IsomorphicCrypto: class MockIsomorphicCrypto {
constructor(_cryptoUtils: unknown) {}
},
}));
const mockHandleTokenResponse = vi.fn();
vi.mock('../utils/AuthenticationHelper', () => ({
default: class MockAuthenticationHelper {
constructor(_storage: unknown, _crypto: unknown) {}
handleTokenResponse = mockHandleTokenResponse;
},
}));
class MemoryStore implements Storage {
private store = new Map<string, string>();
async getData(key: string): Promise<string> {
return this.store.get(key) ?? null!;
}
async setData(key: string, value: string): Promise<void> {
this.store.set(key, value);
}
async removeData(key: string): Promise<void> {
this.store.delete(key);
}
}
async function getStoredConfig(client: ThunderIDJavaScriptClient): Promise<Record<string, any>> {
return (client as any).storageManager.getConfigData();
}
const BASE_CONFIG = {baseUrl: 'https://example.com', clientId: 'test-client', clientSecret: 'test-secret'} as any;
const OIDC_META = {
backchannel_authentication_endpoint: 'https://example.com/oauth2/bc-authorize',
token_endpoint: 'https://example.com/oauth2/token',
};
async function initClientWithOIDC(store: MemoryStore): Promise<ThunderIDJavaScriptClient> {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize(BASE_CONFIG);
const sm = (client as any).storageManager;
await sm.setOIDCProviderMetaData(OIDC_META);
await sm.setTemporaryDataParameter('op_config_initiated', true);
return client;
}
function mockFetchOnce(body: unknown, ok = true, status = 200): void {
const serialized = typeof body === 'string' ? body : JSON.stringify(body);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValueOnce({
json: () => Promise.resolve(body),
text: () => Promise.resolve(serialized),
ok,
status,
statusText: ok ? 'OK' : 'Bad Request',
}),
);
}
describe('ThunderIDJavaScriptClient', () => {
let store: MemoryStore;
beforeEach(() => {
vi.clearAllMocks();
store = new MemoryStore();
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('initialize()', () => {
it('should apply DEFAULT_CONFIG baseline when no overrides are provided', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize({baseUrl: 'https://example.com', clientId: 'test-client'} as any);
const config = await getStoredConfig(client);
expect(config['enablePKCE']).toBe(true);
expect(config['sendCookiesInRequests']).toBe(true);
expect(config['tokenValidation'].idToken.clockTolerance).toBe(300);
expect(config['tokenValidation'].idToken.validate).toBe(true);
expect(config['tokenValidation'].idToken.validateIssuer).toBe(true);
});
it('should deep-merge partial tokenValidation, preserving sibling defaults', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize({
baseUrl: 'https://example.com',
clientId: 'test-client',
tokenValidation: {idToken: {validate: false}},
} as any);
const config = await getStoredConfig(client);
expect(config['tokenValidation'].idToken.validate).toBe(false);
expect(config['tokenValidation'].idToken.clockTolerance).toBe(300);
expect(config['tokenValidation'].idToken.validateIssuer).toBe(true);
});
it('should allow individual tokenValidation fields to be overridden independently', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize({
baseUrl: 'https://example.com',
clientId: 'test-client',
tokenValidation: {idToken: {clockTolerance: 60}},
} as any);
const config = await getStoredConfig(client);
expect(config['tokenValidation'].idToken.clockTolerance).toBe(60);
expect(config['tokenValidation'].idToken.validate).toBe(true);
expect(config['tokenValidation'].idToken.validateIssuer).toBe(true);
});
it('should set explicit fields (applicationId, scope) at highest precedence', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize({
applicationId: 'app-123',
baseUrl: 'https://example.com',
clientId: 'test-client',
scopes: ['openid', 'profile'],
} as any);
const config = await getStoredConfig(client);
expect(config['applicationId']).toBe('app-123');
expect(config['scope']).toContain('openid');
});
});
describe('initiateCIBA()', () => {
it('should throw when backchannel_authentication_endpoint is absent from OIDC metadata', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize(BASE_CONFIG);
const sm = (client as any).storageManager;
await sm.setOIDCProviderMetaData({token_endpoint: 'https://example.com/oauth2/token'});
await sm.setTemporaryDataParameter('op_config_initiated', true);
await expect(client.initiateCIBA({loginHint: 'user@example.com'})).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA1-NF01',
});
});
it('should throw when no hint is provided', async () => {
const client = await initClientWithOIDC(store);
await expect(client.initiateCIBA({})).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA1-IV01',
});
});
it('should throw when multiple hints are provided', async () => {
const client = await initClientWithOIDC(store);
await expect(client.initiateCIBA({loginHint: 'user@example.com', idTokenHint: 'id-token'})).rejects.toMatchObject(
{code: 'JS-AUTH_CORE-CIBA1-IV02'},
);
});
it('should throw when the server returns a non-ok response', async () => {
const client = await initClientWithOIDC(store);
mockFetchOnce({error: 'invalid_request'}, false, 400);
await expect(client.initiateCIBA({loginHint: 'user@example.com'})).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA1-HE03',
statusCode: 400,
});
});
it('should throw when the server response is missing auth_req_id', async () => {
const client = await initClientWithOIDC(store);
mockFetchOnce({expires_in: 120, interval: 5});
await expect(client.initiateCIBA({loginHint: 'user@example.com'})).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA1-PR04',
});
});
it('should return authReqId, interval, and expiresIn on success', async () => {
const client = await initClientWithOIDC(store);
mockFetchOnce({auth_req_id: 'req-123', expires_in: 300, interval: 5});
const result = await client.initiateCIBA({loginHint: 'user@example.com'});
expect(result).toEqual({authReqId: 'req-123', expiresIn: 300, interval: 5});
});
it('should default interval to 5 and expiresIn to 120 when server omits them', async () => {
const client = await initClientWithOIDC(store);
mockFetchOnce({auth_req_id: 'req-456'});
const result = await client.initiateCIBA({loginHint: 'user@example.com'});
expect(result.interval).toBe(5);
expect(result.expiresIn).toBe(120);
});
it('should send Authorization: Basic header when using client_secret_basic', async () => {
const client = await initClientWithOIDC(store);
const fetchMock = vi.fn().mockResolvedValueOnce({
json: () => Promise.resolve({auth_req_id: 'req-789', expires_in: 120, interval: 5}),
text: () => Promise.resolve(JSON.stringify({auth_req_id: 'req-789', expires_in: 120, interval: 5})),
ok: true,
status: 200,
statusText: 'OK',
});
vi.stubGlobal('fetch', fetchMock);
await client.initiateCIBA({bindingMessage: 'Approve login', loginHint: 'user@example.com'});
const [, init] = fetchMock.mock.calls[0];
expect(init.headers.Authorization).toMatch(/^Basic /);
const body: URLSearchParams = init.body;
expect(body.has('client_secret')).toBe(false);
});
it('should send client_secret in body and no Authorization header when using client_secret_post', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize({...BASE_CONFIG, tokenRequest: {authMethod: 'client_secret_post'}});
const sm = (client as any).storageManager;
await sm.setOIDCProviderMetaData(OIDC_META);
await sm.setTemporaryDataParameter('op_config_initiated', true);
const fetchMock = vi.fn().mockResolvedValueOnce({
json: () => Promise.resolve({auth_req_id: 'req-post', expires_in: 120, interval: 5}),
text: () => Promise.resolve(JSON.stringify({auth_req_id: 'req-post', expires_in: 120, interval: 5})),
ok: true,
status: 200,
statusText: 'OK',
});
vi.stubGlobal('fetch', fetchMock);
await client.initiateCIBA({loginHint: 'user@example.com'});
const [, init] = fetchMock.mock.calls[0];
expect(init.headers.Authorization).toBeUndefined();
const body: URLSearchParams = init.body;
expect(body.get('client_secret')).toBe('test-secret');
});
});
describe('pollCIBA()', () => {
it('should throw when token_endpoint is absent from OIDC metadata', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize(BASE_CONFIG);
const sm = (client as any).storageManager;
await sm.setOIDCProviderMetaData({
backchannel_authentication_endpoint: 'https://example.com/oauth2/bc-authorize',
});
await sm.setTemporaryDataParameter('op_config_initiated', true);
await expect(client.pollCIBA('req-123', 5)).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA2-NF01',
});
});
it('should resolve with TokenResponse when the server approves on the first poll', async () => {
const client = await initClientWithOIDC(store);
const tokenResponse = {access_token: 'tok', expires_in: 3600};
mockHandleTokenResponse.mockResolvedValueOnce(tokenResponse);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValueOnce({
json: () => Promise.resolve(tokenResponse),
ok: true,
status: 200,
statusText: 'OK',
}),
);
const result = await client.pollCIBA('req-123', 0);
expect(result).toBe(tokenResponse);
expect(mockHandleTokenResponse).toHaveBeenCalledOnce();
});
it('should retry on authorization_pending and resolve on subsequent approval', async () => {
const client = await initClientWithOIDC(store);
const tokenResponse = {access_token: 'tok', expires_in: 3600};
mockHandleTokenResponse.mockResolvedValueOnce(tokenResponse);
const fetchMock = vi
.fn()
.mockResolvedValueOnce({
json: () => Promise.resolve({error: 'authorization_pending'}),
text: () => Promise.resolve(JSON.stringify({error: 'authorization_pending'})),
ok: false,
status: 400,
statusText: 'Bad Request',
})
.mockResolvedValueOnce({
json: () => Promise.resolve(tokenResponse),
text: () => Promise.resolve(JSON.stringify(tokenResponse)),
ok: true,
status: 200,
statusText: 'OK',
});
vi.stubGlobal('fetch', fetchMock);
const result = await client.pollCIBA('req-123', 0);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(result).toBe(tokenResponse);
});
it('should increase interval by 5 on slow_down and continue polling', async () => {
const client = await initClientWithOIDC(store);
const tokenResponse = {access_token: 'tok', expires_in: 3600};
mockHandleTokenResponse.mockResolvedValueOnce(tokenResponse);
const fetchMock = vi
.fn()
.mockResolvedValueOnce({
json: () => Promise.resolve({error: 'slow_down'}),
text: () => Promise.resolve(JSON.stringify({error: 'slow_down'})),
ok: false,
status: 400,
statusText: 'Bad Request',
})
.mockResolvedValueOnce({
json: () => Promise.resolve(tokenResponse),
text: () => Promise.resolve(JSON.stringify(tokenResponse)),
ok: true,
status: 200,
statusText: 'OK',
});
vi.stubGlobal('fetch', fetchMock);
const delays: number[] = [];
vi.stubGlobal('setTimeout', (fn: () => void, ms: number) => {
delays.push(ms);
fn();
return 0;
});
await client.pollCIBA('req-123', 2);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(delays[0]).toBe(2000);
expect(delays[1]).toBe(7000);
});
it('should throw on expired_token', async () => {
const client = await initClientWithOIDC(store);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValueOnce({
json: () => Promise.resolve({error: 'expired_token'}),
text: () => Promise.resolve(JSON.stringify({error: 'expired_token'})),
ok: false,
status: 400,
statusText: 'Bad Request',
}),
);
await expect(client.pollCIBA('req-123', 0)).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA2-HE03',
});
});
it('should throw on access_denied', async () => {
const client = await initClientWithOIDC(store);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValueOnce({
json: () => Promise.resolve({error: 'access_denied'}),
text: () => Promise.resolve(JSON.stringify({error: 'access_denied'})),
ok: false,
status: 400,
statusText: 'Bad Request',
}),
);
await expect(client.pollCIBA('req-123', 0)).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA2-HE03',
});
});
it('should throw immediately when AbortSignal is already aborted', async () => {
const client = await initClientWithOIDC(store);
const controller = new AbortController();
controller.abort();
await expect(client.pollCIBA('req-123', 0, {signal: controller.signal})).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA2-AB05',
});
});
it('should abort mid-sleep and reject without waiting for the full interval', async () => {
const client = await initClientWithOIDC(store);
const controller = new AbortController();
// Abort after a short delay while pollCIBA is sleeping before its first poll
const abortTimer = globalThis.setTimeout(() => controller.abort(), 10);
try {
await expect(client.pollCIBA('req-123', 60, {signal: controller.signal})).rejects.toMatchObject({
code: 'JS-AUTH_CORE-CIBA2-AB05',
});
} finally {
globalThis.clearTimeout(abortTimer);
}
});
});
describe('getSignOutUrl()', () => {
const END_SESSION = 'https://example.com/oauth2/logout';
async function initForSignOut(
overrides: Record<string, unknown>,
meta: Record<string, unknown> = {end_session_endpoint: END_SESSION},
): Promise<ThunderIDJavaScriptClient> {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize({...BASE_CONFIG, afterSignOutUrl: 'https://example.com/console', ...overrides});
const sm = (client as any).storageManager;
await sm.setOIDCProviderMetaData(meta);
await sm.setTemporaryDataParameter('op_config_initiated', true);
return client;
}
it('includes id_token_hint and post_logout_redirect_uri when sendIdTokenInLogoutRequest is true', async () => {
const client = await initForSignOut({sendIdTokenInLogoutRequest: true});
await (client as any).storageManager.setSessionData({id_token: 'test-id-token'});
const url = new URL(await (client as any).getSignOutUrl());
expect(`${url.origin}${url.pathname}`).toBe(END_SESSION);
expect(url.searchParams.get('id_token_hint')).toBe('test-id-token');
expect(url.searchParams.get('post_logout_redirect_uri')).toBe('https://example.com/console');
expect(url.searchParams.get('state')).toBe('sign_out_success');
expect(url.searchParams.has('client_id')).toBe(false);
});
it('sends client_id instead of id_token_hint when sendIdTokenInLogoutRequest is false', async () => {
const client = await initForSignOut({sendIdTokenInLogoutRequest: false});
const url = new URL(await (client as any).getSignOutUrl());
expect(url.searchParams.get('client_id')).toBe('test-client');
expect(url.searchParams.has('id_token_hint')).toBe(false);
expect(url.searchParams.get('post_logout_redirect_uri')).toBe('https://example.com/console');
});
it('throws when the OP advertises no end_session_endpoint', async () => {
const client = await initForSignOut(
{sendIdTokenInLogoutRequest: true},
{token_endpoint: 'https://example.com/oauth2/token'},
);
await expect((client as any).getSignOutUrl()).rejects.toMatchObject({code: 'JS-AUTH_CORE-GSOU-NF01'});
});
it('falls back to client_id when no ID token is available', async () => {
const client = await initForSignOut({sendIdTokenInLogoutRequest: true});
const url = new URL(await (client as any).getSignOutUrl());
expect(url.searchParams.get('client_id')).toBe('test-client');
expect(url.searchParams.has('id_token_hint')).toBe(false);
});
it('sends id_token_hint by default (no explicit flag) when an ID token is available', async () => {
const client = await initForSignOut({});
await (client as any).storageManager.setSessionData({id_token: 'test-id-token'});
const url = new URL(await (client as any).getSignOutUrl());
expect(url.searchParams.get('id_token_hint')).toBe('test-id-token');
expect(url.searchParams.has('client_id')).toBe(false);
});
});
describe('requestAccessTokenRevocation()', () => {
const REVOCATION_ENDPOINT = 'https://example.com/oauth2/revoke';
async function initForRevocation(): Promise<ThunderIDJavaScriptClient> {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize(BASE_CONFIG);
const sm = (client as any).storageManager;
await sm.setOIDCProviderMetaData({revocation_endpoint: REVOCATION_ENDPOINT});
await sm.setTemporaryDataParameter('op_config_initiated', true);
await sm.setSessionData({access_token: 'stored-access-token'});
return client;
}
it('reads the access token from storage when no override is passed', async () => {
const client = await initForRevocation();
mockFetchOnce({}, true, 200);
await (client as any).requestAccessTokenRevocation();
const [, requestInit] = (fetch as any).mock.calls[0];
expect(requestInit.body).toContain('token=stored-access-token');
});
it('uses the passed accessToken instead of reading storage, so a concurrent session clear cannot race it', async () => {
const client = await initForRevocation();
// Simulate the session having already been cleared by the time the request body is built.
await (client as any).storageManager.setSessionData({access_token: undefined});
mockFetchOnce({}, true, 200);
await (client as any).requestAccessTokenRevocation(undefined, 'snapshotted-access-token');
const [, requestInit] = (fetch as any).mock.calls[0];
expect(requestInit.body).toContain('token=snapshotted-access-token');
});
it('throws when the OP advertises no revocation_endpoint', async () => {
const client = new ThunderIDJavaScriptClient(store, {} as any);
await client.initialize(BASE_CONFIG);
const sm = (client as any).storageManager;
await sm.setOIDCProviderMetaData({token_endpoint: 'https://example.com/oauth2/token'});
await sm.setTemporaryDataParameter('op_config_initiated', true);
await expect((client as any).requestAccessTokenRevocation()).rejects.toMatchObject({
code: 'JS-AUTH_CORE-RAT3-NF01',
});
});
it('throws when the revocation request receives a non-200 response', async () => {
const client = await initForRevocation();
mockFetchOnce({error: 'invalid_token'}, false, 400);
await expect((client as any).requestAccessTokenRevocation()).rejects.toMatchObject({
code: 'JS-AUTH_CORE-RAT3-HE03',
});
});
});
});