forked from thunder-id/javascript-sdks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecuteEmbeddedSignInFlow.test.ts
More file actions
467 lines (396 loc) · 17.8 KB
/
Copy pathexecuteEmbeddedSignInFlow.test.ts
File metadata and controls
467 lines (396 loc) · 17.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
/**
* Copyright (c) 2026, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {EmbeddedSignInFlowResponse, EmbeddedSignInFlowStatus} from '../../models/embedded-signin-flow';
import logger from '../../utils/logger';
import executeEmbeddedSignInFlow from '../executeEmbeddedSignInFlow';
const URL = 'https://localhost:8090/flow/execute';
const mockFlowResponse = (overrides: Partial<EmbeddedSignInFlowResponse> = {}): EmbeddedSignInFlowResponse =>
({
flowStatus: EmbeddedSignInFlowStatus.Incomplete,
...overrides,
}) as EmbeddedSignInFlowResponse;
const captureRequestBody = (): Record<string, unknown> => {
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const requestInit = calls[calls.length - 1][1] as RequestInit;
return JSON.parse(requestInit.body as string) as Record<string, unknown>;
};
const captureRequestHeaders = (): Record<string, string> => {
const calls = (fetch as ReturnType<typeof vi.fn>).mock.calls;
const requestInit = calls[calls.length - 1][1] as RequestInit;
return requestInit.headers as Record<string, string>;
};
describe('executeEmbeddedSignInFlow', (): void => {
beforeEach((): void => {
vi.resetAllMocks();
global.fetch = vi.fn().mockResolvedValue({
json: () => Promise.resolve(mockFlowResponse()),
ok: true,
});
});
describe('verbose: true injection', (): void => {
it('injects verbose:true for a new flow start with applicationId and flowType', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION'},
url: URL,
});
expect(captureRequestBody()).toMatchObject({verbose: true});
});
it('injects verbose:true for a new flow start that also includes scopes', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION', scopes: ['openid', 'profile']},
url: URL,
});
const body = captureRequestBody();
expect(body).toMatchObject({verbose: true, inputs: {requested_permissions: 'openid profile'}});
expect(body).not.toHaveProperty('scopes');
});
it('injects verbose:true for a bare flow resumption (executionId only)', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {executionId: 'exec-abc'},
url: URL,
});
expect(captureRequestBody()).toMatchObject({verbose: true});
});
it('does NOT inject verbose:true for a step submission (executionId + inputs)', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {action: 'submit', executionId: 'exec-abc', inputs: {password: 'secret', username: 'user'}},
url: URL,
});
expect(captureRequestBody()).not.toHaveProperty('verbose');
});
it('strips a user-supplied verbose before applying internal logic', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {action: 'submit', executionId: 'exec-abc', inputs: {}, verbose: false},
url: URL,
});
expect(captureRequestBody()).not.toHaveProperty('verbose');
});
it('strips user-supplied verbose:true from step submissions', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {action: 'submit', executionId: 'exec-abc', inputs: {}, verbose: true},
url: URL,
});
expect(captureRequestBody()).not.toHaveProperty('verbose');
});
});
describe('scopes → inputs.requested_permissions translation', (): void => {
it('translates scopes to a space-separated inputs.requested_permissions string', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION', scopes: ['openid', 'profile', 'email']},
url: URL,
});
const body = captureRequestBody();
expect(body).toMatchObject({inputs: {requested_permissions: 'openid profile email'}});
expect(body).not.toHaveProperty('scopes');
});
it('does not add requested_permissions when scopes is absent', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION'},
url: URL,
});
expect(captureRequestBody()).not.toHaveProperty('inputs');
});
it('does not add requested_permissions when scopes is an empty array', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION', scopes: []},
url: URL,
});
const body = captureRequestBody();
expect(body).not.toHaveProperty('scopes');
expect(body).not.toHaveProperty('inputs');
});
});
describe('Flow-Secret header', (): void => {
it('sends the Flow Secret header on a new flow start', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
flowSecret: 'flow-secret-123',
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION'},
url: URL,
});
expect(captureRequestHeaders()).toMatchObject({'Flow-Secret': 'flow-secret-123'});
});
it('does NOT send the Flow Secret header on a step submission', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
flowSecret: 'flow-secret-123',
payload: {action: 'submit', executionId: 'exec-abc', inputs: {password: 'secret', username: 'user'}},
url: URL,
});
expect(captureRequestHeaders()).not.toHaveProperty('Flow-Secret');
});
it('does NOT send the Flow Secret header when no flowSecret is provided', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION'},
url: URL,
});
expect(captureRequestHeaders()).not.toHaveProperty('Flow-Secret');
});
});
describe('failure relay to the OAuth2 callback', (): void => {
const BASE_URL = 'https://localhost:8090';
const mockFlowThenCallback = (flowResponse: unknown, callbackResult: unknown, flowOk = true): void => {
global.fetch = vi
.fn()
.mockResolvedValueOnce({
json: () => Promise.resolve(flowResponse),
ok: flowOk,
status: flowOk ? 200 : 500,
statusText: flowOk ? 'OK' : 'Internal Server Error',
text: () => Promise.resolve(JSON.stringify(flowResponse)),
})
.mockResolvedValueOnce({
json: () => Promise.resolve(callbackResult),
ok: true,
});
};
/** An in-band flow failure whose relay is then rejected by the callback. */
const mockFlowThenCallbackRejection = (callbackErrorText: string): void => {
global.fetch = vi
.fn()
.mockResolvedValueOnce({
json: () =>
Promise.resolve({errorAssertion: 'signed-error-assertion', flowStatus: EmbeddedSignInFlowStatus.Error}),
ok: true,
})
.mockResolvedValueOnce({
ok: false,
status: 400,
statusText: 'Bad Request',
text: () => Promise.resolve(callbackErrorText),
});
};
it('relays an in-band errorAssertion and returns the client redirect', async (): Promise<void> => {
mockFlowThenCallback(
{errorAssertion: 'signed-error-assertion', flowStatus: EmbeddedSignInFlowStatus.Error},
{redirect_uri: 'https://client.example.com/cb?error=access_denied'},
);
const response = await executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
});
expect(fetch).toHaveBeenCalledTimes(2);
expect((fetch as ReturnType<typeof vi.fn>).mock.calls[1][0]).toBe(`${BASE_URL}/oauth2/auth/callback`);
// The error assertion is relayed in the same field a success assertion uses.
expect(captureRequestBody()).toEqual({assertion: 'signed-error-assertion', authId: 'auth-1'});
expect(response.flowStatus).toBe(EmbeddedSignInFlowStatus.Error);
expect((response as {redirectUrl?: string}).redirectUrl).toBe(
'https://client.example.com/cb?error=access_denied',
);
});
it('preserves the original error details when the callback returns no redirect', async (): Promise<void> => {
mockFlowThenCallback(
{
error: {code: 'FET-1066'},
errorAssertion: 'signed-error-assertion',
executionId: 'exec-abc',
flowStatus: EmbeddedSignInFlowStatus.Error,
},
{status: 'OK'},
);
const response = await executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
});
// CIBA callbacks return no redirect, so the caller still needs the flow error to display.
expect((response as {redirectUrl?: string}).redirectUrl).toBeUndefined();
expect((response as {executionId?: string}).executionId).toBe('exec-abc');
expect((response as {error?: {code?: string}}).error?.code).toBe('FET-1066');
});
it('relays the errorAssertion carried in a non-OK flow response body', async (): Promise<void> => {
mockFlowThenCallback(
{code: 'FES-1013', errorAssertion: 'signed-error-assertion'},
{redirect_uri: 'https://client.example.com/cb?error=server_error'},
false,
);
const response = await executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
});
// The error assertion is relayed in the same field a success assertion uses.
expect(captureRequestBody()).toEqual({assertion: 'signed-error-assertion', authId: 'auth-1'});
expect((response as {redirectUrl?: string}).redirectUrl).toBe('https://client.example.com/cb?error=server_error');
});
it('throws a generic error when the relay itself fails', async (): Promise<void> => {
global.fetch = vi
.fn()
.mockResolvedValueOnce({
ok: false,
status: 500,
statusText: 'Internal Server Error',
text: () => Promise.resolve(JSON.stringify({code: 'FES-1013', errorAssertion: 'signed-error-assertion'})),
})
.mockResolvedValueOnce({
ok: false,
status: 400,
statusText: 'Bad Request',
text: () => Promise.resolve('callback rejected'),
});
// A failed relay leaves the authorization request to expire, so it must surface rather than be
// swallowed. The message stays generic because it is rendered to the end user; the callback's
// own response is logged instead.
await expect(
executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
}),
).rejects.toThrow(/OAuth2 authorization failed/);
});
it('does not relay an in-band failure without an authId', async (): Promise<void> => {
global.fetch = vi.fn().mockResolvedValue({
json: () =>
Promise.resolve({errorAssertion: 'signed-error-assertion', flowStatus: EmbeddedSignInFlowStatus.Error}),
ok: true,
});
const response = await executeEmbeddedSignInFlow({
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
});
expect(fetch).toHaveBeenCalledTimes(1);
expect(response.flowStatus).toBe(EmbeddedSignInFlowStatus.Error);
expect((response as {redirectUrl?: string}).redirectUrl).toBeUndefined();
});
it('does not relay an in-band failure without an errorAssertion', async (): Promise<void> => {
global.fetch = vi.fn().mockResolvedValue({
json: () => Promise.resolve({flowStatus: EmbeddedSignInFlowStatus.Error}),
ok: true,
});
const response = await executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
});
expect(fetch).toHaveBeenCalledTimes(1);
expect(response.flowStatus).toBe(EmbeddedSignInFlowStatus.Error);
});
it('throws as before when a non-OK response carries no errorAssertion', async (): Promise<void> => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
statusText: 'Bad Request',
text: () => Promise.resolve('plain failure'),
});
await expect(
executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
}),
).rejects.toThrow(/plain failure/);
});
// The body of a real 4xx is structured JSON that simply has no assertion, e.g. an expired flow
// context. That reaches readErrorAssertion's non-throwing branch, unlike the plain-text case above.
it('throws the flow error when a JSON body carries no errorAssertion', async (): Promise<void> => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
statusText: 'Bad Request',
text: () => Promise.resolve(JSON.stringify({code: 'FES-1004', message: 'Invalid execution id'})),
});
await expect(
executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
}),
).rejects.toThrow(/FES-1004/);
// Only the flow request was made; there was nothing to relay.
expect(fetch).toHaveBeenCalledTimes(1);
});
// The callback's own response is deliberately kept out of the thrown error because that message is
// rendered to the end user, which makes this log the only surviving record of why a relay failed.
it('logs the callback response when the relay fails', async (): Promise<void> => {
const errorSpy = vi.spyOn(logger, 'error').mockImplementation((): void => {});
mockFlowThenCallbackRejection('callback rejected the assertion');
await expect(
executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
}),
).rejects.toThrow(/OAuth2 authorization failed/);
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('400'), 'callback rejected the assertion');
errorSpy.mockRestore();
});
});
describe('success relay to the OAuth2 callback', (): void => {
const BASE_URL = 'https://localhost:8090';
it('returns the client redirect when the callback accepts the assertion', async (): Promise<void> => {
global.fetch = vi
.fn()
.mockResolvedValueOnce({
json: () => Promise.resolve({assertion: 'signed-assertion', flowStatus: EmbeddedSignInFlowStatus.Complete}),
ok: true,
})
.mockResolvedValueOnce({
json: () => Promise.resolve({redirect_uri: 'https://client.example.com/cb?code=xyz'}),
ok: true,
});
const response = await executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
});
expect(captureRequestBody()).toEqual({assertion: 'signed-assertion', authId: 'auth-1'});
expect(response.flowStatus).toBe(EmbeddedSignInFlowStatus.Complete);
expect((response as {redirectUrl?: string}).redirectUrl).toBe('https://client.example.com/cb?code=xyz');
});
// Success and failure relays share postAuthCallback, so a rejected callback surfaces the same
// generic message either way, and the callback's own response is never put in front of the user.
it('throws a generic error without the callback body when the callback rejects', async (): Promise<void> => {
const errorSpy = vi.spyOn(logger, 'error').mockImplementation((): void => {});
global.fetch = vi
.fn()
.mockResolvedValueOnce({
json: () => Promise.resolve({assertion: 'signed-assertion', flowStatus: EmbeddedSignInFlowStatus.Complete}),
ok: true,
})
.mockResolvedValueOnce({
ok: false,
status: 400,
statusText: 'Bad Request',
text: () => Promise.resolve('assertion not bound to the authorization request'),
});
const error: Error = await executeEmbeddedSignInFlow({
authId: 'auth-1',
baseUrl: BASE_URL,
payload: {action: 'submit', executionId: 'exec-abc'},
}).catch((err: Error) => err);
expect(error.message).toBe('OAuth2 authorization failed');
expect(error.message).not.toContain('not bound');
expect(errorSpy).toHaveBeenCalledWith(
expect.stringContaining('400'),
'assertion not bound to the authorization request',
);
errorSpy.mockRestore();
});
});
it('throws when payload is missing', async (): Promise<void> => {
await expect(executeEmbeddedSignInFlow({url: URL})).rejects.toThrow('Authorization payload is required');
});
it('uses baseUrl to construct the endpoint when url is not provided', async (): Promise<void> => {
await executeEmbeddedSignInFlow({
baseUrl: 'https://localhost:8090',
payload: {applicationId: 'app-1', flowType: 'AUTHENTICATION'},
});
expect(fetch).toHaveBeenCalledWith('https://localhost:8090/flow/execute', expect.any(Object));
});
});