Skip to content

Commit

Permalink
fix: do not mutate JWTVerifyOptions.requiredClaims
Browse files Browse the repository at this point in the history
fixes #610
  • Loading branch information
panva committed Nov 27, 2023
1 parent b7b1e3a commit 1bf9cec
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
12 changes: 7 additions & 5 deletions src/lib/jwt_claims_set.ts
Expand Up @@ -53,12 +53,14 @@ export default (

const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options

if (maxTokenAge !== undefined) requiredClaims.push('iat')
if (audience !== undefined) requiredClaims.push('aud')
if (subject !== undefined) requiredClaims.push('sub')
if (issuer !== undefined) requiredClaims.push('iss')
const presenceCheck = [...requiredClaims]

for (const claim of new Set(requiredClaims.reverse())) {
if (maxTokenAge !== undefined) presenceCheck.push('iat')
if (audience !== undefined) presenceCheck.push('aud')
if (subject !== undefined) presenceCheck.push('sub')
if (issuer !== undefined) presenceCheck.push('iss')

for (const claim of new Set(presenceCheck.reverse())) {
if (!(claim in payload)) {
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claim, 'missing')
}
Expand Down
17 changes: 9 additions & 8 deletions test/jwt/verify.test.mjs
Expand Up @@ -418,6 +418,8 @@ test('requiredClaims claims check', async (t) => {
.setProtectedHeader({ alg: 'HS256' })
.sign(t.context.secret)

const requiredClaims = ['nbf']

for (const [claim, option] of [
['iss', 'issuer'],
['aud', 'audience'],
Expand All @@ -428,16 +430,15 @@ test('requiredClaims claims check', async (t) => {
code: 'ERR_JWT_CLAIM_VALIDATION_FAILED',
message: `missing required "${claim}" claim`,
})
await t.throwsAsync(
jwtVerify(jwt, t.context.secret, { [option]: 'foo', requiredClaims: ['nbf'] }),
{
code: 'ERR_JWT_CLAIM_VALIDATION_FAILED',
message: `missing required "${claim}" claim`,
},
)
await t.throwsAsync(jwtVerify(jwt, t.context.secret, { [option]: 'foo', requiredClaims }), {
code: 'ERR_JWT_CLAIM_VALIDATION_FAILED',
message: `missing required "${claim}" claim`,
})
}
await t.throwsAsync(jwtVerify(jwt, t.context.secret, { requiredClaims: ['nbf'] }), {
await t.throwsAsync(jwtVerify(jwt, t.context.secret, { requiredClaims }), {
code: 'ERR_JWT_CLAIM_VALIDATION_FAILED',
message: `missing required "nbf" claim`,
})

t.deepEqual(requiredClaims, ['nbf'])
})

0 comments on commit 1bf9cec

Please sign in to comment.