Skip to content

Commit f297ee6

Browse files
authored
Merge pull request #56 from byu-oit/throw-better-x5t-error
Throw better error if x5t in JWT doesn't match any known keys
2 parents 479e0fb + 2f536e6 commit f297ee6

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

lib/index.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -382,8 +382,12 @@ async function verifyJWT (options, cache, jwt) {
382382
const openIdConfig = await initOpenId(cache)
383383
const algorithms = openIdConfig.id_token_signing_alg_values_supported
384384

385-
const key = (await initPem(cache)).filter(key => key.x5t === jwtHeaders.x5t)
386-
const pem = key[0].x5c
385+
const matchingKey = (await initPem(cache)).find(key => key.x5t === jwtHeaders.x5t)
386+
if (!matchingKey) {
387+
debug('Failed verifying JWT: x5t in JWT did not correspond to any known key')
388+
throw new Error('x5t in JWT did not correspond to any known key')
389+
}
390+
const pem = matchingKey.x5c
387391

388392
debug('verifying JWT')
389393
try {

test/index.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,18 @@ describe('byu-jwt', function () {
8282
expect(value).to.equal(false)
8383
})
8484
})
85+
86+
it('invalid x5t in JWT', () => {
87+
const [encodedJwtHeaders, ...restOfJwt] = jwt.split('.')
88+
const decodedJwtHeaders = JSON.parse(Buffer.from(encodedJwtHeaders.replace(/=/g, ''), 'base64').toString())
89+
const jwtHeadersWithInvalidX5t = { ...decodedJwtHeaders, x5t: 'invalid x5t' }
90+
const encodedJwtHeadersWithInvalidX5t = Buffer.from(JSON.stringify(jwtHeadersWithInvalidX5t)).toString('base64').replace(/=/g, '')
91+
const jwtWithInvalidX5t = [encodedJwtHeadersWithInvalidX5t, ...restOfJwt].join('.')
92+
return byuJWT.verifyJWT(jwtWithInvalidX5t)
93+
.then(value => {
94+
expect(value).to.equal(false)
95+
})
96+
})
8597
})
8698

8799
describe('decodeJWT', () => {
@@ -120,6 +132,15 @@ describe('byu-jwt', function () {
120132
expect(err.message).to.equal('Invalid JWT')
121133
})
122134
})
135+
136+
it('missing JWT', () => {
137+
const headers = {}
138+
return byuJWT.authenticate(headers)
139+
.then(() => { throw Error('not this error') })
140+
.catch(err => {
141+
expect(err.message).to.equal('Missing expected JWT')
142+
})
143+
})
123144
})
124145

125146
describe('authenticateUAPIMiddleware', () => {

0 commit comments

Comments
 (0)