forked from panva/node-oidc-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
651 lines (541 loc) · 19.7 KB
/
client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/* eslint-disable max-classes-per-file */
const { format, URL } = require('url');
const crypto = require('crypto');
const { STATUS_CODES } = require('http');
const { strict: assert } = require('assert');
const hash = require('object-hash');
const QuickLRU = require('quick-lru');
const KeyStore = require('../helpers/keystore');
const snakeCase = require('../helpers/_/snake_case');
const mapKeys = require('../helpers/_/map_keys');
const camelCase = require('../helpers/_/camel_case');
const isPlainObject = require('../helpers/_/is_plain_object');
const base64url = require('../helpers/base64url');
const request = require('../helpers/request');
const nanoid = require('../helpers/nanoid');
const epochTime = require('../helpers/epoch_time');
const instance = require('../helpers/weak_cache');
const constantEquals = require('../helpers/constant_equals');
const { InvalidClient, InvalidClientMetadata } = require('../helpers/errors');
const getSchema = require('../helpers/client_schema');
const { 'x5t#S256': x5cThumbprint } = require('../helpers/calculate_thumbprint');
const sectorIdentifier = require('../helpers/sector_identifier');
const { LOOPBACKS } = require('../consts/client_attributes');
// intentionally ignore x5t#S256 so that they are left to be calculated by the library
const EC_CURVES = new Set(['P-256', 'secp256k1', 'P-384', 'P-521']);
const OKP_SUBTYPES = new Set(['Ed25519', 'Ed448', 'X25519', 'X448']);
const backchannel = Symbol();
const fingerprint = (properties) => hash(properties, {
algorithm: 'sha256',
ignoreUnknown: true,
unorderedArrays: true,
});
const validateJWKS = (jwks) => {
if (jwks !== undefined) {
if (!Array.isArray(jwks.keys) || !jwks.keys.every(isPlainObject)) {
throw new InvalidClientMetadata('client JSON Web Key Set is invalid');
}
}
};
const nonSecretAuthMethods = new Set(['private_key_jwt', 'none', 'tls_client_auth', 'self_signed_tls_client_auth']);
const clientEncryptions = [
'id_token_encrypted_response_alg',
'request_object_encryption_alg',
'userinfo_encrypted_response_alg',
'introspection_encrypted_response_alg',
'authorization_encrypted_response_alg',
];
const signAlgAttributes = [
'id_token_signed_response_alg',
'request_object_signing_alg',
'token_endpoint_auth_signing_alg',
'userinfo_signed_response_alg',
'introspection_signed_response_alg',
'authorization_signed_response_alg',
];
function isSymmetricAlg(prop) {
const value = this[prop];
return /^(A|P|dir$)/.test(value);
}
function isHmac(prop) {
const value = this[prop];
return /^HS/.test(value);
}
function checkJWK(jwk) {
try {
assert(isPlainObject(jwk));
assert(typeof jwk.kty === 'string' && jwk.kty);
switch (jwk.kty) {
case 'EC':
assert(typeof jwk.crv === 'string' && jwk.crv);
if (!EC_CURVES.has(jwk.crv)) return undefined;
assert(typeof jwk.x === 'string' && jwk.x);
assert(typeof jwk.y === 'string' && jwk.y);
break;
case 'OKP':
assert(typeof jwk.crv === 'string' && jwk.crv);
if (!OKP_SUBTYPES.has(jwk.crv)) return undefined;
assert(typeof jwk.x === 'string' && jwk.x);
break;
case 'RSA':
assert(typeof jwk.e === 'string' && jwk.e);
assert(typeof jwk.n === 'string' && jwk.n);
break;
case 'oct':
break;
default:
return undefined;
}
assert(jwk.d === undefined && jwk.kty !== 'oct');
assert(jwk.alg === undefined || (typeof jwk.alg === 'string' && jwk.alg));
assert(jwk.kid === undefined || (typeof jwk.kid === 'string' && jwk.kid));
assert(jwk.use === undefined || (typeof jwk.use === 'string' && jwk.use));
assert(jwk.x5c === undefined || (Array.isArray(jwk.x5c) && jwk.x5c.every((x) => typeof x === 'string' && x)));
} catch {
throw new InvalidClientMetadata('client JSON Web Key Set is invalid');
}
return jwk;
}
function stripFragment(uri) {
return format(new URL(uri), { fragment: false });
}
function deriveEncryptionKey(secret, length) {
const digest = length <= 32 ? 'sha256' : length <= 48 ? 'sha384' : length <= 64 ? 'sha512' : false; // eslint-disable-line no-nested-ternary
if (!digest) {
throw new Error('unsupported symmetric encryption key derivation');
}
const derived = crypto.createHash(digest)
.update(secret)
.digest()
.slice(0, length);
return base64url.encodeBuffer(derived);
}
module.exports = function getClient(provider) {
const staticCache = new Map();
const dynamicCache = new QuickLRU({ maxSize: 100 });
const Schema = getSchema(provider);
const { IdToken } = provider;
let adapter;
function getAdapter() {
if (!adapter) adapter = new (instance(provider).Adapter)('Client');
return adapter;
}
async function sectorValidate(client) {
if (!instance(provider).configuration('sectorIdentifierUriValidate')(client)) {
return;
}
const { statusCode, body } = await request.call(provider, {
method: 'GET',
url: client.sectorIdentifierUri,
responseType: 'json',
}).catch((err) => {
throw new InvalidClientMetadata('could not load sector_identifier_uri response', err.message);
});
if (statusCode !== 200) {
throw new InvalidClientMetadata(`unexpected sector_identifier_uri response status code, expected 200 OK, got ${statusCode} ${STATUS_CODES[statusCode]}`);
}
try {
assert(Array.isArray(body), 'sector_identifier_uri must return single JSON array');
if (client.responseTypes.length) {
const match = client.redirectUris.every((uri) => body.includes(uri));
assert(
match,
'all registered redirect_uris must be included in the sector_identifier_uri response',
);
}
if (
client.grantTypes.includes('urn:openid:params:grant-type:ciba')
|| client.grantTypes.includes('urn:ietf:params:oauth:grant-type:device_code')
) {
assert(
body.includes(client.jwksUri),
"client's jwks_uri must be included in the sector_identifier_uri response",
);
}
} catch (err) {
throw new InvalidClientMetadata(err.message);
}
}
class ClientKeyStore extends KeyStore {
#client;
#provider = provider;
constructor(clientInstance) {
super();
this.#client = clientInstance;
}
get client() {
return this.#client;
}
get provider() {
return this.#provider;
}
get jwksUri() {
return this.client && this.client.jwksUri;
}
fresh() {
if (!this.jwksUri) return true;
const now = epochTime();
return !!this.freshUntil && this.freshUntil > now;
}
stale() {
return !this.fresh();
}
add(key) {
if (this.client.tokenEndpointAuthMethod === 'self_signed_tls_client_auth' && Array.isArray(key.x5c) && key.x5c.length) {
// eslint-disable-next-line no-param-reassign
key['x5t#S256'] = x5cThumbprint(key.x5c[0]);
}
super.add(key);
}
async refresh() {
if (this.fresh()) return;
if (!this.lock) {
this.lock = (async () => {
const { headers, body, statusCode } = await request.call(this.provider, {
method: 'GET',
url: this.jwksUri,
responseType: 'json',
});
// min refetch in 60 seconds unless cache headers say a longer response ttl
const freshUntil = [epochTime() + 60];
if (headers.expires) {
freshUntil.push(epochTime(Date.parse(headers.expires)));
}
if (headers['cache-control'] && /max-age=(\d+)/.test(headers['cache-control'])) {
const maxAge = parseInt(RegExp.$1, 10);
freshUntil.push(epochTime() + maxAge);
}
this.freshUntil = Math.max(...freshUntil.filter(Boolean));
if (statusCode !== 200) {
throw new Error(`unexpected jwks_uri response status code, expected 200 OK, got ${statusCode} ${STATUS_CODES[statusCode]}`);
}
validateJWKS(body);
this.clear();
body.keys
.map(checkJWK)
.filter(Boolean)
.forEach(ClientKeyStore.prototype.add.bind(this));
delete this.lock;
})().catch((err) => {
delete this.lock;
throw new InvalidClientMetadata('client JSON Web Key Set failed to be refreshed', err.error_description || err.message);
});
}
await this.lock;
}
}
function buildAsymmetricKeyStore(client) {
Object.defineProperty(client, 'asymmetricKeyStore', {
configurable: true,
get() {
const keystore = new ClientKeyStore(this);
Object.defineProperty(this, 'asymmetricKeyStore', {
configurable: false,
value: keystore,
});
return this.asymmetricKeyStore;
},
});
}
function buildSymmetricKeyStore(client) {
Object.defineProperty(client, 'symmetricKeyStore', {
configurable: false,
value: new KeyStore(),
});
const algs = new Set();
if (client.clientSecret) {
['token', 'introspection', 'revocation'].forEach((endpoint) => {
if (client[`${endpoint}EndpointAuthMethod`] === 'client_secret_jwt') {
if (client[`${endpoint}EndpointAuthSigningAlg`]) {
algs.add(client[`${endpoint}EndpointAuthSigningAlg`]);
} else {
(instance(provider).configuration(`${endpoint}EndpointAuthSigningAlgValues`) || [])
.forEach(Set.prototype.add.bind(algs));
}
}
});
instance(provider).configuration('requestObjectSigningAlgValues').forEach(Set.prototype.add.bind(algs));
instance(provider).configuration('requestObjectEncryptionAlgValues').forEach(Set.prototype.add.bind(algs));
if (instance(provider).configuration('requestObjectEncryptionAlgValues').includes('dir')) {
instance(provider).configuration('requestObjectEncryptionEncValues').forEach(Set.prototype.add.bind(algs));
}
[
'idTokenEncryptedResponse',
'userinfoEncryptedResponse',
'introspectionEncryptedResponse',
'authorizationEncryptedResponse',
].forEach((prop) => {
algs.add(client[`${prop}Alg`]);
if (client[`${prop}Alg`] === 'dir') {
algs.add(client[`${prop}Enc`]);
}
});
algs.delete(undefined);
for (const alg of algs) { // eslint-disable-line no-restricted-syntax
if (!(
alg.startsWith('HS')
|| alg.startsWith('PBES2')
|| /^A(\d{3})(?:GCM)?KW$/.test(alg)
|| /^A(\d{3})(?:GCM|CBC-HS(\d{3}))$/.test(alg)
)) {
algs.delete(alg);
}
}
// eslint-disable-next-line no-restricted-syntax
for (const alg of algs) {
if (alg.startsWith('HS')) {
// eslint-disable-next-line no-bitwise
const length = parseInt(alg.substr(-3), 10) >> 3;
let secret = Buffer.from(client.clientSecret);
if (secret.byteLength < length) {
const padded = Buffer.alloc(length);
padded.set(secret);
secret = padded;
}
client.symmetricKeyStore.add({
alg, use: 'sig', kty: 'oct', k: base64url.encodeBuffer(secret),
});
} else if (/^A(\d{3})(?:GCM)?KW$/.test(alg)) {
const len = parseInt(RegExp.$1, 10) / 8;
client.symmetricKeyStore.add({
alg, use: 'enc', kty: 'oct', k: deriveEncryptionKey(client.clientSecret, len),
});
} else if (/^A(\d{3})(?:GCM|CBC-HS(\d{3}))$/.test(alg)) {
const len = parseInt(RegExp.$2 || RegExp.$1, 10) / 8;
client.symmetricKeyStore.add({
alg, use: 'enc', kty: 'oct', k: deriveEncryptionKey(client.clientSecret, len),
});
} else if (alg.startsWith('PBES2')) {
client.symmetricKeyStore.add({
alg, use: 'enc', kty: 'oct', k: base64url.encode(client.clientSecret),
});
}
}
}
}
function addStatic(metadata) {
if (!isPlainObject(metadata) || !metadata.client_id) {
throw new InvalidClientMetadata('client_id is mandatory property for statically configured clients');
}
if (staticCache.has(metadata.client_id)) {
throw new InvalidClientMetadata('client_id must be unique amongst statically configured clients');
}
staticCache.set(metadata.client_id, JSON.parse(JSON.stringify(metadata)));
}
async function add(metadata, { ctx, store = false } = {}) {
const client = new Client(metadata, ctx); // eslint-disable-line no-use-before-define
if (client.sectorIdentifierUri !== undefined) {
await sectorValidate(client);
}
if (store) {
await getAdapter().upsert(client.clientId, client.metadata());
dynamicCache.set(fingerprint(metadata), client);
}
return client;
}
function remove(id) {
return getAdapter().destroy(id);
}
instance(provider).clientAdd = add;
instance(provider).clientAddStatic = addStatic;
instance(provider).clientRemove = remove;
class Client {
#sectorIdentifier = null;
constructor(metadata, ctx) {
const schema = new Schema(metadata, ctx);
Object.assign(this, mapKeys(schema, (value, key) => {
if (!instance(provider).RECOGNIZED_METADATA.includes(key)) {
return key;
}
return camelCase(key);
}));
buildAsymmetricKeyStore(this);
buildSymmetricKeyStore(this);
validateJWKS(this.jwks);
if (this.jwks) {
this.jwks.keys
.map(checkJWK)
.filter(Boolean)
.forEach(ClientKeyStore.prototype.add.bind(this.asymmetricKeyStore));
}
}
async [backchannel](mode, backchannelAuthenticationRequest, payload) {
assert(this.backchannelClientNotificationEndpoint);
assert.equal(this.backchannelTokenDeliveryMode, mode);
assert(backchannelAuthenticationRequest);
assert(backchannelAuthenticationRequest.jti);
assert.equal(backchannelAuthenticationRequest.kind, 'BackchannelAuthenticationRequest');
assert(backchannelAuthenticationRequest.params.client_notification_token);
return request.call(provider, {
method: 'POST',
url: this.backchannelClientNotificationEndpoint,
headers: {
Authorization: `Bearer ${backchannelAuthenticationRequest.params.client_notification_token}`,
},
json: { ...payload, auth_req_id: backchannelAuthenticationRequest.jti },
}).then((response) => {
const { statusCode } = response;
if (statusCode !== 204 && statusCode !== 200) {
const error = new Error(`expected 204 No Content from ${this.backchannelClientNotificationEndpoint}, got: ${statusCode} ${STATUS_CODES[statusCode]}`);
error.response = response;
throw error;
}
});
}
async backchannelPing(backchannelAuthenticationRequest) {
return this[backchannel]('ping', backchannelAuthenticationRequest);
}
async backchannelLogout(sub, sid) {
const logoutToken = new IdToken({ sub }, { client: this, ctx: undefined });
logoutToken.mask = { sub: null };
logoutToken.set('events', {
'http://schemas.openid.net/event/backchannel-logout': {},
});
logoutToken.set('jti', nanoid());
if (this.backchannelLogoutSessionRequired) {
logoutToken.set('sid', sid);
}
return request.call(provider, {
method: 'POST',
url: this.backchannelLogoutUri,
form: { logout_token: await logoutToken.issue({ use: 'logout' }) },
}).then((response) => {
const { statusCode } = response;
if (statusCode !== 200) {
const error = new Error(`expected 200 OK from ${this.backchannelLogoutUri}, got: ${statusCode} ${STATUS_CODES[statusCode]}`);
error.response = response;
throw error;
}
});
}
responseTypeAllowed(type) {
return this.responseTypes.includes(type);
}
grantTypeAllowed(type) {
return this.grantTypes.includes(type);
}
redirectUriAllowed(value) {
let parsed;
try {
parsed = new URL(value);
} catch (err) {
return false;
}
const match = this.redirectUris.includes(value);
if (
match
|| this.applicationType !== 'native'
|| parsed.protocol !== 'http:'
|| !LOOPBACKS.has(parsed.hostname)
) {
return match;
}
parsed.port = '';
return !!this.redirectUris
.find((registeredUri) => {
const registered = new URL(registeredUri);
registered.port = '';
return parsed.href === registered.href;
});
}
webMessageUriAllowed(webMessageUri) {
return this.webMessageUris && this.webMessageUris.includes(webMessageUri);
}
requestUriAllowed(uri) {
const requested = stripFragment(uri);
return !!(this.requestUris || []).find((enabled) => requested === stripFragment(enabled));
}
postLogoutRedirectUriAllowed(uri) {
return this.postLogoutRedirectUris.includes(uri);
}
metadata() {
return mapKeys(this, (value, key) => {
const snaked = snakeCase(key);
if (!instance(provider).RECOGNIZED_METADATA.includes(snaked)) {
return key;
}
return snaked;
});
}
get sectorIdentifier() {
if (this.#sectorIdentifier === null) {
this.#sectorIdentifier = sectorIdentifier(this);
}
return this.#sectorIdentifier;
}
includeSid() {
return this.backchannelLogoutUri && this.backchannelLogoutSessionRequired;
}
compareClientSecret(actual) {
return constantEquals(this.clientSecret, actual, 1000);
}
checkClientSecretExpiration(message, errorOverride) {
if (!this.clientSecretExpiresAt) {
return;
}
const clockTolerance = instance(provider).configuration('clockTolerance');
if (epochTime() - clockTolerance >= this.clientSecretExpiresAt) {
const err = new InvalidClient(message, `client_id ${this.clientId} client_secret expired at ${this.clientSecretExpiresAt}`);
if (errorOverride) {
err.error = errorOverride;
err.message = errorOverride;
}
throw err;
}
}
static async find(id) {
if (typeof id !== 'string') {
return undefined;
}
if (staticCache.has(id)) {
const cached = staticCache.get(id);
if (!(cached instanceof Client)) {
const client = new Client(cached);
if (client.sectorIdentifierUri !== undefined) {
await sectorValidate(client);
}
Object.defineProperty(client, 'noManage', { value: true });
staticCache.set(id, client);
}
return staticCache.get(id);
}
const properties = await getAdapter().find(id);
if (!properties) {
return undefined;
}
const propHash = fingerprint(properties);
let client = dynamicCache.get(propHash);
if (!client) {
client = await add(properties, { store: false });
dynamicCache.set(propHash, client);
}
return client;
}
static needsSecret(metadata) {
if (!nonSecretAuthMethods.has(metadata.token_endpoint_auth_method)) {
return true;
}
if (
!nonSecretAuthMethods.has(metadata.introspection_endpoint_auth_method)
&& metadata.introspection_endpoint_auth_method
) {
return true;
}
if (
!nonSecretAuthMethods.has(metadata.revocation_endpoint_auth_method)
&& metadata.revocation_endpoint_auth_method
) {
return true;
}
if (signAlgAttributes.some(isHmac, metadata)) {
return true;
}
if (clientEncryptions.some(isSymmetricAlg, metadata)) {
return true;
}
return false;
}
}
Object.defineProperty(Client, 'Schema', { value: Schema });
return Client;
};