@axa-fr/oidc-client 7.29.8 → 7.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +174 -0
- package/dist/events.d.ts +3 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/fetch.d.ts +2 -2
- package/dist/fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1339 -871
- package/dist/index.umd.cjs +2 -2
- package/dist/initSession.d.ts +2 -0
- package/dist/initSession.d.ts.map +1 -1
- package/dist/initWorker.d.ts +1 -25
- package/dist/initWorker.d.ts.map +1 -1
- package/dist/jwt.d.ts.map +1 -1
- package/dist/legacyCompatibility.spec.d.ts +2 -0
- package/dist/legacyCompatibility.spec.d.ts.map +1 -0
- package/dist/login.d.ts +2 -1
- package/dist/login.d.ts.map +1 -1
- package/dist/logout.d.ts.map +1 -1
- package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcServiceWorker.js +1049 -0
- package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcTrustedDomains.js +31 -0
- package/dist/oidc.d.ts +6 -1
- package/dist/oidc.d.ts.map +1 -1
- package/dist/oidcClient.d.ts +13 -2
- package/dist/oidcClient.d.ts.map +1 -1
- package/dist/oidcError.d.ts +5 -0
- package/dist/oidcError.d.ts.map +1 -1
- package/dist/parseTokens.d.ts +10 -0
- package/dist/parseTokens.d.ts.map +1 -1
- package/dist/protocol.d.ts +7 -1
- package/dist/protocol.d.ts.map +1 -1
- package/dist/renewTokens.d.ts +0 -6
- package/dist/renewTokens.d.ts.map +1 -1
- package/dist/requests.d.ts +3 -3
- package/dist/requests.d.ts.map +1 -1
- package/dist/resourceParameters.d.ts +9 -0
- package/dist/resourceParameters.d.ts.map +1 -0
- package/dist/resourceTokens.d.ts +34 -0
- package/dist/resourceTokens.d.ts.map +1 -0
- package/dist/resourceTokens.spec.d.ts +2 -0
- package/dist/resourceTokens.spec.d.ts.map +1 -0
- package/dist/silentLogin.d.ts +2 -1
- package/dist/silentLogin.d.ts.map +1 -1
- package/dist/types.d.ts +28 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +3 -3
- package/src/events.ts +3 -0
- package/src/fetch.ts +115 -15
- package/src/index.ts +4 -0
- package/src/initSession.ts +9 -0
- package/src/initWorker.ts +65 -13
- package/src/jwt.spec.ts +17 -0
- package/src/jwt.ts +4 -1
- package/src/legacyCompatibility.spec.ts +142 -0
- package/src/login.ts +91 -29
- package/src/logout.ts +36 -0
- package/src/oidc.ts +71 -20
- package/src/oidcClient.ts +48 -3
- package/src/oidcError.ts +7 -0
- package/src/parseTokens.ts +14 -1
- package/src/protocol.ts +16 -1
- package/src/renewTokens.ts +19 -8
- package/src/requests.ts +13 -11
- package/src/resourceParameters.ts +85 -0
- package/src/resourceTokens.spec.ts +1271 -0
- package/src/resourceTokens.ts +708 -0
- package/src/silentLogin.spec.ts +87 -1
- package/src/silentLogin.ts +24 -22
- package/src/types.ts +34 -0
- package/src/version.ts +1 -1
|
@@ -0,0 +1,1271 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { base64urlOfHashOfASCIIEncodingAsync } from './crypto';
|
|
4
|
+
import { eventNames } from './events';
|
|
5
|
+
import { initSession } from './initSession';
|
|
6
|
+
import { initWorkerAsync, registrationCache } from './initWorker';
|
|
7
|
+
import { generateJwkAsync } from './jwt';
|
|
8
|
+
import { Oidc } from './oidc';
|
|
9
|
+
import { OidcClient } from './oidcClient';
|
|
10
|
+
import { OidcError, OidcErrorCode } from './oidcError';
|
|
11
|
+
import { parseJwt, parseOriginalTokens, TokenRenewMode, Tokens } from './parseTokens';
|
|
12
|
+
import { getResourceContextName } from './protocol';
|
|
13
|
+
import {
|
|
14
|
+
performAuthorizationRequestAsync,
|
|
15
|
+
performFirstTokenRequestAsync,
|
|
16
|
+
performPushedAuthorizationRequestAsync,
|
|
17
|
+
performTokenRequestAsync,
|
|
18
|
+
} from './requests';
|
|
19
|
+
import {
|
|
20
|
+
cancelResourceTransactions,
|
|
21
|
+
getCallbackResource,
|
|
22
|
+
rememberResourceTransaction,
|
|
23
|
+
} from './resourceParameters';
|
|
24
|
+
import timer from './timer';
|
|
25
|
+
import type { Fetch, OidcConfiguration } from './types';
|
|
26
|
+
import { TokenAutomaticRenewMode } from './types';
|
|
27
|
+
import codeVersion from './version';
|
|
28
|
+
|
|
29
|
+
class TestStorage implements Storage {
|
|
30
|
+
[key: string]: unknown;
|
|
31
|
+
get length(): number {
|
|
32
|
+
return Object.keys(this).length;
|
|
33
|
+
}
|
|
34
|
+
clear(): void {
|
|
35
|
+
for (const key of Object.keys(this)) delete this[key];
|
|
36
|
+
}
|
|
37
|
+
getItem(key: string): string | null {
|
|
38
|
+
return typeof this[key] === 'string' ? this[key] : null;
|
|
39
|
+
}
|
|
40
|
+
key(index: number): string | null {
|
|
41
|
+
return Object.keys(this)[index] ?? null;
|
|
42
|
+
}
|
|
43
|
+
removeItem(key: string): void {
|
|
44
|
+
delete this[key];
|
|
45
|
+
}
|
|
46
|
+
setItem(key: string, value: string): void {
|
|
47
|
+
this[key] = value;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const issuer = 'https://issuer.example.com';
|
|
52
|
+
const resourceA = 'urn:example:api:a';
|
|
53
|
+
const resourceB = 'urn:example:api:b';
|
|
54
|
+
const jwt = (payload: Record<string, unknown>): string =>
|
|
55
|
+
`e30.${btoa(JSON.stringify(payload))}.signature`;
|
|
56
|
+
let storage: TestStorage;
|
|
57
|
+
let oidc: Oidc;
|
|
58
|
+
let client: OidcClient;
|
|
59
|
+
let fetch: ReturnType<typeof vi.fn<Fetch>>;
|
|
60
|
+
|
|
61
|
+
const createTokens = (): Tokens =>
|
|
62
|
+
parseOriginalTokens(
|
|
63
|
+
{
|
|
64
|
+
access_token: 'default-token',
|
|
65
|
+
refresh_token: 'refresh-0',
|
|
66
|
+
expires_in: 3600,
|
|
67
|
+
token_type: 'Bearer',
|
|
68
|
+
id_token: jwt({
|
|
69
|
+
iss: issuer,
|
|
70
|
+
sub: 'user-one',
|
|
71
|
+
nonce: 'nonce',
|
|
72
|
+
iat: Date.now() / 1000,
|
|
73
|
+
exp: Date.now() / 1000 + 3600,
|
|
74
|
+
}),
|
|
75
|
+
},
|
|
76
|
+
null,
|
|
77
|
+
TokenRenewMode.access_token_invalid,
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
const tokenResponse = (resource: string, refreshToken?: string): Response =>
|
|
81
|
+
new Response(
|
|
82
|
+
JSON.stringify({
|
|
83
|
+
access_token: `${resource}-token`,
|
|
84
|
+
expires_in: 120,
|
|
85
|
+
token_type: 'Bearer',
|
|
86
|
+
...(refreshToken ? { refresh_token: refreshToken } : {}),
|
|
87
|
+
}),
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
beforeEach(() => {
|
|
91
|
+
storage = new TestStorage();
|
|
92
|
+
vi.stubGlobal('sessionStorage', storage);
|
|
93
|
+
vi.stubGlobal('localStorage', storage);
|
|
94
|
+
vi.stubGlobal('window', {
|
|
95
|
+
sessionStorage: storage,
|
|
96
|
+
location: { href: 'https://app.example.com/' },
|
|
97
|
+
crypto: globalThis.crypto,
|
|
98
|
+
});
|
|
99
|
+
vi.stubGlobal('navigator', { onLine: true });
|
|
100
|
+
fetch = vi.fn<Fetch>().mockImplementation(async (_input, init) => {
|
|
101
|
+
const resource = new URLSearchParams(String(init?.body)).get('resource');
|
|
102
|
+
return tokenResponse(resource);
|
|
103
|
+
});
|
|
104
|
+
vi.stubGlobal('fetch', fetch);
|
|
105
|
+
const configuration: OidcConfiguration = {
|
|
106
|
+
authority: issuer,
|
|
107
|
+
client_id: 'client',
|
|
108
|
+
redirect_uri: 'https://app.example.com/callback',
|
|
109
|
+
scope: 'openid read write',
|
|
110
|
+
authority_configuration: {
|
|
111
|
+
issuer,
|
|
112
|
+
authorization_endpoint: `${issuer}/authorize`,
|
|
113
|
+
token_endpoint: `${issuer}/token`,
|
|
114
|
+
revocation_endpoint: `${issuer}/revoke`,
|
|
115
|
+
},
|
|
116
|
+
resources: [
|
|
117
|
+
{ resource: resourceA, allowedUrlPrefixes: ['https://api.example.com/a'], scope: 'read' },
|
|
118
|
+
{ resource: resourceB, allowedUrlPrefixes: ['https://api.example.com/b'], scope: 'write' },
|
|
119
|
+
],
|
|
120
|
+
resource: [resourceA, resourceB],
|
|
121
|
+
storage,
|
|
122
|
+
token_automatic_renew_mode: TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted,
|
|
123
|
+
refresh_time_before_tokens_expiration_in_second: 0,
|
|
124
|
+
};
|
|
125
|
+
oidc = new Oidc(configuration, 'default', () => fetch);
|
|
126
|
+
oidc.tokens = createTokens();
|
|
127
|
+
initSession('default', storage).setTokens(oidc.tokens);
|
|
128
|
+
initSession('default', storage).setNonceAsync({ nonce: 'nonce' });
|
|
129
|
+
client = new OidcClient(oidc);
|
|
130
|
+
oidc.location = {
|
|
131
|
+
open: vi.fn(),
|
|
132
|
+
reload: vi.fn(),
|
|
133
|
+
getCurrentHref: () => 'https://app.example.com/',
|
|
134
|
+
getPath: () => '/',
|
|
135
|
+
getOrigin: () => 'https://app.example.com',
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
afterEach(async () => {
|
|
140
|
+
await oidc.resourceTokens.clearAllAsync();
|
|
141
|
+
vi.restoreAllMocks();
|
|
142
|
+
vi.unstubAllGlobals();
|
|
143
|
+
vi.useRealTimers();
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
describe('resource-specific access tokens', () => {
|
|
147
|
+
it('forwards pre-redirect silent authorization failures instead of timing out', async () => {
|
|
148
|
+
oidc.configuration.silent_login_uri = 'https://app.example.com/silent-login';
|
|
149
|
+
oidc.configuration.silent_redirect_uri = 'https://app.example.com/silent-callback';
|
|
150
|
+
const postMessage = vi.fn();
|
|
151
|
+
vi.stubGlobal('window', { ...window, parent: { postMessage } });
|
|
152
|
+
const error = new OidcError(
|
|
153
|
+
OidcErrorCode.REQUEST_FAILED,
|
|
154
|
+
'The provider rejected the resource.',
|
|
155
|
+
{
|
|
156
|
+
phase: 'login',
|
|
157
|
+
retryable: false,
|
|
158
|
+
oauthError: 'invalid_target',
|
|
159
|
+
},
|
|
160
|
+
);
|
|
161
|
+
vi.spyOn(oidc, 'initAsync').mockRejectedValue(error);
|
|
162
|
+
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
163
|
+
await expect(oidc.loginAsync(undefined, { _oidc_resource: resourceA }, true)).rejects.toBe(
|
|
164
|
+
error,
|
|
165
|
+
);
|
|
166
|
+
expect(postMessage).toHaveBeenCalledWith(
|
|
167
|
+
expect.stringContaining('invalid_target'),
|
|
168
|
+
'https://app.example.com',
|
|
169
|
+
);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('shares concurrent login attempts before asynchronous resource clearing finishes', async () => {
|
|
173
|
+
let release: () => void;
|
|
174
|
+
const gate = new Promise<void>(resolve => {
|
|
175
|
+
release = resolve;
|
|
176
|
+
});
|
|
177
|
+
const clear = vi.spyOn(oidc.resourceTokens, 'clearAllAsync').mockReturnValue(gate);
|
|
178
|
+
vi.spyOn(oidc, 'initAsync').mockRejectedValue(new Error('Stop before authorization.'));
|
|
179
|
+
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
180
|
+
const first = oidc.loginAsync();
|
|
181
|
+
const second = oidc.loginAsync();
|
|
182
|
+
const clearingCalls = clear.mock.calls.length;
|
|
183
|
+
release();
|
|
184
|
+
await Promise.allSettled([first, second]);
|
|
185
|
+
expect(clearingCalls).toBe(1);
|
|
186
|
+
expect(oidc.initAsync).toHaveBeenCalledOnce();
|
|
187
|
+
expect(oidc.loginPromise).toBeNull();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('preserves configured worker query parameters when adding the version', async () => {
|
|
191
|
+
registrationCache.clear();
|
|
192
|
+
const register = vi.fn().mockRejectedValue(new Error('Stop before registration.'));
|
|
193
|
+
vi.stubGlobal('navigator', { serviceWorker: { register } });
|
|
194
|
+
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
195
|
+
await expect(
|
|
196
|
+
initWorkerAsync(
|
|
197
|
+
{
|
|
198
|
+
...oidc.configuration,
|
|
199
|
+
service_worker_activate: () => true,
|
|
200
|
+
service_worker_relative_url: '/OidcServiceWorker.js?provider=openiddict',
|
|
201
|
+
},
|
|
202
|
+
'default',
|
|
203
|
+
),
|
|
204
|
+
).rejects.toThrow('Stop before registration.');
|
|
205
|
+
expect(register).toHaveBeenCalledWith(
|
|
206
|
+
`/OidcServiceWorker.js?provider=openiddict&v=${codeVersion}`,
|
|
207
|
+
{ updateViaCache: 'none' },
|
|
208
|
+
);
|
|
209
|
+
registrationCache.clear();
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const installSilentFrame = () => {
|
|
213
|
+
const frame = { contentWindow: {}, setAttribute: vi.fn(), style: {}, remove: vi.fn() };
|
|
214
|
+
const append = vi.fn();
|
|
215
|
+
let listener: (event: { origin: string; source: unknown; data: string }) => void;
|
|
216
|
+
vi.stubGlobal('window', {
|
|
217
|
+
...window,
|
|
218
|
+
addEventListener: (_type: string, callback: typeof listener) => {
|
|
219
|
+
listener = callback;
|
|
220
|
+
},
|
|
221
|
+
removeEventListener: vi.fn(),
|
|
222
|
+
});
|
|
223
|
+
vi.stubGlobal('document', { createElement: () => frame, body: { appendChild: append } });
|
|
224
|
+
oidc.configuration.silent_login_uri = 'https://app.example.com/silent-login';
|
|
225
|
+
oidc.configuration.silent_redirect_uri = 'https://app.example.com/silent-callback';
|
|
226
|
+
oidc.configuration.silent_login_timeout = 500;
|
|
227
|
+
return {
|
|
228
|
+
frame,
|
|
229
|
+
append,
|
|
230
|
+
reply: (data: string): void =>
|
|
231
|
+
listener({ origin: 'https://app.example.com', source: frame.contentWindow, data }),
|
|
232
|
+
};
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
it('automatically authorizes a new resource silently without replacing the original grant', async () => {
|
|
236
|
+
const { frame, append, reply } = installSilentFrame();
|
|
237
|
+
oidc.configuration.resource = resourceA;
|
|
238
|
+
const request = client.getAccessTokenForResourceAsync(resourceB);
|
|
239
|
+
await vi.waitFor(() => expect(append).toHaveBeenCalledOnce());
|
|
240
|
+
expect(frame.setAttribute.mock.calls[0][1]).toContain('prompt=none');
|
|
241
|
+
expect(frame.setAttribute.mock.calls[0][1]).toContain(
|
|
242
|
+
`resource=${encodeURIComponent(resourceB)}`,
|
|
243
|
+
);
|
|
244
|
+
reply(
|
|
245
|
+
`default_oidc_tokens:${JSON.stringify({ resource: resourceB, tokens: { ...createTokens(), accessToken: 'new-resource-token', refreshToken: 'own-grant-refresh' }, sessionState: 'session' })}`,
|
|
246
|
+
);
|
|
247
|
+
await expect(request).resolves.toMatchObject({
|
|
248
|
+
resource: resourceB,
|
|
249
|
+
accessToken: 'new-resource-token',
|
|
250
|
+
});
|
|
251
|
+
expect(oidc.tokens.refreshToken).toBe('refresh-0');
|
|
252
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
253
|
+
await client.getAccessTokenForResourceAsync(resourceB, { forceRenew: true });
|
|
254
|
+
expect(new URLSearchParams(String(fetch.mock.calls[0][1].body)).get('refresh_token')).toBe(
|
|
255
|
+
'own-grant-refresh',
|
|
256
|
+
);
|
|
257
|
+
expect(frame.remove).toHaveBeenCalledOnce();
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it.each(['consent_required', 'login_required', 'invalid_target'])(
|
|
261
|
+
'surfaces silent provider error %s without dropping the default session',
|
|
262
|
+
async error => {
|
|
263
|
+
const { append, reply } = installSilentFrame();
|
|
264
|
+
oidc.configuration.resource = resourceA;
|
|
265
|
+
const request = client.getAccessTokenForResourceAsync(resourceB);
|
|
266
|
+
const rejection = expect(request).rejects.toMatchObject({ oauthError: error });
|
|
267
|
+
await vi.waitFor(() => expect(append).toHaveBeenCalledOnce());
|
|
268
|
+
reply(
|
|
269
|
+
`default_oidc_error:${JSON.stringify({ error, error_description: 'Provider rejected this request' })}`,
|
|
270
|
+
);
|
|
271
|
+
await rejection;
|
|
272
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
273
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
274
|
+
},
|
|
275
|
+
);
|
|
276
|
+
|
|
277
|
+
it('rejects silent authorization for a different authenticated subject', async () => {
|
|
278
|
+
const { append, reply } = installSilentFrame();
|
|
279
|
+
oidc.configuration.resource = resourceA;
|
|
280
|
+
const request = client.getAccessTokenForResourceAsync(resourceB);
|
|
281
|
+
const rejection = expect(request).rejects.toMatchObject({
|
|
282
|
+
code: OidcErrorCode.RESOURCE_CONTEXT_MISMATCH,
|
|
283
|
+
});
|
|
284
|
+
await vi.waitFor(() => expect(append).toHaveBeenCalledOnce());
|
|
285
|
+
const tokens = createTokens();
|
|
286
|
+
tokens.idTokenPayload.sub = 'different-user';
|
|
287
|
+
reply(`default_oidc_tokens:${JSON.stringify({ resource: resourceB, tokens })}`);
|
|
288
|
+
await rejection;
|
|
289
|
+
expect(oidc.tokens.idTokenPayload.sub).toBe('user-one');
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it('reports a bounded silent timeout', async () => {
|
|
293
|
+
vi.useFakeTimers();
|
|
294
|
+
const { append } = installSilentFrame();
|
|
295
|
+
oidc.configuration.resource = resourceA;
|
|
296
|
+
const request = client.getAccessTokenForResourceAsync(resourceB);
|
|
297
|
+
const rejection = expect(request).rejects.toMatchObject({
|
|
298
|
+
code: OidcErrorCode.SILENT_LOGIN_TIMEOUT,
|
|
299
|
+
});
|
|
300
|
+
await vi.waitFor(() => expect(append).toHaveBeenCalledOnce());
|
|
301
|
+
await vi.advanceTimersByTimeAsync(500);
|
|
302
|
+
await rejection;
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it('renews acquired resources automatically before their access tokens expire', async () => {
|
|
306
|
+
vi.useFakeTimers();
|
|
307
|
+
vi.spyOn(timer, 'setTimeout').mockImplementation((handler, delay, ...args) =>
|
|
308
|
+
setTimeout(handler, delay, ...args),
|
|
309
|
+
);
|
|
310
|
+
vi.spyOn(timer, 'clearTimeout').mockImplementation(timeout => clearTimeout(timeout));
|
|
311
|
+
oidc.configuration.token_automatic_renew_mode =
|
|
312
|
+
TokenAutomaticRenewMode.AutomaticBeforeTokenExpiration;
|
|
313
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
314
|
+
await client.getAccessTokenForResourceAsync(resourceB);
|
|
315
|
+
await vi.advanceTimersByTimeAsync(120000);
|
|
316
|
+
expect(fetch).toHaveBeenCalledTimes(4);
|
|
317
|
+
expect(client.getAccessTokenForResource(resourceA)).not.toBeNull();
|
|
318
|
+
expect(client.getAccessTokenForResource(resourceB)).not.toBeNull();
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
it('caps renewal margins for short-lived API tokens without renewing siblings early', async () => {
|
|
322
|
+
vi.useFakeTimers();
|
|
323
|
+
vi.spyOn(timer, 'setTimeout').mockImplementation((handler, delay, ...args) =>
|
|
324
|
+
setTimeout(handler, delay, ...args),
|
|
325
|
+
);
|
|
326
|
+
vi.spyOn(timer, 'clearTimeout').mockImplementation(timeout => clearTimeout(timeout));
|
|
327
|
+
oidc.configuration.token_automatic_renew_mode =
|
|
328
|
+
TokenAutomaticRenewMode.AutomaticBeforeTokenExpiration;
|
|
329
|
+
oidc.configuration.refresh_time_before_tokens_expiration_in_second = 80;
|
|
330
|
+
fetch.mockImplementation(async (_input, init) => {
|
|
331
|
+
const resource = new URLSearchParams(String(init?.body)).get('resource');
|
|
332
|
+
return new Response(
|
|
333
|
+
JSON.stringify({
|
|
334
|
+
access_token: `${resource}-token`,
|
|
335
|
+
expires_in: resource === resourceA ? 20 : 120,
|
|
336
|
+
}),
|
|
337
|
+
);
|
|
338
|
+
});
|
|
339
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
340
|
+
const b = await client.getAccessTokenForResourceAsync(resourceB);
|
|
341
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
342
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
343
|
+
await vi.advanceTimersByTimeAsync(9999);
|
|
344
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
345
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
346
|
+
expect(fetch).toHaveBeenCalledTimes(3);
|
|
347
|
+
expect(new URLSearchParams(String(fetch.mock.calls[2][1].body)).get('resource')).toBe(
|
|
348
|
+
resourceA,
|
|
349
|
+
);
|
|
350
|
+
expect(client.getAccessTokenForResource(resourceB)).toEqual(b);
|
|
351
|
+
expect(client.getAccessTokenForResource(resourceA).expiresAt).toBeGreaterThan(
|
|
352
|
+
Date.now() / 1000 + 19,
|
|
353
|
+
);
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
it.each([-1, Number.NaN, Number.POSITIVE_INFINITY])(
|
|
357
|
+
'rejects an invalid renewal margin before acquisition: %s',
|
|
358
|
+
async margin => {
|
|
359
|
+
oidc.configuration.refresh_time_before_tokens_expiration_in_second = margin;
|
|
360
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toThrow(
|
|
361
|
+
'finite, non-negative renewal margin',
|
|
362
|
+
);
|
|
363
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
364
|
+
},
|
|
365
|
+
);
|
|
366
|
+
|
|
367
|
+
it('acquires and caches two API tokens without replacing the default token', async () => {
|
|
368
|
+
const a = await client.getAccessTokenForResourceAsync(resourceA);
|
|
369
|
+
const b = await client.getAccessTokenForResourceAsync(resourceB);
|
|
370
|
+
expect(a).toMatchObject({
|
|
371
|
+
resource: resourceA,
|
|
372
|
+
accessToken: `${resourceA}-token`,
|
|
373
|
+
issuer,
|
|
374
|
+
clientId: 'client',
|
|
375
|
+
configurationName: 'default',
|
|
376
|
+
});
|
|
377
|
+
expect(b.accessToken).toBe(`${resourceB}-token`);
|
|
378
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
379
|
+
expect(await client.getAccessTokenForResourceAsync(resourceA)).toEqual(a);
|
|
380
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
381
|
+
expect(client.getAccessTokenForResource(resourceB)).toEqual(b);
|
|
382
|
+
expect(a.expiresAt).toBeGreaterThan(Date.now() / 1000 + 100);
|
|
383
|
+
expect(a).not.toHaveProperty('refreshToken');
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
it('serializes rotating shared refresh tokens across different resources', async () => {
|
|
387
|
+
fetch.mockImplementation(async (_input, init) => {
|
|
388
|
+
const parameters = new URLSearchParams(String(init?.body));
|
|
389
|
+
return tokenResponse(
|
|
390
|
+
parameters.get('resource'),
|
|
391
|
+
parameters.get('refresh_token') === 'refresh-0' ? 'refresh-1' : 'refresh-2',
|
|
392
|
+
);
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
const [a, b] = await Promise.all([
|
|
396
|
+
client.getAccessTokenForResourceAsync(resourceA),
|
|
397
|
+
client.getAccessTokenForResourceAsync(resourceB),
|
|
398
|
+
]);
|
|
399
|
+
expect(
|
|
400
|
+
fetch.mock.calls.map(([, init]) =>
|
|
401
|
+
new URLSearchParams(String(init.body)).get('refresh_token'),
|
|
402
|
+
),
|
|
403
|
+
).toEqual(['refresh-0', 'refresh-1']);
|
|
404
|
+
expect(oidc.tokens.refreshToken).toBe('refresh-2');
|
|
405
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
406
|
+
expect(client.getAccessTokenForResource(resourceA)).toEqual(a);
|
|
407
|
+
expect(client.getAccessTokenForResource(resourceB)).toEqual(b);
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
it('notifies subscribers when a persisted resource token is restored without a network request', async () => {
|
|
411
|
+
const token = await client.getAccessTokenForResourceAsync(resourceA);
|
|
412
|
+
const restoredOidc = new Oidc(oidc.configuration, 'default', () => fetch);
|
|
413
|
+
restoredOidc.tokens = oidc.tokens;
|
|
414
|
+
const restoredClient = new OidcClient(restoredOidc);
|
|
415
|
+
const listener = vi.fn();
|
|
416
|
+
restoredOidc.subscribeEvents(listener);
|
|
417
|
+
|
|
418
|
+
expect(restoredClient.getAccessTokenForResource(resourceA)).toBeNull();
|
|
419
|
+
await expect(restoredClient.getAccessTokenForResourceAsync(resourceA)).resolves.toEqual(token);
|
|
420
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
421
|
+
expect(listener).toHaveBeenCalledWith(eventNames.resource_token_acquired, {
|
|
422
|
+
resource: resourceA,
|
|
423
|
+
});
|
|
424
|
+
listener.mockClear();
|
|
425
|
+
await restoredClient.getAccessTokenForResourceAsync(resourceA);
|
|
426
|
+
expect(listener).not.toHaveBeenCalled();
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
it('does not restore a persisted token after the resource is cleared during its cache lookup', async () => {
|
|
430
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
431
|
+
let release: () => void;
|
|
432
|
+
const gate = new Promise<void>(resolve => {
|
|
433
|
+
release = resolve;
|
|
434
|
+
});
|
|
435
|
+
const initialize = oidc.initAsync.bind(oidc);
|
|
436
|
+
const initialization = vi
|
|
437
|
+
.spyOn(oidc, 'initAsync')
|
|
438
|
+
.mockImplementationOnce(initialize)
|
|
439
|
+
.mockImplementationOnce(async (...parameters) => {
|
|
440
|
+
await gate;
|
|
441
|
+
return initialize(...parameters);
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
const acquisition = client.getAccessTokenForResourceAsync(resourceA);
|
|
445
|
+
const rejection = expect(acquisition).rejects.toMatchObject({
|
|
446
|
+
code: OidcErrorCode.RESOURCE_TOKEN_UNAVAILABLE,
|
|
447
|
+
});
|
|
448
|
+
await vi.waitFor(() => expect(initialization).toHaveBeenCalledTimes(2));
|
|
449
|
+
await client.clearResourceTokensAsync(resourceA);
|
|
450
|
+
release();
|
|
451
|
+
|
|
452
|
+
await rejection;
|
|
453
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
454
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
it('deduplicates concurrent requests for the same resource', async () => {
|
|
458
|
+
const requests = [
|
|
459
|
+
client.getAccessTokenForResourceAsync(resourceA),
|
|
460
|
+
client.getAccessTokenForResourceAsync(resourceA),
|
|
461
|
+
];
|
|
462
|
+
expect(requests[0]).toBe(requests[1]);
|
|
463
|
+
await Promise.all(requests);
|
|
464
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
it('renews only the expired or explicitly selected token', async () => {
|
|
468
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
469
|
+
const b = await client.getAccessTokenForResourceAsync(resourceB);
|
|
470
|
+
const name = getResourceContextName('default', resourceA);
|
|
471
|
+
const saved = JSON.parse(storage.getItem(`oidc.${name}`));
|
|
472
|
+
saved.tokens.expiresAt = Date.now() / 1000 - 1;
|
|
473
|
+
storage.setItem(`oidc.${name}`, JSON.stringify(saved));
|
|
474
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
475
|
+
await client.getAccessTokenForResourceAsync(resourceA, { forceRenew: true });
|
|
476
|
+
expect(fetch).toHaveBeenCalledTimes(4);
|
|
477
|
+
expect(client.getAccessTokenForResource(resourceB)).toEqual(b);
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
it('clears one resource without revoking the shared grant or discarding its sibling', async () => {
|
|
481
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
482
|
+
const b = await client.getAccessTokenForResourceAsync(resourceB);
|
|
483
|
+
await client.clearResourceTokensAsync(resourceA);
|
|
484
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
485
|
+
expect(client.getAccessTokenForResource(resourceB)).toEqual(b);
|
|
486
|
+
expect(oidc.tokens.refreshToken).toBe('refresh-0');
|
|
487
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
it.each(['issuer', 'clientId', 'configurationName', 'resource', 'subject'])(
|
|
491
|
+
'rejects cached tokens with a different %s',
|
|
492
|
+
async field => {
|
|
493
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
494
|
+
const key = `oidc.${getResourceContextName('default', resourceA)}`;
|
|
495
|
+
const saved = JSON.parse(storage.getItem(key));
|
|
496
|
+
saved.tokens.resourceContext[field] = 'wrong';
|
|
497
|
+
storage.setItem(key, JSON.stringify(saved));
|
|
498
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toMatchObject({
|
|
499
|
+
code: OidcErrorCode.RESOURCE_CONTEXT_MISMATCH,
|
|
500
|
+
});
|
|
501
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
502
|
+
},
|
|
503
|
+
);
|
|
504
|
+
|
|
505
|
+
it('preserves invalid_target without retrying without resource', async () => {
|
|
506
|
+
fetch.mockResolvedValue(
|
|
507
|
+
new Response(
|
|
508
|
+
JSON.stringify({ error: 'invalid_target', error_description: 'Resource is unsupported' }),
|
|
509
|
+
{ status: 400 },
|
|
510
|
+
),
|
|
511
|
+
);
|
|
512
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toMatchObject({
|
|
513
|
+
code: OidcErrorCode.INVALID_TARGET,
|
|
514
|
+
oauthError: 'invalid_target',
|
|
515
|
+
oauthErrorDescription: 'Resource is unsupported',
|
|
516
|
+
});
|
|
517
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
518
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
it('requires a silent authorization setup for resources outside the known grant', async () => {
|
|
522
|
+
oidc.configuration.resource = resourceA;
|
|
523
|
+
await expect(client.getAccessTokenForResourceAsync(resourceB)).rejects.toThrow(
|
|
524
|
+
'Configure silent_redirect_uri',
|
|
525
|
+
);
|
|
526
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
it('silently authorizes scopes not granted to the original session instead of reusing its refresh token', async () => {
|
|
530
|
+
oidc.tokens.scope = 'openid read';
|
|
531
|
+
initSession('default', storage).setTokens(oidc.tokens);
|
|
532
|
+
await expect(client.getAccessTokenForResourceAsync(resourceB)).rejects.toThrow(
|
|
533
|
+
'Configure silent_redirect_uri',
|
|
534
|
+
);
|
|
535
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
it('rejects resource worker fallback when the configured worker is unavailable', async () => {
|
|
539
|
+
oidc.configuration.service_worker_relative_url = '/OidcServiceWorker.js';
|
|
540
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toMatchObject({
|
|
541
|
+
code: OidcErrorCode.RESOURCE_WORKER_UNSUPPORTED,
|
|
542
|
+
});
|
|
543
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
544
|
+
oidc.configuration.service_worker_relative_url = undefined;
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
it('negotiates the base capability and rejects an older worker before creating resource state', async () => {
|
|
548
|
+
const postMessage = vi.fn(
|
|
549
|
+
(message: unknown, options?: Transferable[] | StructuredSerializeOptions): void => {
|
|
550
|
+
const port = (Array.isArray(options) ? options : options?.transfer)?.[0];
|
|
551
|
+
if (!(port instanceof MessagePort))
|
|
552
|
+
throw new Error('The adapter did not transfer a MessagePort.');
|
|
553
|
+
if (!message || typeof message !== 'object' || !('configurationName' in message))
|
|
554
|
+
throw new Error('The adapter omitted the configuration name.');
|
|
555
|
+
port.postMessage({
|
|
556
|
+
configurationName: message.configurationName,
|
|
557
|
+
version: codeVersion,
|
|
558
|
+
tokens: null,
|
|
559
|
+
});
|
|
560
|
+
},
|
|
561
|
+
);
|
|
562
|
+
const active: ServiceWorker = {
|
|
563
|
+
postMessage,
|
|
564
|
+
scriptURL: 'https://app.example.com/LegacyOidcServiceWorker.js',
|
|
565
|
+
state: 'activated',
|
|
566
|
+
onstatechange: null,
|
|
567
|
+
onerror: null,
|
|
568
|
+
addEventListener: vi.fn(),
|
|
569
|
+
removeEventListener: vi.fn(),
|
|
570
|
+
dispatchEvent: vi.fn().mockReturnValue(true),
|
|
571
|
+
};
|
|
572
|
+
const partialRegistration: Pick<
|
|
573
|
+
ServiceWorkerRegistration,
|
|
574
|
+
'active' | 'waiting' | 'installing' | 'addEventListener' | 'update'
|
|
575
|
+
> = {
|
|
576
|
+
active,
|
|
577
|
+
waiting: null,
|
|
578
|
+
installing: null,
|
|
579
|
+
addEventListener: vi.fn(),
|
|
580
|
+
update: vi.fn().mockResolvedValue(undefined),
|
|
581
|
+
};
|
|
582
|
+
const registration = partialRegistration as ServiceWorkerRegistration;
|
|
583
|
+
vi.stubGlobal('navigator', {
|
|
584
|
+
onLine: true,
|
|
585
|
+
serviceWorker: {
|
|
586
|
+
controller: active,
|
|
587
|
+
ready: Promise.resolve(registration),
|
|
588
|
+
addEventListener: vi.fn(),
|
|
589
|
+
},
|
|
590
|
+
});
|
|
591
|
+
oidc.configuration.service_worker_relative_url = '/LegacyOidcServiceWorker.js';
|
|
592
|
+
oidc.configuration.service_worker_activate = () => true;
|
|
593
|
+
oidc.configuration.service_worker_register = async (): Promise<ServiceWorkerRegistration> =>
|
|
594
|
+
registration;
|
|
595
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toMatchObject({
|
|
596
|
+
code: OidcErrorCode.RESOURCE_WORKER_UNSUPPORTED,
|
|
597
|
+
});
|
|
598
|
+
expect(postMessage).toHaveBeenCalledOnce();
|
|
599
|
+
expect(postMessage.mock.calls[0][0]).toMatchObject({ configurationName: 'default' });
|
|
600
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
601
|
+
registrationCache.clear();
|
|
602
|
+
oidc.configuration.service_worker_relative_url = undefined;
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
it('does not allow invalid identifiers or conflicting token extras', async () => {
|
|
606
|
+
await expect(
|
|
607
|
+
client.getAccessTokenForResourceAsync('https://unknown.example.com/'),
|
|
608
|
+
).rejects.toThrow('registered');
|
|
609
|
+
oidc.configuration.token_request_extras = { resource: resourceB };
|
|
610
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toMatchObject({
|
|
611
|
+
code: OidcErrorCode.INVALID_RESOURCE,
|
|
612
|
+
});
|
|
613
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
it('validates configured JWT audiences without assuming audience equals resource', async () => {
|
|
617
|
+
oidc.configuration.resources = [
|
|
618
|
+
{
|
|
619
|
+
resource: resourceA,
|
|
620
|
+
allowedUrlPrefixes: ['https://api.example.com/a'],
|
|
621
|
+
audiences: ['api-a'],
|
|
622
|
+
},
|
|
623
|
+
];
|
|
624
|
+
fetch.mockResolvedValue(
|
|
625
|
+
new Response(
|
|
626
|
+
JSON.stringify({
|
|
627
|
+
access_token: jwt({ aud: 'api-a', iss: issuer, exp: Date.now() / 1000 + 120 }),
|
|
628
|
+
expires_in: 120,
|
|
629
|
+
}),
|
|
630
|
+
),
|
|
631
|
+
);
|
|
632
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).resolves.toMatchObject({
|
|
633
|
+
resource: resourceA,
|
|
634
|
+
});
|
|
635
|
+
fetch.mockResolvedValue(
|
|
636
|
+
new Response(
|
|
637
|
+
JSON.stringify({
|
|
638
|
+
access_token: jwt({ aud: 'api-b', iss: issuer, exp: Date.now() / 1000 + 120 }),
|
|
639
|
+
expires_in: 120,
|
|
640
|
+
}),
|
|
641
|
+
),
|
|
642
|
+
);
|
|
643
|
+
await expect(
|
|
644
|
+
client.getAccessTokenForResourceAsync(resourceA, { forceRenew: true }),
|
|
645
|
+
).rejects.toMatchObject({ code: OidcErrorCode.RESOURCE_CONTEXT_MISMATCH });
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
it('does not resurrect a resource when a refresh completes after clearing it', async () => {
|
|
649
|
+
let resolve: (response: Response) => void;
|
|
650
|
+
fetch.mockImplementation(
|
|
651
|
+
() =>
|
|
652
|
+
new Promise<Response>(complete => {
|
|
653
|
+
resolve = complete;
|
|
654
|
+
}),
|
|
655
|
+
);
|
|
656
|
+
const request = client.getAccessTokenForResourceAsync(resourceA);
|
|
657
|
+
const rejection = expect(request).rejects.toThrow('cleared');
|
|
658
|
+
await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());
|
|
659
|
+
await client.clearResourceTokensAsync(resourceA);
|
|
660
|
+
resolve(tokenResponse(resourceA));
|
|
661
|
+
await rejection;
|
|
662
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
663
|
+
expect(
|
|
664
|
+
JSON.parse(storage.getItem(`oidc.${getResourceContextName('default', resourceA)}`)).tokens,
|
|
665
|
+
).toBeNull();
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
it('clears all resource state on local session logout', async () => {
|
|
669
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
670
|
+
await client.getAccessTokenForResourceAsync(resourceB);
|
|
671
|
+
await client.clearSessionAsync();
|
|
672
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
673
|
+
expect(client.getAccessTokenForResource(resourceB)).toBeNull();
|
|
674
|
+
expect(oidc.tokens).toBeNull();
|
|
675
|
+
});
|
|
676
|
+
|
|
677
|
+
it('retains shared refresh rotation after clearing only the requested resource', async () => {
|
|
678
|
+
let complete: (response: Response) => void;
|
|
679
|
+
fetch.mockImplementationOnce(
|
|
680
|
+
() =>
|
|
681
|
+
new Promise<Response>(resolve => {
|
|
682
|
+
complete = resolve;
|
|
683
|
+
}),
|
|
684
|
+
);
|
|
685
|
+
const pending = client.getAccessTokenForResourceAsync(resourceA);
|
|
686
|
+
const rejection = expect(pending).rejects.toThrow('cleared');
|
|
687
|
+
await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());
|
|
688
|
+
await client.clearResourceTokensAsync(resourceA);
|
|
689
|
+
complete(tokenResponse(resourceA, 'rotated-after-clear'));
|
|
690
|
+
await rejection;
|
|
691
|
+
expect(oidc.tokens.refreshToken).toBe('rotated-after-clear');
|
|
692
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
it('rejects a refresh response when the identity session changes during acquisition', async () => {
|
|
696
|
+
let complete: (response: Response) => void;
|
|
697
|
+
fetch.mockImplementationOnce(
|
|
698
|
+
() =>
|
|
699
|
+
new Promise<Response>(resolve => {
|
|
700
|
+
complete = resolve;
|
|
701
|
+
}),
|
|
702
|
+
);
|
|
703
|
+
const pending = client.getAccessTokenForResourceAsync(resourceA);
|
|
704
|
+
const rejection = expect(pending).rejects.toThrow('session changed');
|
|
705
|
+
await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());
|
|
706
|
+
const replacement = createTokens();
|
|
707
|
+
replacement.idTokenPayload.sub = 'new-user';
|
|
708
|
+
replacement.refreshToken = 'new-session-refresh';
|
|
709
|
+
oidc.tokens = replacement;
|
|
710
|
+
initSession('default', storage).setTokens(replacement);
|
|
711
|
+
complete(tokenResponse(resourceA, 'old-session-rotation'));
|
|
712
|
+
await rejection;
|
|
713
|
+
expect(oidc.tokens.refreshToken).toBe('new-session-refresh');
|
|
714
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
715
|
+
});
|
|
716
|
+
|
|
717
|
+
it('rejects insufficient returned scopes while retaining a rotated shared grant', async () => {
|
|
718
|
+
fetch.mockResolvedValue(
|
|
719
|
+
new Response(
|
|
720
|
+
JSON.stringify({
|
|
721
|
+
access_token: 'wrong-scope',
|
|
722
|
+
expires_in: 120,
|
|
723
|
+
refresh_token: 'rotated',
|
|
724
|
+
scope: 'write',
|
|
725
|
+
}),
|
|
726
|
+
),
|
|
727
|
+
);
|
|
728
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toThrow(
|
|
729
|
+
'required resource scopes',
|
|
730
|
+
);
|
|
731
|
+
expect(oidc.tokens.refreshToken).toBe('rotated');
|
|
732
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
it('surfaces network failures without silently substituting the default token', async () => {
|
|
736
|
+
fetch.mockRejectedValue(new TypeError('Failed to fetch'));
|
|
737
|
+
await expect(client.getAccessTokenForResourceAsync(resourceA)).rejects.toMatchObject({
|
|
738
|
+
code: OidcErrorCode.NETWORK_ERROR,
|
|
739
|
+
});
|
|
740
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
741
|
+
});
|
|
742
|
+
|
|
743
|
+
it('removes resource-owned transaction secrets without deleting the base context', async () => {
|
|
744
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
745
|
+
const session = initSession(getResourceContextName('default', resourceA), storage);
|
|
746
|
+
await session.setStateAsync('resource-state');
|
|
747
|
+
await session.setCodeVerifierAsync('resource-verifier');
|
|
748
|
+
await session.setNonceAsync({ nonce: 'resource-nonce' });
|
|
749
|
+
await session.setDemonstratingProofOfPossessionNonce('resource-dpop-nonce');
|
|
750
|
+
await client.clearResourceTokensAsync(resourceA);
|
|
751
|
+
expect(await session.getStateAsync()).toBeUndefined();
|
|
752
|
+
expect(await session.getCodeVerifierAsync()).toBeUndefined();
|
|
753
|
+
expect(await session.getNonceAsync()).toEqual({ nonce: undefined });
|
|
754
|
+
expect(session.getDemonstratingProofOfPossessionNonce()).toBeUndefined();
|
|
755
|
+
expect(await initSession('default', storage).getNonceAsync()).toEqual({ nonce: 'nonce' });
|
|
756
|
+
});
|
|
757
|
+
|
|
758
|
+
it('revokes resource tokens and independent grants without duplicating the shared refresh token', async () => {
|
|
759
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
760
|
+
await oidc.resourceTokens.acceptAuthorizationAsync(resourceB, {
|
|
761
|
+
...createTokens(),
|
|
762
|
+
accessToken: 'independent-access',
|
|
763
|
+
refreshToken: 'independent-refresh',
|
|
764
|
+
});
|
|
765
|
+
fetch.mockClear();
|
|
766
|
+
fetch.mockResolvedValue(new Response(null, { status: 200 }));
|
|
767
|
+
await oidc.logoutAsync(null, { 'no_reload:oidc': 'true' });
|
|
768
|
+
expect(
|
|
769
|
+
fetch.mock.calls
|
|
770
|
+
.map(([, init]) => new URLSearchParams(String(init.body)).get('token'))
|
|
771
|
+
.sort(),
|
|
772
|
+
).toEqual(
|
|
773
|
+
[
|
|
774
|
+
'default-token',
|
|
775
|
+
'refresh-0',
|
|
776
|
+
`${resourceA}-token`,
|
|
777
|
+
'independent-access',
|
|
778
|
+
'independent-refresh',
|
|
779
|
+
].sort(),
|
|
780
|
+
);
|
|
781
|
+
expect(oidc.tokens).toBeNull();
|
|
782
|
+
});
|
|
783
|
+
|
|
784
|
+
it('waits for a pending rotation before revoking the current grant during logout', async () => {
|
|
785
|
+
let complete: (response: Response) => void;
|
|
786
|
+
fetch.mockImplementationOnce(
|
|
787
|
+
() =>
|
|
788
|
+
new Promise<Response>(resolve => {
|
|
789
|
+
complete = resolve;
|
|
790
|
+
}),
|
|
791
|
+
);
|
|
792
|
+
const pending = client.getAccessTokenForResourceAsync(resourceA);
|
|
793
|
+
const rejection = expect(pending).rejects.toThrow('cleared');
|
|
794
|
+
await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());
|
|
795
|
+
fetch.mockResolvedValue(new Response(null, { status: 200 }));
|
|
796
|
+
const logout = oidc.logoutAsync(null, { 'no_reload:oidc': 'true' });
|
|
797
|
+
await vi.waitFor(() => expect(oidc.isLoggingOut).toBe(true));
|
|
798
|
+
complete(tokenResponse(resourceA, 'latest-refresh'));
|
|
799
|
+
await rejection;
|
|
800
|
+
await logout;
|
|
801
|
+
const revoked = fetch.mock.calls
|
|
802
|
+
.slice(1)
|
|
803
|
+
.map(([, init]) => new URLSearchParams(String(init.body)).get('token'));
|
|
804
|
+
expect(revoked).toContain('latest-refresh');
|
|
805
|
+
expect(revoked).toContain(`${resourceA}-token`);
|
|
806
|
+
expect(revoked).not.toContain('refresh-0');
|
|
807
|
+
});
|
|
808
|
+
|
|
809
|
+
it('rejects refresh-token reuse across separate authorization transactions', async () => {
|
|
810
|
+
await expect(
|
|
811
|
+
oidc.resourceTokens.acceptAuthorizationAsync(resourceB, createTokens()),
|
|
812
|
+
).rejects.toThrow('separate authorization');
|
|
813
|
+
expect(oidc.tokens.refreshToken).toBe('refresh-0');
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
it.each([false, true])(
|
|
817
|
+
'routes a real resource callback with DPoP=%s through its own state, nonce and PKCE without replacing default tokens',
|
|
818
|
+
async isDpop => {
|
|
819
|
+
oidc.configuration.demonstrating_proof_of_possession = isDpop;
|
|
820
|
+
const originalKey = isDpop
|
|
821
|
+
? await generateJwkAsync(window)(
|
|
822
|
+
oidc.configuration.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm,
|
|
823
|
+
)
|
|
824
|
+
: undefined;
|
|
825
|
+
if (originalKey)
|
|
826
|
+
await initSession('default', storage).setDemonstratingProofOfPossessionJwkAsync(
|
|
827
|
+
originalKey,
|
|
828
|
+
);
|
|
829
|
+
const context = initSession(getResourceContextName('default', resourceB), storage);
|
|
830
|
+
await context.setNonceAsync({ nonce: 'resource-nonce' });
|
|
831
|
+
await context.setStateAsync('resource-state');
|
|
832
|
+
await context.setCodeVerifierAsync('resource-verifier');
|
|
833
|
+
context.setLoginParams({ callbackPath: '/done', extras: {} });
|
|
834
|
+
rememberResourceTransaction('default', 'resource-state', resourceB);
|
|
835
|
+
oidc.location.getCurrentHref = () =>
|
|
836
|
+
'https://app.example.com/silent-callback?state=resource-state&code=resource-code';
|
|
837
|
+
fetch.mockResolvedValue(
|
|
838
|
+
new Response(
|
|
839
|
+
JSON.stringify({
|
|
840
|
+
access_token: 'callback-access',
|
|
841
|
+
refresh_token: 'callback-refresh',
|
|
842
|
+
token_type: isDpop ? 'DPoP' : 'Bearer',
|
|
843
|
+
expires_in: 120,
|
|
844
|
+
id_token: jwt({
|
|
845
|
+
iss: issuer,
|
|
846
|
+
sub: 'user-one',
|
|
847
|
+
nonce: 'resource-nonce',
|
|
848
|
+
exp: Date.now() / 1000 + 3600,
|
|
849
|
+
}),
|
|
850
|
+
}),
|
|
851
|
+
),
|
|
852
|
+
);
|
|
853
|
+
expect(await oidc.loginCallbackAsync(true)).toMatchObject({
|
|
854
|
+
callbackPath: '/done',
|
|
855
|
+
parsedTokens: { accessToken: 'callback-access' },
|
|
856
|
+
});
|
|
857
|
+
expect(new URLSearchParams(String(fetch.mock.calls[0][1].body)).get('resource')).toBe(
|
|
858
|
+
resourceB,
|
|
859
|
+
);
|
|
860
|
+
expect(new URLSearchParams(String(fetch.mock.calls[0][1].body)).get('code_verifier')).toBe(
|
|
861
|
+
'resource-verifier',
|
|
862
|
+
);
|
|
863
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
864
|
+
expect(getCallbackResource('default', oidc.location.getCurrentHref())).toBeUndefined();
|
|
865
|
+
if (originalKey) {
|
|
866
|
+
expect(initSession('default', storage).getDemonstratingProofOfPossessionJwkAsync()).toEqual(
|
|
867
|
+
originalKey,
|
|
868
|
+
);
|
|
869
|
+
expect(context.getDemonstratingProofOfPossessionJwkAsync()).toEqual(originalKey);
|
|
870
|
+
const apiFetch = vi.fn<Fetch>().mockResolvedValue(new Response());
|
|
871
|
+
await client.fetchForResource(resourceB, apiFetch)('https://api.example.com/b/items');
|
|
872
|
+
const proof = new Headers(apiFetch.mock.calls[0][1].headers).get('DPoP');
|
|
873
|
+
expect(parseJwt(proof.split('.')[1]).ath).toBe(
|
|
874
|
+
await base64urlOfHashOfASCIIEncodingAsync('callback-access'),
|
|
875
|
+
);
|
|
876
|
+
}
|
|
877
|
+
},
|
|
878
|
+
);
|
|
879
|
+
|
|
880
|
+
it('validates callback token extras after merging them with the selected resource', async () => {
|
|
881
|
+
const context = initSession(getResourceContextName('default', resourceB), storage);
|
|
882
|
+
await context.setNonceAsync({ nonce: 'resource-nonce' });
|
|
883
|
+
await context.setStateAsync('resource-state');
|
|
884
|
+
context.setLoginParams({ callbackPath: '/', extras: {} });
|
|
885
|
+
rememberResourceTransaction('default', 'resource-state', resourceB);
|
|
886
|
+
oidc.location.getCurrentHref = () =>
|
|
887
|
+
'https://app.example.com/silent-callback?state=resource-state&code=resource-code';
|
|
888
|
+
oidc.configuration.token_request_extras = { resource: resourceA };
|
|
889
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
890
|
+
await expect(oidc.loginCallbackAsync(true)).rejects.toMatchObject({
|
|
891
|
+
code: OidcErrorCode.INVALID_RESOURCE,
|
|
892
|
+
});
|
|
893
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
894
|
+
});
|
|
895
|
+
|
|
896
|
+
it.each(['missing ID token', 'missing nonce'])(
|
|
897
|
+
'rejects a real resource callback with %s before persisting tokens',
|
|
898
|
+
async failure => {
|
|
899
|
+
const context = initSession(getResourceContextName('default', resourceB), storage);
|
|
900
|
+
await context.setNonceAsync({ nonce: 'resource-nonce' });
|
|
901
|
+
await context.setStateAsync('resource-state');
|
|
902
|
+
await context.setCodeVerifierAsync('resource-verifier');
|
|
903
|
+
context.setLoginParams({ callbackPath: '/', extras: {} });
|
|
904
|
+
rememberResourceTransaction('default', 'resource-state', resourceB);
|
|
905
|
+
oidc.location.getCurrentHref = () =>
|
|
906
|
+
'https://app.example.com/silent-callback?state=resource-state&code=resource-code';
|
|
907
|
+
fetch.mockResolvedValueOnce(
|
|
908
|
+
new Response(
|
|
909
|
+
JSON.stringify({
|
|
910
|
+
access_token: 'unverified-resource',
|
|
911
|
+
expires_in: 120,
|
|
912
|
+
id_token:
|
|
913
|
+
failure === 'missing ID token'
|
|
914
|
+
? undefined
|
|
915
|
+
: jwt({
|
|
916
|
+
iss: issuer,
|
|
917
|
+
sub: 'user-one',
|
|
918
|
+
exp: Date.now() / 1000 + 3600,
|
|
919
|
+
}),
|
|
920
|
+
}),
|
|
921
|
+
),
|
|
922
|
+
);
|
|
923
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
924
|
+
await expect(oidc.loginCallbackAsync(true)).rejects.toMatchObject({
|
|
925
|
+
code: OidcErrorCode.INVALID_NONCE,
|
|
926
|
+
});
|
|
927
|
+
expect(context.getTokens()).toBeNull();
|
|
928
|
+
expect(oidc.tokens.accessToken).toBe('default-token');
|
|
929
|
+
},
|
|
930
|
+
);
|
|
931
|
+
|
|
932
|
+
it('retries a DPoP nonce challenge with the bound grant key and persists the successful nonce', async () => {
|
|
933
|
+
oidc.configuration.demonstrating_proof_of_possession = true;
|
|
934
|
+
const context = initSession('default', storage);
|
|
935
|
+
await context.setDemonstratingProofOfPossessionJwkAsync(
|
|
936
|
+
await generateJwkAsync(window)(
|
|
937
|
+
oidc.configuration.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm,
|
|
938
|
+
),
|
|
939
|
+
);
|
|
940
|
+
fetch
|
|
941
|
+
.mockResolvedValueOnce(
|
|
942
|
+
new Response(JSON.stringify({ error: 'use_dpop_nonce' }), {
|
|
943
|
+
status: 400,
|
|
944
|
+
headers: { 'DPoP-Nonce': 'required-nonce' },
|
|
945
|
+
}),
|
|
946
|
+
)
|
|
947
|
+
.mockResolvedValueOnce(
|
|
948
|
+
new Response(
|
|
949
|
+
JSON.stringify({ access_token: 'dpop-resource', token_type: 'DPoP', expires_in: 120 }),
|
|
950
|
+
{ headers: { 'DPoP-Nonce': 'successful-nonce' } },
|
|
951
|
+
),
|
|
952
|
+
);
|
|
953
|
+
await client.getAccessTokenForResourceAsync(resourceA);
|
|
954
|
+
expect(parseJwt(fetch.mock.calls[1][1].headers['DPoP'].split('.')[1])).toMatchObject({
|
|
955
|
+
nonce: 'required-nonce',
|
|
956
|
+
htm: 'POST',
|
|
957
|
+
htu: `${issuer}/token`,
|
|
958
|
+
});
|
|
959
|
+
expect(context.getDemonstratingProofOfPossessionNonce()).toBe('successful-nonce');
|
|
960
|
+
});
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
describe('resource-aware authenticated fetch', () => {
|
|
964
|
+
it('does not restore an API DPoP nonce from a response arriving after resource clearing', async () => {
|
|
965
|
+
oidc.configuration.demonstrating_proof_of_possession = true;
|
|
966
|
+
await initSession('default', storage).setDemonstratingProofOfPossessionJwkAsync(
|
|
967
|
+
await generateJwkAsync(window)(
|
|
968
|
+
oidc.configuration.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm,
|
|
969
|
+
),
|
|
970
|
+
);
|
|
971
|
+
fetch.mockResolvedValueOnce(
|
|
972
|
+
new Response(
|
|
973
|
+
JSON.stringify({
|
|
974
|
+
access_token: 'dpop-resource',
|
|
975
|
+
token_type: 'DPoP',
|
|
976
|
+
expires_in: 120,
|
|
977
|
+
}),
|
|
978
|
+
),
|
|
979
|
+
);
|
|
980
|
+
let complete: ((response: Response) => void) | undefined;
|
|
981
|
+
const apiFetch = vi.fn<Fetch>().mockImplementation(
|
|
982
|
+
() =>
|
|
983
|
+
new Promise<Response>(resolve => {
|
|
984
|
+
complete = resolve;
|
|
985
|
+
}),
|
|
986
|
+
);
|
|
987
|
+
const pending = client.fetchForResource(resourceA, apiFetch)('https://api.example.com/a/items');
|
|
988
|
+
await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledOnce());
|
|
989
|
+
await client.clearResourceTokensAsync(resourceA);
|
|
990
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
991
|
+
if (!complete) throw new Error('The API request did not start.');
|
|
992
|
+
complete(new Response('api', { headers: { 'DPoP-Nonce': 'late-nonce' } }));
|
|
993
|
+
expect((await pending).ok).toBe(true);
|
|
994
|
+
expect(
|
|
995
|
+
initSession(
|
|
996
|
+
getResourceContextName('default', resourceA),
|
|
997
|
+
storage,
|
|
998
|
+
).getDemonstratingProofOfPossessionApiNonce(),
|
|
999
|
+
).toBeUndefined();
|
|
1000
|
+
expect(client.getAccessTokenForResource(resourceA)).toBeNull();
|
|
1001
|
+
expect(warn).toHaveBeenCalledOnce();
|
|
1002
|
+
});
|
|
1003
|
+
|
|
1004
|
+
it('keeps API DPoP nonces separate by resource and from token-endpoint nonces', async () => {
|
|
1005
|
+
oidc.configuration.demonstrating_proof_of_possession = true;
|
|
1006
|
+
const base = initSession('default', storage);
|
|
1007
|
+
await base.setDemonstratingProofOfPossessionJwkAsync(
|
|
1008
|
+
await generateJwkAsync(window)(
|
|
1009
|
+
oidc.configuration.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm,
|
|
1010
|
+
),
|
|
1011
|
+
);
|
|
1012
|
+
await base.setDemonstratingProofOfPossessionNonce('authorization-nonce');
|
|
1013
|
+
fetch.mockImplementation(async (_input, init) => {
|
|
1014
|
+
const resource = new URLSearchParams(String(init.body)).get('resource');
|
|
1015
|
+
return new Response(
|
|
1016
|
+
JSON.stringify({ access_token: `${resource}-dpop`, token_type: 'DPoP', expires_in: 120 }),
|
|
1017
|
+
);
|
|
1018
|
+
});
|
|
1019
|
+
const apiFetch = vi.fn<Fetch>().mockImplementation(
|
|
1020
|
+
async input =>
|
|
1021
|
+
new Response('api', {
|
|
1022
|
+
headers: { 'DPoP-Nonce': String(input).includes('/a/') ? 'api-a-nonce' : 'api-b-nonce' },
|
|
1023
|
+
}),
|
|
1024
|
+
);
|
|
1025
|
+
const a = client.fetchForResource(resourceA, apiFetch);
|
|
1026
|
+
const b = client.fetchForResource(resourceB, apiFetch);
|
|
1027
|
+
await a('https://api.example.com/a/items');
|
|
1028
|
+
await b('https://api.example.com/b/items');
|
|
1029
|
+
await a('https://api.example.com/a/items');
|
|
1030
|
+
await b('https://api.example.com/b/items');
|
|
1031
|
+
const claims = apiFetch.mock.calls.map(([, init]) =>
|
|
1032
|
+
parseJwt(new Headers(init.headers).get('DPoP').split('.')[1]),
|
|
1033
|
+
);
|
|
1034
|
+
expect(claims[0]).not.toHaveProperty('nonce');
|
|
1035
|
+
expect(claims[1]).not.toHaveProperty('nonce');
|
|
1036
|
+
expect(claims[2].nonce).toBe('api-a-nonce');
|
|
1037
|
+
expect(claims[3].nonce).toBe('api-b-nonce');
|
|
1038
|
+
expect(base.getDemonstratingProofOfPossessionNonce()).toBe('authorization-nonce');
|
|
1039
|
+
await client.getAccessTokenForResourceAsync(resourceA, { forceRenew: true });
|
|
1040
|
+
expect(
|
|
1041
|
+
parseJwt(fetch.mock.calls[fetch.mock.calls.length - 1][1].headers['DPoP'].split('.')[1])
|
|
1042
|
+
.nonce,
|
|
1043
|
+
).toBe('authorization-nonce');
|
|
1044
|
+
await a('https://api.example.com/a/items');
|
|
1045
|
+
expect(
|
|
1046
|
+
parseJwt(
|
|
1047
|
+
new Headers(apiFetch.mock.calls[apiFetch.mock.calls.length - 1][1].headers)
|
|
1048
|
+
.get('DPoP')
|
|
1049
|
+
.split('.')[1],
|
|
1050
|
+
).nonce,
|
|
1051
|
+
).toBe('api-a-nonce');
|
|
1052
|
+
await client.clearResourceTokensAsync(resourceA);
|
|
1053
|
+
expect(
|
|
1054
|
+
initSession(
|
|
1055
|
+
getResourceContextName('default', resourceA),
|
|
1056
|
+
storage,
|
|
1057
|
+
).getDemonstratingProofOfPossessionApiNonce(),
|
|
1058
|
+
).toBeUndefined();
|
|
1059
|
+
expect(
|
|
1060
|
+
initSession(
|
|
1061
|
+
getResourceContextName('default', resourceB),
|
|
1062
|
+
storage,
|
|
1063
|
+
).getDemonstratingProofOfPossessionApiNonce(),
|
|
1064
|
+
).toBe('api-b-nonce');
|
|
1065
|
+
});
|
|
1066
|
+
it.each(['https://api.example.com/b', 'https://api.example.com/v2/items'])(
|
|
1067
|
+
'never reuses the default token for a managed API origin without selection: %s',
|
|
1068
|
+
async destination => {
|
|
1069
|
+
const apiFetch = vi.fn<Fetch>();
|
|
1070
|
+
await expect(client.fetchWithTokens(apiFetch)(destination)).rejects.toThrow(
|
|
1071
|
+
'Select a resource explicitly',
|
|
1072
|
+
);
|
|
1073
|
+
expect(apiFetch).not.toHaveBeenCalled();
|
|
1074
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
1075
|
+
},
|
|
1076
|
+
);
|
|
1077
|
+
it.each([resourceA, resourceB])('attaches only the token for %s', async resource => {
|
|
1078
|
+
const response = new Response('api response');
|
|
1079
|
+
const apiFetch = vi.fn<Fetch>().mockResolvedValue(response);
|
|
1080
|
+
const path = resource === resourceA ? 'a' : 'b';
|
|
1081
|
+
expect(
|
|
1082
|
+
await client.fetchForResource(resource, apiFetch)(`https://api.example.com/${path}/items`),
|
|
1083
|
+
).toBe(response);
|
|
1084
|
+
expect(new Headers(apiFetch.mock.calls[0][1].headers).get('Authorization')).toBe(
|
|
1085
|
+
`Bearer ${resource}-token`,
|
|
1086
|
+
);
|
|
1087
|
+
expect(apiFetch.mock.calls[0][1].redirect).toBe('error');
|
|
1088
|
+
});
|
|
1089
|
+
|
|
1090
|
+
it.each([
|
|
1091
|
+
'https://api.example.com/b/items',
|
|
1092
|
+
'https://api.example.com.evil.test/a',
|
|
1093
|
+
'https://api.example.com/a-other',
|
|
1094
|
+
])('does not acquire or dispatch tokens to %s', async destination => {
|
|
1095
|
+
const apiFetch = vi.fn<Fetch>();
|
|
1096
|
+
await expect(client.fetchForResource(resourceA, apiFetch)(destination)).rejects.toMatchObject({
|
|
1097
|
+
code: OidcErrorCode.INVALID_RESOURCE,
|
|
1098
|
+
});
|
|
1099
|
+
expect(apiFetch).not.toHaveBeenCalled();
|
|
1100
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
1101
|
+
});
|
|
1102
|
+
|
|
1103
|
+
it('rejects redirect following before acquisition or dispatch', async () => {
|
|
1104
|
+
const apiFetch = vi.fn<Fetch>();
|
|
1105
|
+
await expect(
|
|
1106
|
+
client.fetchForResource(resourceA, apiFetch)('https://api.example.com/a', {
|
|
1107
|
+
redirect: 'follow',
|
|
1108
|
+
}),
|
|
1109
|
+
).rejects.toThrow('redirects');
|
|
1110
|
+
expect(apiFetch).not.toHaveBeenCalled();
|
|
1111
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
1112
|
+
});
|
|
1113
|
+
|
|
1114
|
+
it.each([undefined, 'https://%'])(
|
|
1115
|
+
'rejects invalid explicit selectors or URLs without default-token fallback',
|
|
1116
|
+
async value => {
|
|
1117
|
+
const apiFetch = vi.fn<Fetch>();
|
|
1118
|
+
const request =
|
|
1119
|
+
value === undefined
|
|
1120
|
+
? client.fetchWithTokens(apiFetch, false, { resource: value })(
|
|
1121
|
+
'https://api.example.com/a',
|
|
1122
|
+
)
|
|
1123
|
+
: client.fetchForResource(resourceA, apiFetch)(value);
|
|
1124
|
+
await expect(request).rejects.toMatchObject({ code: OidcErrorCode.INVALID_RESOURCE });
|
|
1125
|
+
expect(apiFetch).not.toHaveBeenCalled();
|
|
1126
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
1127
|
+
},
|
|
1128
|
+
);
|
|
1129
|
+
|
|
1130
|
+
it('preserves Request method, body and signal and does not mutate headers', async () => {
|
|
1131
|
+
const controller = new AbortController();
|
|
1132
|
+
const input = new Request('https://api.example.com/a/items', {
|
|
1133
|
+
method: 'POST',
|
|
1134
|
+
body: 'payload',
|
|
1135
|
+
signal: controller.signal,
|
|
1136
|
+
headers: { 'X-Custom': 'kept' },
|
|
1137
|
+
});
|
|
1138
|
+
const headers = new Headers({ 'X-Init': 'kept' });
|
|
1139
|
+
const apiFetch = vi.fn<Fetch>().mockResolvedValue(new Response());
|
|
1140
|
+
await client.fetchWithTokens(apiFetch, false, { resource: resourceA })(input, { headers });
|
|
1141
|
+
const [request, init] = apiFetch.mock.calls[0];
|
|
1142
|
+
expect(request).toBe(input);
|
|
1143
|
+
expect(init.method).toBe('POST');
|
|
1144
|
+
expect(headers.has('Authorization')).toBe(false);
|
|
1145
|
+
expect(input.headers.has('Authorization')).toBe(false);
|
|
1146
|
+
expect(await input.text()).toBe('payload');
|
|
1147
|
+
controller.abort();
|
|
1148
|
+
expect(input.signal.aborted).toBe(true);
|
|
1149
|
+
});
|
|
1150
|
+
|
|
1151
|
+
it.each(['inferred', 'explicit'])(
|
|
1152
|
+
'uses the resource token and shared grant key in %s DPoP mode',
|
|
1153
|
+
async mode => {
|
|
1154
|
+
oidc.configuration.demonstrating_proof_of_possession = true;
|
|
1155
|
+
const key = await generateJwkAsync(window)(
|
|
1156
|
+
oidc.configuration.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm,
|
|
1157
|
+
);
|
|
1158
|
+
await initSession('default', storage).setDemonstratingProofOfPossessionJwkAsync(key);
|
|
1159
|
+
fetch.mockResolvedValue(
|
|
1160
|
+
new Response(
|
|
1161
|
+
JSON.stringify({
|
|
1162
|
+
access_token: 'resource-dpop-token',
|
|
1163
|
+
token_type: mode === 'inferred' ? 'DPoP' : 'Bearer',
|
|
1164
|
+
expires_in: 120,
|
|
1165
|
+
}),
|
|
1166
|
+
),
|
|
1167
|
+
);
|
|
1168
|
+
const apiFetch = vi.fn<Fetch>().mockResolvedValue(new Response());
|
|
1169
|
+
const authenticatedFetch =
|
|
1170
|
+
mode === 'inferred'
|
|
1171
|
+
? client.fetchForResource(resourceA, apiFetch)
|
|
1172
|
+
: client.fetchWithTokens(apiFetch, false, {
|
|
1173
|
+
resource: resourceA,
|
|
1174
|
+
demonstratingProofOfPossession: true,
|
|
1175
|
+
});
|
|
1176
|
+
await authenticatedFetch(
|
|
1177
|
+
new Request('https://api.example.com/a/items', { method: 'POST', body: 'payload' }),
|
|
1178
|
+
);
|
|
1179
|
+
const headers = new Headers(apiFetch.mock.calls[0][1].headers);
|
|
1180
|
+
expect(headers.get('Authorization')).toBe('DPoP resource-dpop-token');
|
|
1181
|
+
expect(parseJwt(headers.get('DPoP').split('.')[1])).toMatchObject({
|
|
1182
|
+
htm: 'POST',
|
|
1183
|
+
htu: 'https://api.example.com/a/items',
|
|
1184
|
+
});
|
|
1185
|
+
expect(headers.get('DPoP')).not.toContain('default-token');
|
|
1186
|
+
expect(parseJwt(headers.get('DPoP').split('.')[1]).ath).toBe(
|
|
1187
|
+
await base64urlOfHashOfASCIIEncodingAsync('resource-dpop-token'),
|
|
1188
|
+
);
|
|
1189
|
+
},
|
|
1190
|
+
);
|
|
1191
|
+
});
|
|
1192
|
+
|
|
1193
|
+
describe('OAuth repeated resource transport', () => {
|
|
1194
|
+
it.each(['authorization', 'PAR', 'code', 'refresh'])(
|
|
1195
|
+
'serializes repeated resources in %s without changing scope encoding',
|
|
1196
|
+
async kind => {
|
|
1197
|
+
const parameters = {
|
|
1198
|
+
client_id: 'client',
|
|
1199
|
+
state: 'state',
|
|
1200
|
+
scope: 'openid read',
|
|
1201
|
+
resource: [resourceA, resourceB],
|
|
1202
|
+
};
|
|
1203
|
+
const network = vi
|
|
1204
|
+
.fn<Fetch>()
|
|
1205
|
+
.mockResolvedValue(
|
|
1206
|
+
new Response(
|
|
1207
|
+
JSON.stringify(
|
|
1208
|
+
kind === 'PAR'
|
|
1209
|
+
? { request_uri: 'urn:request:one', expires_in: 60 }
|
|
1210
|
+
: { access_token: 'token', expires_in: 60 },
|
|
1211
|
+
),
|
|
1212
|
+
{ status: kind === 'PAR' ? 201 : 200 },
|
|
1213
|
+
),
|
|
1214
|
+
);
|
|
1215
|
+
const open = vi.fn();
|
|
1216
|
+
const location = {
|
|
1217
|
+
open,
|
|
1218
|
+
reload: vi.fn(),
|
|
1219
|
+
getCurrentHref: () => '',
|
|
1220
|
+
getPath: () => '',
|
|
1221
|
+
getOrigin: () => '',
|
|
1222
|
+
};
|
|
1223
|
+
const session = initSession('default', storage);
|
|
1224
|
+
let encoded: string;
|
|
1225
|
+
if (kind === 'authorization') {
|
|
1226
|
+
await performAuthorizationRequestAsync(session, location)(
|
|
1227
|
+
`${issuer}/authorize`,
|
|
1228
|
+
parameters,
|
|
1229
|
+
);
|
|
1230
|
+
encoded = open.mock.calls[0][0].split('?')[1];
|
|
1231
|
+
} else if (kind === 'PAR') {
|
|
1232
|
+
await performPushedAuthorizationRequestAsync(network)(`${issuer}/par`, parameters);
|
|
1233
|
+
encoded = String(network.mock.calls[0][1].body);
|
|
1234
|
+
} else if (kind === 'code') {
|
|
1235
|
+
vi.stubGlobal('fetch', network);
|
|
1236
|
+
await session.setCodeVerifierAsync('verifier');
|
|
1237
|
+
await performFirstTokenRequestAsync(session)(
|
|
1238
|
+
`${issuer}/token`,
|
|
1239
|
+
parameters,
|
|
1240
|
+
{},
|
|
1241
|
+
TokenRenewMode.access_token_invalid,
|
|
1242
|
+
);
|
|
1243
|
+
encoded = String(network.mock.calls[0][1].body);
|
|
1244
|
+
} else {
|
|
1245
|
+
await performTokenRequestAsync(network)(
|
|
1246
|
+
`${issuer}/token`,
|
|
1247
|
+
{ ...parameters, grant_type: 'refresh_token' },
|
|
1248
|
+
{},
|
|
1249
|
+
null,
|
|
1250
|
+
{},
|
|
1251
|
+
TokenRenewMode.access_token_invalid,
|
|
1252
|
+
);
|
|
1253
|
+
encoded = String(network.mock.calls[0][1].body);
|
|
1254
|
+
}
|
|
1255
|
+
expect(new URLSearchParams(encoded).getAll('resource')).toEqual([resourceA, resourceB]);
|
|
1256
|
+
expect(encoded).toContain('scope=openid%20read');
|
|
1257
|
+
},
|
|
1258
|
+
);
|
|
1259
|
+
|
|
1260
|
+
it('associates callback state with its resource and cancels only that resource', () => {
|
|
1261
|
+
rememberResourceTransaction('default', 'state-a', resourceA);
|
|
1262
|
+
rememberResourceTransaction('default', 'state-b', resourceB);
|
|
1263
|
+
cancelResourceTransactions('default', resourceA);
|
|
1264
|
+
expect(
|
|
1265
|
+
getCallbackResource('default', 'https://app.example.com/callback?state=state-a'),
|
|
1266
|
+
).toBeUndefined();
|
|
1267
|
+
expect(getCallbackResource('default', 'https://app.example.com/callback?state=state-b')).toBe(
|
|
1268
|
+
resourceB,
|
|
1269
|
+
);
|
|
1270
|
+
});
|
|
1271
|
+
});
|