deno.land / x / oauth4webapi@v1.2.2 / conformance / runner.ts

runner.ts
View Documentation
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
import anyTest, { type TestFn } from 'ava'
export const test = anyTest as TestFn<{ instance: Test }>
import { getScope } from './ava.config.js'import * as oauth from '../src/index.js'import { createTestFromPlan, waitForState, getTestExposed, type ModulePrescription, type Plan, type Test,} from './api.js'
import { JWS_ALGORITHM } from './env.js'const conformance = JSON.parse(process.env.CONFORMANCE!)
const configuration: { alias: string client: { client_id: string client_secret?: string redirect_uri: string jwks: { keys: Array<JsonWebKey & { kid: string }> } }} = conformance.configuration
export const plan: Plan = conformance.planexport const variant: Record<string, string> = conformance.variant
let prefix = ''
switch (plan.name) { case 'fapi2-baseline-id2-client-test-plan': prefix = 'fapi2-baseline-id2-client-test-' break case 'fapi2-advanced-id1-client-test-plan': // TODO: https://gitlab.com/openid/conformance-suite/-/merge_requests/1173#note_1014001397 prefix = 'fapi2-baseline-id2-client-test-' break case 'oidcc-client-test-plan': case 'oidcc-client-basic-certification-test-plan': prefix = 'oidcc-client-test-' break default: throw new Error()}
const algorithms: Map<string, RsaHashedImportParams | EcKeyImportParams | Algorithm> = new Map([ [ 'PS256', { name: 'RSA-PSS', hash: { name: 'SHA-256' }, }, ], [ 'ES256', { name: 'ECDSA', namedCurve: 'P-256', }, ], [ 'RS256', { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }, }, ], ['EdDSA', { name: 'Ed25519' }],])
function importPrivateKey(alg: string, jwk: JsonWebKey) { return crypto.subtle.importKey('jwk', jwk, algorithms.get(alg)!, false, ['sign'])}
export function modules(name: string): ModulePrescription[] { if (name === prefix.slice(0, -1)) { return conformance.plan.modules.filter((x: ModulePrescription) => x.testModule === name) }
return conformance.plan.modules.filter( (x: ModulePrescription) => x.testModule === `${prefix}${name}`, )}
function usesJarm(plan: Plan) { return plan.name.startsWith('fapi2-advanced')}
function usesDpop(variant: Record<string, string>) { return variant.sender_constrain === 'dpop'}
function usesPar(plan: Plan) { return plan.name.startsWith('fapi2')}
function usesRequestObject(planName: string, variant: Record<string, string>) { if (planName.startsWith('fapi2-advanced')) { return true }
if (variant.request_type === 'request_object') { return true }
return false}
export const green = test.macro({ async exec(t, module: ModulePrescription) { t.timeout(15000)
const instance = await createTestFromPlan(plan, module) t.context.instance = instance
t.log('Test ID', instance.id) t.log('Test Name', instance.name)
const variant = { ...conformance.variant, ...module.variant, } t.log('variant', variant)
const { issuer: issuerIdentifier, accounts_endpoint } = await getTestExposed(instance)
if (!issuerIdentifier) { throw new Error() }
const issuer = new URL(issuerIdentifier)
const as = await oauth .discoveryRequest(issuer) .then((response) => oauth.processDiscoveryResponse(issuer, response))
t.log('AS Metadata', as)
const client: oauth.Client = { client_id: configuration.client.client_id, client_secret: configuration.client.client_secret, }
client.token_endpoint_auth_method = variant.client_auth_type || 'client_secret_basic' if (instance.name.includes('client-secret-basic')) { client.token_endpoint_auth_method = 'client_secret_basic' }
let clientPrivateKey!: oauth.PrivateKey
switch (client.token_endpoint_auth_method) { case 'none': delete client.client_secret break case 'private_key_jwt': delete client.client_secret const jwk = configuration.client.jwks.keys.find((key) => key.alg === JWS_ALGORITHM)! clientPrivateKey = { kid: jwk.kid, key: await importPrivateKey(JWS_ALGORITHM, jwk), } }
const scope = getScope(variant) const code_verifier = oauth.generateRandomCodeVerifier() const code_challenge = await oauth.calculatePKCECodeChallenge(code_verifier) const code_challenge_method = 'S256'
let authorizationUrl = new URL(as.authorization_endpoint!) if (usesRequestObject(plan.name, variant) === false) { authorizationUrl.searchParams.set('client_id', client.client_id) authorizationUrl.searchParams.set('code_challenge', code_challenge) authorizationUrl.searchParams.set('code_challenge_method', code_challenge_method) authorizationUrl.searchParams.set('redirect_uri', configuration.client.redirect_uri) authorizationUrl.searchParams.set('response_type', 'code') authorizationUrl.searchParams.set('scope', scope) } else { authorizationUrl.searchParams.set('client_id', client.client_id) const params = new URLSearchParams() params.set('code_challenge', code_challenge) params.set('code_challenge_method', code_challenge_method) params.set('redirect_uri', configuration.client.redirect_uri) params.set('response_type', 'code') params.set('scope', scope)
const jwk = configuration.client.jwks.keys.find((key) => key.alg === JWS_ALGORITHM)! const privateKey = await importPrivateKey(JWS_ALGORITHM, jwk)
authorizationUrl.searchParams.set( 'request', await oauth.issueRequestObject(as, client, params, { kid: jwk.kid, key: privateKey }), ) authorizationUrl.searchParams.set('scope', scope) authorizationUrl.searchParams.set('response_type', 'code') }
let DPoP!: CryptoKeyPair if (usesDpop(variant)) { DPoP = await oauth.generateKeyPair(<oauth.JWSAlgorithm>JWS_ALGORITHM) authorizationUrl.searchParams.set( 'dpop_jkt', await oauth.calculateJwkThumbprint(DPoP.publicKey), ) }
if (usesPar(plan)) { t.log('PAR request with', Object.fromEntries(authorizationUrl.searchParams.entries())) const request = () => oauth.pushedAuthorizationRequest(as, client, authorizationUrl.searchParams, { DPoP, clientPrivateKey, }) let par = await request()
let challenges: oauth.WWWAuthenticateChallenge[] | undefined if ((challenges = oauth.parseWwwAuthenticateChallenges(par))) { for (const challenge of challenges) { t.log('challenge', challenge) } throw new Error() }
let result = await oauth.processPushedAuthorizationResponse(as, client, par) if (oauth.isOAuth2Error(result)) { t.log('error', result) if (result.error === 'use_dpop_nonce') { t.log('retrying with a newly obtained dpop nonce') par = await request() result = await oauth.processPushedAuthorizationResponse(as, client, par) } throw new Error() // Handle OAuth 2.0 response body error } t.log('PAR response', await par.clone().json()) authorizationUrl = new URL(as.authorization_endpoint!) authorizationUrl.searchParams.set('client_id', client.client_id) authorizationUrl.searchParams.set('request_uri', result.request_uri) }
await Promise.allSettled([fetch(authorizationUrl.href, { redirect: 'manual' })])
t.log('redirect with', Object.fromEntries(authorizationUrl.searchParams.entries()))
const { authorization_endpoint_response_redirect } = await getTestExposed(instance) if (!authorization_endpoint_response_redirect) { throw new Error() }
const currentUrl = new URL(authorization_endpoint_response_redirect)
let sub: string let access_token: string { let params: ReturnType<typeof oauth.validateAuthResponse>
if (usesJarm(plan)) { params = await oauth.validateJwtAuthResponse(as, client, currentUrl) } else { params = oauth.validateAuthResponse(as, client, currentUrl) }
if (oauth.isOAuth2Error(params)) { t.log('error', params) throw new Error() // Handle OAuth 2.0 redirect error }
t.log('parsed callback parameters', Object.fromEntries(params.entries()))
const request = () => oauth.authorizationCodeGrantRequest( as, client, <Exclude<typeof params, oauth.OAuth2Error>>params, configuration.client.redirect_uri, code_verifier, { clientPrivateKey, DPoP }, ) let response = await request()
let challenges: oauth.WWWAuthenticateChallenge[] | undefined if ((challenges = oauth.parseWwwAuthenticateChallenges(response))) { for (const challenge of challenges) { t.log('challenge', challenge) } throw new Error() }
let result: | oauth.OAuth2TokenEndpointResponse | oauth.OpenIDTokenEndpointResponse | oauth.OAuth2Error if (scope.includes('openid')) { result = await oauth.processAuthorizationCodeOpenIDResponse(as, client, response) } else { result = await oauth.processAuthorizationCodeOAuth2Response(as, client, response) }
if (oauth.isOAuth2Error(result)) { t.log('error', result) if (result.error === 'use_dpop_nonce') { t.log('retrying with a newly obtained dpop nonce') response = await request() if (scope.includes('openid')) { result = await oauth.processAuthorizationCodeOpenIDResponse(as, client, response) } else { result = await oauth.processAuthorizationCodeOAuth2Response(as, client, response) } } throw new Error() // Handle OAuth 2.0 response body error }
t.log('token endpoint response body', await response.clone().json()) ;({ access_token } = result) if (result.id_token) { const claims = oauth.getValidatedIdTokenClaims(result) t.log('ID Token Claims', claims) ;({ sub } = claims) } }
if (scope.includes('openid') && as.userinfo_endpoint) { // fetch userinfo response const request = () => { t.log('fetching', as.userinfo_endpoint) return oauth.userInfoRequest(as, client, access_token, { DPoP }) } let response = await request()
let challenges: oauth.WWWAuthenticateChallenge[] | undefined if ((challenges = oauth.parseWwwAuthenticateChallenges(response))) { let retried = false for (const challenge of challenges) { t.log('challenge', challenge) if (challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce') { t.log('retrying with a newly obtained dpop nonce') response = await request() retried = true } } if (!retried) { throw new Error() } }
try { t.log('userinfo endpoint response body', await response.clone().json()) } catch { t.log('userinfo endpoint response body', await response.clone().text()) }
await oauth.processUserInfoResponse(as, client, sub!, response) t.log('userinfo response passed validation') }
if (accounts_endpoint) { const request = () => { t.log('fetching', accounts_endpoint) return oauth.protectedResourceRequest( access_token, 'GET', new URL(accounts_endpoint), new Headers(), null, { DPoP }, ) } let accounts = await request()
let challenges: oauth.WWWAuthenticateChallenge[] | undefined if ((challenges = oauth.parseWwwAuthenticateChallenges(accounts))) { let retried = false for (const challenge of challenges) { t.log('challenge', challenge) if (challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce') { t.log('retrying with a newly obtained dpop nonce') accounts = await request() retried = true } } if (!retried) { throw new Error() } }
try { t.log('accounts endpoint response body', await accounts.clone().json()) } catch { t.log('accounts endpoint response body', await accounts.clone().text()) } }
await waitForState(instance)
t.log('Test Finished') t.pass() }, title(providedTitle = '', module: ModulePrescription) { if (module.variant) { return `${providedTitle}${plan.name} (${plan.id}) - ${module.testModule} - ${JSON.stringify( module.variant, )}` } return `${providedTitle}${plan.name} (${plan.id}) - ${module.testModule}` },})
export const red = test.macro({ async exec( t, module: ModulePrescription, expectedMessage?: string | RegExp, expectedErrorName: string = 'OperationProcessingError', ) { await t .throwsAsync(() => <any>green.exec(t, module), { message: expectedMessage, name: expectedErrorName, }) .then((err) => { if (err) { t.log('rejected with', { message: err.message, name: err.name, }) } })
await waitForState(t.context.instance) t.log('Test Finished') t.pass() }, title: <any>green.title,})
export const skipped = test.macro({ async exec(t, module: ModulePrescription) { await Promise.allSettled([green.exec(t, module)])
await waitForState(t.context.instance, { results: new Set(['SKIPPED']) }) t.log('Test result is SKIPPED') t.pass() }, title: <any>green.title,})
oauth4webapi

Version Info

Tagged at
2 years ago