-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAuthenticationResponse.js
More file actions
617 lines (524 loc) · 15.6 KB
/
AuthenticationResponse.js
File metadata and controls
617 lines (524 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
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
/**
* Dependencies
*/
const { URL } = require('whatwg-url')
const assert = require('assert')
const { crypto } = require('@solid/jose')
const base64url = require('base64url')
const fetch = require('node-fetch')
const Headers = fetch.Headers ? fetch.Headers : global.Headers
const FormUrlEncoded = require('./FormUrlEncoded')
const IDToken = require('./IDToken')
const Session = require('./Session')
const onHttpError = require('./onHttpError')
const HttpError = require('standard-http-error')
/**
* AuthenticationResponse
*/
class AuthenticationResponse {
/**
* @param rp {RelyingParty}
* @param [redirect] {string} req.query
* @param [body] {string} req.body.text
* @param session {Session|Storage} req.session or localStorage or similar
* @param params {object} hashmap
* @param mode {string} 'query'/'fragment'/'form_post',
* determined in `parseResponse()`
*/
constructor ({rp, redirect, body, session, mode, params = {}}) {
this.rp = rp
this.redirect = redirect
this.body = body
this.session = session
this.mode = mode
this.params = params
}
/**
* validateResponse
*
* @description
* Authentication response validation.
*
* @param {string|Object} response
*
* @returns {Promise<Session>}
*/
static validateResponse (response) {
return Promise.resolve(response)
.then(this.parseResponse)
.then(this.errorResponse)
.then(this.matchRequest)
.then(this.validateStateParam)
.then(this.validateIssParam)
.then(this.validateResponseMode)
.then(this.validateResponseParams)
.then(this.exchangeAuthorizationCode)
.then(this.validateIDToken)
.then(Session.fromAuthResponse)
}
/**
* parseResponse
*
* @param {object} response
*
* @returns {object}
*/
static parseResponse (response) {
let {redirect, body} = response
// response must be either a redirect uri or request body, but not both
if ((redirect && body) || (!redirect && !body)) {
throw new HttpError(400, 'Invalid response mode')
}
// parse redirect uri
if (redirect) {
let url = new URL(redirect)
let {search, hash} = url
if ((search && hash) || (!search && !hash)) {
throw new HttpError(400, 'Invalid response mode')
}
if (search) {
response.params = FormUrlEncoded.decode(search.substring(1))
response.mode = 'query'
}
if (hash) {
response.params = FormUrlEncoded.decode(hash.substring(1))
response.mode = 'fragment'
}
}
// parse request form body
if (body) {
response.params = FormUrlEncoded.decode(body)
response.mode = 'form_post'
}
return response
}
/**
* errorResponse
*
* @param {AuthenticationResponse} response
*
* @throws {Error} If response params include the OAuth2 'error' param,
* throws an error based on it.
*
* @returns {AuthenticationResponse} Chainable
*
* @todo Figure out HTTP status code (typically 400, 401 or 403)
* based on the OAuth2/OIDC `error` code, probably using an external library
*/
static errorResponse (response) {
const errorCode = response.params.error
if (errorCode) {
const errorParams = {}
errorParams['error'] = errorCode
errorParams['error_description'] = response.params['error_description']
errorParams['error_uri'] = response.params['error_uri']
errorParams['state'] = response.params['state']
const error = new Error(`AuthenticationResponse error: ${errorCode}`)
error.info = errorParams
throw error
}
return response
}
/**
* matchRequest
*
* @param {Object} response
* @returns {Promise}
*/
static matchRequest (response) {
let {rp, params, session} = response
let state = params.state
let issuer = rp.provider.configuration.issuer
if (!state) {
throw new Error(
'Missing state parameter in authentication response')
}
let key = `${issuer}/requestHistory/${state}`
let request = session[key]
if (!request) {
throw new Error(
'Mismatching state parameter in authentication response')
}
response.request = JSON.parse(request)
return response
}
/**
* validateStateParam
*
* @param {Object} response
* @returns {Promise}
*/
static validateStateParam (response) {
let octets = new Uint8Array(response.request.state)
let encoded = response.params.state
return crypto.subtle.digest({ name: 'SHA-256' }, octets).then(digest => {
if (encoded !== base64url(Buffer.from(digest))) {
throw new Error(
'Mismatching state parameter in authentication response')
}
return response
})
}
/**
* validateIssParam
*
* @description
* RFC 9207: OAuth 2.0 Authorization Server Issuer Identification
* Validates the iss parameter in the authorization response, if present.
* The iss parameter helps prevent mix-up attacks by ensuring the response
* came from the expected authorization server.
*
* @param {Object} response
* @returns {Promise}
*/
static validateIssParam (response) {
let {params, rp} = response
// RFC 9207: If iss parameter is present, it MUST match the provider issuer
if (params.iss) {
let expectedIssuer = rp.provider.issuer || rp.provider.url
if (params.iss !== expectedIssuer) {
throw new Error(
`Mismatching issuer in authentication response. Expected: ${expectedIssuer}, Got: ${params.iss}`)
}
}
// Note: RFC 9207 specifies iss SHOULD be present, but we don't enforce it
// for backward compatibility with authorization servers that don't support RFC 9207
return Promise.resolve(response)
}
/**
* validateResponseMode
*
* @param {Object} response
* @returns {Promise}
*/
static validateResponseMode (response) {
if (response.request.response_type !== 'code' && response.mode === 'query') {
throw new Error('Invalid response mode')
}
return response
}
/**
* validateResponseParams
*
* @param {Object} response
* @returns {Promise}
*/
static validateResponseParams (response) {
let {request, params} = response
let expectedParams = request.response_type.split(' ')
if (expectedParams.includes('code')) {
assert(params.code,
'Missing authorization code in authentication response')
// TODO assert novelty of code
}
if (expectedParams.includes('id_token')) {
assert(params.id_token,
'Missing id_token in authentication response')
}
if (expectedParams.includes('token')) {
assert(params.access_token,
'Missing access_token in authentication response')
assert(params.token_type,
'Missing token_type in authentication response')
}
return response
}
/**
* exchangeAuthorizationCode
*
* @param {Object} response
* @returns {Promise} response object
*/
static exchangeAuthorizationCode (response) {
let {rp, params, request} = response
let code = params.code
// only exchange the authorization code when the response type is "code"
if (!code || request['response_type'] !== 'code') {
return Promise.resolve(response)
}
let {provider, registration} = rp
let id = registration['client_id']
let secret = registration['client_secret']
// verify the client is not public
if (!secret) {
return Promise.reject(new Error(
'Client cannot exchange authorization code because ' +
'it is not a confidential client'))
}
// initialize token request arguments
let endpoint = provider.configuration.token_endpoint
let method = 'POST'
// initialize headers
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
// initialize the token request parameters
let bodyContents = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': request['redirect_uri']
}
// determine client authentication method
let authMethod = registration['token_endpoint_auth_method']
|| 'client_secret_basic'
// client secret basic authentication
if (authMethod === 'client_secret_basic') {
let credentials = new Buffer(`${id}:${secret}`).toString('base64')
headers.set('Authorization', `Basic ${credentials}`)
}
// client secret post authentication
if (authMethod === 'client_secret_post') {
bodyContents['client_id'] = id
bodyContents['client_secret'] = secret
}
let body = FormUrlEncoded.encode(bodyContents)
// TODO
// client_secret_jwt authentication
// private_key_jwt
// make the token request
return fetch(endpoint, {method, headers, body})
.then(onHttpError('Error exchanging authorization code'))
.then(tokenResponse => tokenResponse.json())
.then(tokenResponse => {
assert(tokenResponse['access_token'],
'Missing access_token in token response')
assert(tokenResponse['token_type'],
'Missing token_type in token response')
assert(tokenResponse['id_token'],
'Missing id_token in token response')
// anything else?
// IS THIS THE RIGHT THING TO DO HERE?
response.params = Object.assign(response.params, tokenResponse)
return response
})
}
/**
* validateIDToken
*
* @param {Object} response
* @returns {Promise}
*/
static validateIDToken (response) {
// only validate the ID Token if present in the response
if (!response.params.id_token) {
return Promise.resolve(response)
}
return Promise.resolve(response)
.then(AuthenticationResponse.decryptIDToken)
.then(AuthenticationResponse.decodeIDToken)
.then(AuthenticationResponse.validateIssuer)
.then(AuthenticationResponse.validateAudience)
.then(AuthenticationResponse.resolveKeys)
.then(AuthenticationResponse.verifySignature)
.then(AuthenticationResponse.validateExpires)
.then(AuthenticationResponse.verifyNonce)
.then(AuthenticationResponse.validateAcr)
.then(AuthenticationResponse.validateAuthTime)
.then(AuthenticationResponse.validateAccessTokenHash)
.then(AuthenticationResponse.validateAuthorizationCodeHash)
}
/**
* decryptIDToken
*
* @param {Object} response
* @returns {Promise}
*/
static decryptIDToken (response) {
// TODO
return Promise.resolve(response)
}
/**
* decodeIDToken
*
* Note: If the `id_token` is not present in params, this method does not
* get called (short-circuited in `validateIDToken()`).
*
* @param response {AuthenticationResponse}
* @param response.params {object}
* @param [response.params.id_token] {string} IDToken encoded as a JWT
*
* @returns {AuthenticationResponse} Chainable
*/
static decodeIDToken (response) {
let jwt = response.params.id_token
try {
response.decoded = IDToken.decode(jwt)
} catch (decodeError) {
const error = new HttpError(400, 'Error decoding ID Token')
error.cause = decodeError
error.info = { id_token: jwt }
throw error
}
return response
}
/**
* validateIssuer
*
* @param {Object} response
* @returns {Promise}
*/
static validateIssuer (response) {
let configuration = response.rp.provider.configuration
let payload = response.decoded.payload
// validate issuer of token matches this relying party's provider
if (payload.iss !== configuration.issuer) {
throw new Error('Mismatching issuer in ID Token')
}
return response
}
/**
* validateAudience
*
* @param {Object} response
* @returns {Promise}
*/
static validateAudience (response) {
let registration = response.rp.registration
let {aud, azp} = response.decoded.payload
// validate audience includes this relying party
if (typeof aud === 'string' && aud !== registration['client_id']) {
throw new Error('Mismatching audience in id_token')
}
// validate audience includes this relying party
if (Array.isArray(aud) && !aud.includes(registration['client_id'])) {
throw new Error('Mismatching audience in id_token')
}
// validate authorized party is present if required
if (Array.isArray(aud) && !azp) {
throw new Error('Missing azp claim in id_token')
}
// validate authorized party is this relying party
if (azp && azp !== registration['client_id']) {
throw new Error('Mismatching azp claim in id_token')
}
return response
}
/**
* resolveKeys
*
* @param {Object} response
* @returns {Promise}
*/
static resolveKeys (response) {
let rp = response.rp
let provider = rp.provider
let decoded = response.decoded
let isFreshJwks = false
return Promise.resolve(provider.jwks)
.then(jwks => jwks ? jwks : (isFreshJwks = true, rp.jwks()))
.then(jwks => {
if (decoded.resolveKeys(jwks)) {
return Promise.resolve(response)
}
if (!isFreshJwks) {
// The OP JWK Set cached by the RP may be stale due to key rotation by the OP.
return rp.jwks().then(jwks => {
if (decoded.resolveKeys(jwks)) {
return Promise.resolve(response)
}
throw new Error('Cannot resolve signing key for ID Token')
})
}
throw new Error('Cannot resolve signing key for ID Token')
})
}
/**
* verifySignature
*
* @param {Object} response
* @returns {Promise}
*/
static verifySignature (response) {
let alg = response.decoded.header.alg
let registration = response.rp.registration
let expectedAlgorithm = registration['id_token_signed_response_alg'] || 'RS256'
// validate signing algorithm matches expectation
if (alg !== expectedAlgorithm) {
throw new Error(
`Expected ID Token to be signed with ${expectedAlgorithm}`)
}
return response.decoded.verify().then(verified => {
if (!verified) {
throw new Error('Invalid ID Token signature')
}
return response
})
}
/**
* validateExpires
*
* @param {Object} response
* @returns {Promise}
*/
static validateExpires (response) {
let exp = response.decoded.payload.exp
// validate expiration of token
if (exp <= Math.floor(Date.now() / 1000)) {
throw new Error('Expired ID Token')
}
return response
}
/**
* verifyNonce
*
* @param {Object} response
* @returns {Promise}
*/
static verifyNonce (response) {
let octets = new Uint8Array(response.request.nonce)
let nonce = response.decoded.payload.nonce
if (!nonce) {
throw new Error('Missing nonce in ID Token')
}
return crypto.subtle.digest({ name: 'SHA-256' }, octets).then(digest => {
if (nonce !== base64url(Buffer.from(digest))) {
throw new Error('Mismatching nonce in ID Token')
}
return response
})
}
/**
* validateAcr
*
* @param {Object} response
* @returns {Object}
*/
static validateAcr (response) {
// TODO
return response
}
/**
* validateAuthTime
*
* @param {Object} response
* @returns {Promise}
*/
static validateAuthTime (response) {
// TODO
return response
}
/**
* validateAccessTokenHash
*
* @param {Object} response
* @returns {Promise}
*/
static validateAccessTokenHash (response) {
// TODO
return response
}
/**
* validateAuthorizationCodeHash
*
* @param {Object} response
* @returns {Promise}
*/
static validateAuthorizationCodeHash (response) {
// TODO
return response
}
}
/**
* Export
*/
module.exports = AuthenticationResponse