-
Notifications
You must be signed in to change notification settings - Fork 241
Expand file tree
/
Copy pathWebCredentialsManager.spec.ts
More file actions
374 lines (303 loc) · 12.3 KB
/
Copy pathWebCredentialsManager.spec.ts
File metadata and controls
374 lines (303 loc) · 12.3 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
import { Auth0Client } from '@auth0/auth0-spa-js';
import { WebCredentialsManager } from '../WebCredentialsManager';
// Mock the Auth0Client
jest.mock('@auth0/auth0-spa-js');
// Mock the core models with factory functions
jest.mock('../../../../core/models', () => ({
AuthError: jest.fn().mockImplementation(function (name, message, details) {
const error = new Error(message);
error.name = name;
if (details) Object.assign(error, details);
return error;
}),
CredentialsManagerError: jest
.fn()
.mockImplementation(function (originalError) {
const error = new Error(originalError.message);
error.name = originalError.name;
(error as any).type = 'MOCKED_TYPE';
return error;
}),
Credentials: jest.fn().mockImplementation(function (data) {
return Object.assign(this, data);
}),
}));
describe('WebCredentialsManager', () => {
let mockSpaClient: jest.Mocked<Auth0Client>;
let credentialsManager: WebCredentialsManager;
let consoleWarnSpy: jest.SpyInstance;
beforeEach(() => {
jest.clearAllMocks();
mockSpaClient = {
getTokenSilently: jest.fn().mockResolvedValue({}),
getIdTokenClaims: jest.fn().mockResolvedValue({}),
isAuthenticated: jest.fn().mockResolvedValue(false),
logout: jest.fn().mockResolvedValue(undefined),
} as any;
consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
credentialsManager = new WebCredentialsManager(mockSpaClient);
});
afterEach(() => {
consoleWarnSpy.mockRestore();
});
describe('saveCredentials', () => {
it('should log a warning and resolve without doing anything', async () => {
const credentials = {
idToken: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...',
accessToken: 'access_token_123',
tokenType: 'Bearer',
expiresAt: 1234567890,
scope: 'openid profile email',
};
await credentialsManager.saveCredentials(credentials);
expect(consoleWarnSpy).toHaveBeenCalledWith(
'`saveCredentials` is a no-op on the web. @auth0/auth0-spa-js handles credential storage automatically.'
);
});
});
describe('getCredentials', () => {
const mockTokenResponse = {
id_token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...',
access_token: 'access_token_123',
scope: 'openid profile email',
};
const mockIdTokenClaims = {
sub: 'auth0|123',
exp: 1234567890,
iat: 1234567800,
aud: 'test-client-id',
iss: 'https://test.auth0.com/',
__raw: 'raw-token-string',
};
it('should get credentials successfully with default parameters', async () => {
mockSpaClient.getTokenSilently.mockResolvedValue(mockTokenResponse);
mockSpaClient.getIdTokenClaims.mockResolvedValue(mockIdTokenClaims);
const result = await credentialsManager.getCredentials();
expect(mockSpaClient.getTokenSilently).toHaveBeenCalledWith({
cacheMode: 'on',
authorizationParams: { scope: undefined },
detailedResponse: true,
});
expect(mockSpaClient.getIdTokenClaims).toHaveBeenCalledTimes(1);
expect(result).toEqual({
idToken: mockTokenResponse.id_token,
accessToken: mockTokenResponse.access_token,
tokenType: 'Bearer',
expiresAt: mockIdTokenClaims.exp,
scope: mockTokenResponse.scope,
});
});
it('should get credentials with custom scope and parameters', async () => {
mockSpaClient.getTokenSilently.mockResolvedValue(mockTokenResponse);
mockSpaClient.getIdTokenClaims.mockResolvedValue(mockIdTokenClaims);
const scope = 'openid profile email read:data';
const parameters = { audience: 'https://api.example.com' };
await credentialsManager.getCredentials(scope, undefined, parameters);
expect(mockSpaClient.getTokenSilently).toHaveBeenCalledWith({
cacheMode: 'on',
authorizationParams: { ...parameters, scope },
detailedResponse: true,
});
});
it('should force refresh when forceRefresh is true', async () => {
mockSpaClient.getTokenSilently.mockResolvedValue(mockTokenResponse);
mockSpaClient.getIdTokenClaims.mockResolvedValue(mockIdTokenClaims);
await credentialsManager.getCredentials(
undefined,
undefined,
undefined,
true
);
expect(mockSpaClient.getTokenSilently).toHaveBeenCalledWith({
cacheMode: 'off',
authorizationParams: { scope: undefined },
detailedResponse: true,
});
});
it('should throw error when ID token claims are missing', async () => {
mockSpaClient.getTokenSilently.mockResolvedValue(mockTokenResponse);
mockSpaClient.getIdTokenClaims.mockResolvedValue(null);
await expect(credentialsManager.getCredentials()).rejects.toThrow(
'ID token or expiration claim is missing.'
);
});
it('should throw error when exp claim is missing', async () => {
mockSpaClient.getTokenSilently.mockResolvedValue(mockTokenResponse);
mockSpaClient.getIdTokenClaims.mockResolvedValue({
sub: 'auth0|123',
iat: 1234567800,
} as any);
await expect(credentialsManager.getCredentials()).rejects.toThrow(
'ID token or expiration claim is missing.'
);
});
it('should handle other errors with error and error_description', async () => {
const genericError = {
error: 'access_denied',
error_description: 'Access denied',
};
mockSpaClient.getTokenSilently.mockRejectedValue(genericError);
await expect(credentialsManager.getCredentials()).rejects.toThrow(
'Access denied'
);
});
it('should handle errors without error field', async () => {
const genericError = {
message: 'Something went wrong',
};
mockSpaClient.getTokenSilently.mockRejectedValue(genericError);
await expect(credentialsManager.getCredentials()).rejects.toThrow(
'Something went wrong'
);
});
});
describe('hasValidCredentials', () => {
it('should return true when user is authenticated', async () => {
mockSpaClient.isAuthenticated.mockResolvedValue(true);
const result = await credentialsManager.hasValidCredentials();
expect(result).toBe(true);
expect(mockSpaClient.isAuthenticated).toHaveBeenCalledTimes(1);
});
it('should return false when user is not authenticated', async () => {
mockSpaClient.isAuthenticated.mockResolvedValue(false);
const result = await credentialsManager.hasValidCredentials();
expect(result).toBe(false);
expect(mockSpaClient.isAuthenticated).toHaveBeenCalledTimes(1);
});
});
describe('clearCredentials', () => {
it('should call logout with openUrl false', async () => {
await credentialsManager.clearCredentials();
expect(mockSpaClient.logout).toHaveBeenCalledWith({ openUrl: false });
});
it('should handle logout errors', async () => {
const logoutError = new Error('Logout failed');
mockSpaClient.logout.mockRejectedValue(logoutError);
await expect(credentialsManager.clearCredentials()).rejects.toThrow(
'Logout failed'
);
});
});
describe('getApiCredentials', () => {
it('should throw CredentialsManagerError on login_required error', async () => {
const spaError = {
error: 'login_required',
error_description: 'Login is required',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
await expect(
credentialsManager.getApiCredentials('https://api.example.com')
).rejects.toThrow();
const error = await credentialsManager
.getApiCredentials('https://api.example.com')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
expect(error.name).toBe('login_required');
});
it('should throw CredentialsManagerError on invalid_grant error', async () => {
const spaError = {
error: 'invalid_grant',
error_description: 'Refresh token is invalid',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
const error = await credentialsManager
.getApiCredentials('https://api.example.com', 'read:data')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
expect(error.message).toBe('Refresh token is invalid');
});
it('should throw CredentialsManagerError on missing_refresh_token error', async () => {
const spaError = {
error: 'missing_refresh_token',
error_description: 'No refresh token available',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
const error = await credentialsManager
.getApiCredentials('https://api.example.com')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
});
it('should throw CredentialsManagerError on consent_required error', async () => {
const spaError = {
error: 'consent_required',
error_description: 'Consent is required',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
const error = await credentialsManager
.getApiCredentials('https://api.example.com')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
});
it('should throw CredentialsManagerError on network error', async () => {
const spaError = {
error: 'temporarily_unavailable',
error_description: 'Service temporarily unavailable',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
const error = await credentialsManager
.getApiCredentials('https://api.example.com')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
});
it('should throw CredentialsManagerError on invalid_scope error', async () => {
const spaError = {
error: 'invalid_scope',
error_description: 'The requested scope is invalid',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
const error = await credentialsManager
.getApiCredentials('https://api.example.com', 'invalid:scope')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
});
it('should throw CredentialsManagerError on unknown error', async () => {
const spaError = {
error: 'unknown_error',
error_description: 'An unknown error occurred',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
const error = await credentialsManager
.getApiCredentials('https://api.example.com')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
});
it('should handle error without error_description', async () => {
const spaError = {
error: 'invalid_grant',
message: 'The refresh token is invalid',
};
mockSpaClient.getTokenSilently.mockRejectedValue(spaError);
const error = await credentialsManager
.getApiCredentials('https://api.example.com')
.catch((e) => e);
expect(error.type).toBe('MOCKED_TYPE');
expect(error.message).toBe('The refresh token is invalid');
});
});
describe('clearApiCredentials', () => {
it('should log a warning without scope and resolve without doing anything', async () => {
await credentialsManager.clearApiCredentials('https://api.example.com');
expect(consoleWarnSpy).toHaveBeenCalledWith(
"'clearApiCredentials' for audience https://api.example.com is a no-op on the web. @auth0/auth0-spa-js handles credential storage automatically."
);
});
it('should log a warning with scope and resolve without doing anything', async () => {
await credentialsManager.clearApiCredentials(
'https://api.example.com',
'read:data write:data'
);
expect(consoleWarnSpy).toHaveBeenCalledWith(
"'clearApiCredentials' for audience https://api.example.com and scope read:data write:data is a no-op on the web. @auth0/auth0-spa-js handles credential storage automatically."
);
});
it('should handle empty scope string', async () => {
await credentialsManager.clearApiCredentials(
'https://api.example.com',
''
);
expect(consoleWarnSpy).toHaveBeenCalledWith(
"'clearApiCredentials' for audience https://api.example.com is a no-op on the web. @auth0/auth0-spa-js handles credential storage automatically."
);
});
});
});