Skip to content

Commit cc0aa7a

Browse files
authored
Merge commit from fork
* feat(utils/jwt): add JwtAlgorithmRequired error type Add a new error type to throw when algorithm is not specified during JWT verification. This is part of the security fix to prevent algorithm confusion attacks. * fix(utils/jwt): require alg parameter in verify function BREAKING CHANGE: The `alg` parameter is now required for JWT verification. This prevents algorithm confusion attacks where an attacker could forge tokens by exploiting the default HS256 fallback with asymmetric keys. - Remove HS256 default fallback in verify() function - Make algOrOptions parameter required - Add early validation for undefined algOrOptions - Add validation for undefined alg in options object * fix(middleware/jwt): require alg option in jwt middleware BREAKING CHANGE: The `alg` option is now required when using the JWT middleware. This prevents algorithm confusion attacks. - Make alg property required in options type - Add runtime validation to throw error if alg is not provided - Update JSDoc to reflect required alg parameter - Update example in documentation to include alg option * test(jwt): update tests to use required alg parameter Update existing tests to explicitly specify the alg parameter as it is now required. This is a necessary change due to the security fix that removes the default HS256 fallback. * test(jwt): add security tests for algorithm confusion prevention Add tests to verify the security fix prevents algorithm confusion attacks: - Test that verify() throws JwtAlgorithmRequired when alg is missing - Test that verify() throws when alg is undefined in options - Test that RS256 tokens cannot be verified with HS256 (attack scenario) - Test that middleware throws when alg option is not provided - Test that tokens with mismatched algorithms are rejected * fix(jwt): add algorithm mismatch check between header.alg and options.alg Add JwtAlgorithmMismatch error type and verify that the algorithm specified in the JWT header matches the algorithm provided in options. This prevents algorithm substitution attacks where an attacker might try to use a different algorithm than expected. - Add JwtAlgorithmMismatch error class in types.ts - Check header.alg === options.alg in verify() function - Update HS512/HS384 tests to use correct algorithm in verify - Add explicit test for algorithm mismatch detection - Update existing attack prevention test to expect JwtAlgorithmMismatch
1 parent ef2a4b8 commit cc0aa7a

5 files changed

Lines changed: 221 additions & 19 deletions

File tree

‎src/middleware/jwt/index.test.ts‎

Lines changed: 62 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ describe('JWT', () => {
1313

1414
const app = new Hono()
1515

16-
app.use('/auth/*', jwt({ secret: 'a-secret' }))
17-
app.use('/auth-unicode/*', jwt({ secret: 'a-secret' }))
16+
app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256' }))
17+
app.use('/auth-unicode/*', jwt({ secret: 'a-secret', alg: 'HS256' }))
1818
app.use('/nested/*', async (c, next) => {
19-
const auth = jwt({ secret: 'a-secret' })
19+
const auth = jwt({ secret: 'a-secret', alg: 'HS256' })
2020
return auth(c, next)
2121
})
2222

@@ -131,10 +131,16 @@ describe('JWT', () => {
131131

132132
const app = new Hono()
133133

134-
app.use('/auth/*', jwt({ secret: 'a-secret', headerName: 'x-custom-auth-header' }))
135-
app.use('/auth-unicode/*', jwt({ secret: 'a-secret', headerName: 'x-custom-auth-header' }))
134+
app.use(
135+
'/auth/*',
136+
jwt({ secret: 'a-secret', alg: 'HS256', headerName: 'x-custom-auth-header' })
137+
)
138+
app.use(
139+
'/auth-unicode/*',
140+
jwt({ secret: 'a-secret', alg: 'HS256', headerName: 'x-custom-auth-header' })
141+
)
136142
app.use('/nested/*', async (c, next) => {
137-
const auth = jwt({ secret: 'a-secret', headerName: 'x-custom-auth-header' })
143+
const auth = jwt({ secret: 'a-secret', alg: 'HS256', headerName: 'x-custom-auth-header' })
138144
return auth(c, next)
139145
})
140146

@@ -289,8 +295,8 @@ describe('JWT', () => {
289295

290296
const app = new Hono()
291297

292-
app.use('/auth/*', jwt({ secret: 'a-secret', cookie: 'access_token' }))
293-
app.use('/auth-unicode/*', jwt({ secret: 'a-secret', cookie: 'access_token' }))
298+
app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', cookie: 'access_token' }))
299+
app.use('/auth-unicode/*', jwt({ secret: 'a-secret', alg: 'HS256', cookie: 'access_token' }))
294300

295301
app.get('/auth/*', (c) => {
296302
handlerExecuted = true
@@ -378,7 +384,7 @@ describe('JWT', () => {
378384
describe('Error handling with `cause`', () => {
379385
const app = new Hono()
380386

381-
app.use('/auth/*', jwt({ secret: 'a-secret' }))
387+
app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256' }))
382388
app.get('/auth/*', (c) => c.text('Authorized'))
383389

384390
app.onError((e, c) => {
@@ -414,6 +420,7 @@ describe('JWT', () => {
414420
'/auth/*',
415421
jwt({
416422
secret: 'a-secret',
423+
alg: 'HS256',
417424
cookie: {
418425
key: 'cookie_name',
419426
secret: 'cookie_secret',
@@ -466,6 +473,7 @@ describe('JWT', () => {
466473
'/auth/*',
467474
jwt({
468475
secret: 'a-secret',
476+
alg: 'HS256',
469477
cookie: {
470478
key: 'cookie_name',
471479
secret: 'cookie_secret',
@@ -517,6 +525,7 @@ describe('JWT', () => {
517525
'/auth/*',
518526
jwt({
519527
secret: 'a-secret',
528+
alg: 'HS256',
520529
cookie: {
521530
key: 'cookie_name',
522531
prefixOptions: 'host',
@@ -568,6 +577,7 @@ describe('JWT', () => {
568577
'/auth/*',
569578
jwt({
570579
secret: 'a-secret',
580+
alg: 'HS256',
571581
cookie: {
572582
key: 'cookie_name',
573583
},
@@ -604,4 +614,47 @@ describe('JWT', () => {
604614
expect(handlerExecuted).toBeTruthy()
605615
})
606616
})
617+
618+
describe('Security: Algorithm Confusion Attack Prevention', () => {
619+
it('Should throw error when alg option is not provided', () => {
620+
expect(() => {
621+
// @ts-expect-error - intentionally testing without alg option
622+
jwt({ secret: 'a-secret' })
623+
}).toThrow('JWT auth middleware requires options for "alg"')
624+
})
625+
626+
it('Should reject tokens with mismatched algorithm', async () => {
627+
const app = new Hono()
628+
629+
// Configure middleware to expect RS256
630+
app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'RS256' }))
631+
app.get('/auth/*', (c) => {
632+
return c.json(c.get('jwtPayload'))
633+
})
634+
635+
// Try to use a HS256 token (algorithm confusion attempt)
636+
const hs256Token =
637+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'
638+
639+
const req = new Request('http://localhost/auth/a')
640+
req.headers.set('Authorization', `Bearer ${hs256Token}`)
641+
const res = await app.request(req)
642+
643+
// Should fail because the token algorithm doesn't match expected algorithm
644+
expect(res.status).toBe(401)
645+
})
646+
647+
it('Should require explicit alg specification in middleware options', () => {
648+
// This should work - explicit alg specified
649+
expect(() => {
650+
jwt({ secret: 'a-secret', alg: 'HS256' })
651+
}).not.toThrow()
652+
653+
// This should throw - alg not specified
654+
expect(() => {
655+
// @ts-expect-error - intentionally testing without alg option
656+
jwt({ secret: 'a-secret' })
657+
}).toThrow('JWT auth middleware requires options for "alg"')
658+
})
659+
})
607660
})

‎src/middleware/jwt/jwt.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export type JwtVariables<T = any> = {
2727
* @param {object} options - The options for the JWT middleware.
2828
* @param {SignatureKey} [options.secret] - A value of your secret key.
2929
* @param {string} [options.cookie] - If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.
30-
* @param {SignatureAlgorithm} [options.alg=HS256] - An algorithm type that is used for verifying. Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.
30+
* @param {SignatureAlgorithm} options.alg - An algorithm type that is used for verifying (required). Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.
3131
* @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.
3232
* @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification.
3333
* @returns {MiddlewareHandler} The middleware handler function.
@@ -40,6 +40,7 @@ export type JwtVariables<T = any> = {
4040
* '/auth/*',
4141
* jwt({
4242
* secret: 'it-is-very-secret',
43+
* alg: 'HS256',
4344
* headerName: 'x-custom-auth-header', // Optional, default is 'Authorization'
4445
* })
4546
* )
@@ -54,7 +55,7 @@ export const jwt = (options: {
5455
cookie?:
5556
| string
5657
| { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }
57-
alg?: SignatureAlgorithm
58+
alg: SignatureAlgorithm
5859
headerName?: string
5960
verification?: VerifyOptions
6061
}): MiddlewareHandler => {
@@ -64,6 +65,10 @@ export const jwt = (options: {
6465
throw new Error('JWT auth middleware requires options for "secret"')
6566
}
6667

68+
if (!options.alg) {
69+
throw new Error('JWT auth middleware requires options for "alg"')
70+
}
71+
6772
if (!crypto.subtle || !crypto.subtle.importKey) {
6873
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')
6974
}

‎src/utils/jwt/jwt.test.ts‎

Lines changed: 121 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ import { signing } from './jws'
66
import * as JWT from './jwt'
77
import { verifyWithJwks } from './jwt'
88
import {
9+
JwtAlgorithmMismatch,
910
JwtAlgorithmNotImplemented,
11+
JwtAlgorithmRequired,
1012
JwtPayloadRequiresAud,
1113
JwtTokenAudience,
1214
JwtTokenExpired,
@@ -563,7 +565,7 @@ describe('JWT', () => {
563565
let err = null
564566
let authorized
565567
try {
566-
authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)
568+
authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS512)
567569
} catch (e) {
568570
err = e
569571
}
@@ -582,7 +584,7 @@ describe('JWT', () => {
582584
let err = null
583585
let authorized
584586
try {
585-
authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)
587+
authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS384)
586588
} catch (e) {
587589
err = e
588590
}
@@ -610,7 +612,7 @@ describe('JWT', () => {
610612
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.qunGhchNXH_unqWXN6hB0Elhzr5SykSXVhklLti1aFI'
611613
expect(tok).toEqual(expected)
612614

613-
const verifiedPayload = await JWT.verify(tok, secret)
615+
const verifiedPayload = await JWT.verify(tok, secret, AlgorithmTypes.HS256)
614616
expect(verifiedPayload).not.toBeUndefined()
615617
expect(verifiedPayload).toEqual(payload)
616618

@@ -624,7 +626,7 @@ describe('JWT', () => {
624626
let err = null
625627
let authorized
626628
try {
627-
authorized = await JWT.verify(tok, invalidSecret)
629+
authorized = await JWT.verify(tok, invalidSecret, AlgorithmTypes.HS256)
628630
} catch (e) {
629631
err = e
630632
}
@@ -931,3 +933,118 @@ async function generateEd25519Key(): Promise<CryptoKeyPair> {
931933
['sign', 'verify']
932934
)
933935
}
936+
937+
describe('Security: Algorithm Confusion Attack Prevention', () => {
938+
it('Should throw JwtAlgorithmRequired error when alg is not specified in verify()', async () => {
939+
const payload = { message: 'hello world' }
940+
const secret = 'a-secret'
941+
const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)
942+
943+
let err: JwtAlgorithmRequired | undefined
944+
let authorized
945+
try {
946+
// @ts-expect-error - intentionally testing without alg parameter
947+
authorized = await JWT.verify(tok, secret)
948+
} catch (e) {
949+
err = e as JwtAlgorithmRequired
950+
}
951+
expect(err).toBeInstanceOf(JwtAlgorithmRequired)
952+
expect(err?.message).toBe('JWT verification requires "alg" option to be specified')
953+
expect(authorized).toBeUndefined()
954+
})
955+
956+
it('Should throw JwtAlgorithmRequired error when alg is undefined in options object', async () => {
957+
const payload = { message: 'hello world' }
958+
const secret = 'a-secret'
959+
const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)
960+
961+
let err: JwtAlgorithmRequired | undefined
962+
let authorized
963+
try {
964+
// @ts-expect-error - intentionally testing with undefined alg
965+
authorized = await JWT.verify(tok, secret, { alg: undefined })
966+
} catch (e) {
967+
err = e as JwtAlgorithmRequired
968+
}
969+
expect(err).toBeInstanceOf(JwtAlgorithmRequired)
970+
expect(authorized).toBeUndefined()
971+
})
972+
973+
it('Should prevent algorithm confusion attack (RS256 token verified with HS256 using public key)', async () => {
974+
// Generate RSA key pair
975+
const keyPair = await crypto.subtle.generateKey(
976+
{
977+
name: 'RSASSA-PKCS1-v1_5',
978+
modulusLength: 2048,
979+
publicExponent: new Uint8Array([1, 0, 1]),
980+
hash: 'SHA-256',
981+
},
982+
true,
983+
['sign', 'verify']
984+
)
985+
986+
const payload = { message: 'hello world' }
987+
988+
// Sign token with RS256 using private key
989+
const tok = await JWT.sign(payload, keyPair.privateKey, AlgorithmTypes.RS256)
990+
991+
// Verify should succeed with RS256 and public key
992+
const verified = await JWT.verify(tok, keyPair.publicKey, AlgorithmTypes.RS256)
993+
expect(verified).toEqual(payload)
994+
995+
// Attempting to verify with HS256 using the public key should fail with algorithm mismatch
996+
// This simulates the algorithm confusion attack scenario
997+
let err: Error | undefined
998+
let maliciousResult
999+
try {
1000+
maliciousResult = await JWT.verify(tok, keyPair.publicKey, AlgorithmTypes.HS256)
1001+
} catch (e) {
1002+
err = e as Error
1003+
}
1004+
// The verification should fail because the header.alg (RS256) doesn't match options.alg (HS256)
1005+
expect(maliciousResult).toBeUndefined()
1006+
expect(err).toBeInstanceOf(JwtAlgorithmMismatch)
1007+
})
1008+
1009+
it('Should throw JwtAlgorithmMismatch when header.alg does not match options.alg', async () => {
1010+
const payload = { message: 'hello world' }
1011+
const secret = 'a-secret'
1012+
1013+
// Sign with HS512
1014+
const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)
1015+
1016+
// Try to verify with HS256 (wrong algorithm)
1017+
let err: Error | undefined
1018+
let result
1019+
try {
1020+
result = await JWT.verify(tok, secret, AlgorithmTypes.HS256)
1021+
} catch (e) {
1022+
err = e as Error
1023+
}
1024+
1025+
expect(result).toBeUndefined()
1026+
expect(err).toBeInstanceOf(JwtAlgorithmMismatch)
1027+
})
1028+
1029+
it('Should require explicit alg specification to prevent default fallback attack', async () => {
1030+
const payload = { message: 'hello world' }
1031+
const secret = 'a-secret'
1032+
1033+
// Create a token with HS256
1034+
const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)
1035+
1036+
// Verify with explicit HS256 should work
1037+
const verified = await JWT.verify(tok, secret, AlgorithmTypes.HS256)
1038+
expect(verified).toEqual(payload)
1039+
1040+
// Verify without alg should throw error (no default fallback)
1041+
let err: Error | undefined
1042+
try {
1043+
// @ts-expect-error - intentionally testing without alg parameter
1044+
await JWT.verify(tok, secret)
1045+
} catch (e) {
1046+
err = e as Error
1047+
}
1048+
expect(err).toBeInstanceOf(JwtAlgorithmRequired)
1049+
})
1050+
})

‎src/utils/jwt/jwt.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import type { SignatureAlgorithm } from './jwa'
1010
import { signing, verifying } from './jws'
1111
import type { HonoJsonWebKey, SignatureKey } from './jws'
1212
import {
13+
JwtAlgorithmMismatch,
14+
JwtAlgorithmRequired,
1315
JwtHeaderInvalid,
1416
JwtHeaderRequiresKid,
1517
JwtPayloadRequiresAud,
@@ -86,22 +88,30 @@ export type VerifyOptions = {
8688

8789
export type VerifyOptionsWithAlg = {
8890
/** The algorithm used for decoding the token */
89-
alg?: SignatureAlgorithm
91+
alg: SignatureAlgorithm
9092
} & VerifyOptions
9193

9294
export const verify = async (
9395
token: string,
9496
publicKey: SignatureKey,
95-
algOrOptions?: SignatureAlgorithm | VerifyOptionsWithAlg
97+
algOrOptions: SignatureAlgorithm | VerifyOptionsWithAlg
9698
): Promise<JWTPayload> => {
99+
if (!algOrOptions) {
100+
throw new JwtAlgorithmRequired()
101+
}
102+
97103
const {
98-
alg = 'HS256',
104+
alg,
99105
iss,
100106
nbf = true,
101107
exp = true,
102108
iat = true,
103109
aud,
104-
} = typeof algOrOptions === 'string' ? { alg: algOrOptions } : algOrOptions || {}
110+
} = typeof algOrOptions === 'string' ? { alg: algOrOptions } : algOrOptions
111+
112+
if (!alg) {
113+
throw new JwtAlgorithmRequired()
114+
}
105115

106116
const tokenParts = token.split('.')
107117
if (tokenParts.length !== 3) {
@@ -112,6 +122,9 @@ export const verify = async (
112122
if (!isTokenHeader(header)) {
113123
throw new JwtHeaderInvalid(header)
114124
}
125+
if (header.alg !== alg) {
126+
throw new JwtAlgorithmMismatch(alg, header.alg)
127+
}
115128
const now = (Date.now() / 1000) | 0
116129
if (nbf && payload.nbf && payload.nbf > now) {
117130
throw new JwtTokenNotBefore(token)

0 commit comments

Comments
 (0)