Skip to content
Myr

Merge commit from fork

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* 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

authored by calloc134 · committed by GitHub · parent ef2a4b8 · Browse files · 5 files+221 added−19 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+221 added−19 removed

  • tests:+183 added−13 removed
  • other:+38 added−6 removed

5 files+221 added−19 removed

modified:src/middleware/jwt/index.test.ts+62 added-9 removed
11 unmodified lines
12 })1314 const app = new Hono()1516 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' }))18 app.use('/nested/*', async (c, next) => {19 const auth = jwt({ secret: 'a-secret' })19 const auth = jwt({ secret: 'a-secret', alg: 'HS256' })20 return auth(c, next)21 })2223 app.get('/auth/*', (c) => {
106 unmodified lines
130 })131132 const app = new Hono()133134 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 )142 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' })144 return auth(c, next)145 })146147 app.get('/auth/*', (c) => {
146 unmodified lines
294 })295296 const app = new Hono()297292 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' }))300301 app.get('/auth/*', (c) => {302 handlerExecuted = true303 const payload = c.get('jwtPayload')
79 unmodified lines
383384 describe('Error handling with `cause`', () => {385 const app = new Hono()386381 app.use('/auth/*', jwt({ secret: 'a-secret' }))387 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256' }))388 app.get('/auth/*', (c) => c.text('Authorized'))389390 app.onError((e, c) => {391 if (e instanceof HTTPException && e.cause instanceof Error) {
27 unmodified lines
419 app.use(420 '/auth/*',421 jwt({422 secret: 'a-secret',423 alg: 'HS256',424 cookie: {425 key: 'cookie_name',426 secret: 'cookie_secret',427 prefixOptions: 'host',
44 unmodified lines
472 app.use(473 '/auth/*',474 jwt({475 secret: 'a-secret',476 alg: 'HS256',477 cookie: {478 key: 'cookie_name',479 secret: 'cookie_secret',480 },
43 unmodified lines
524 app.use(525 '/auth/*',526 jwt({527 secret: 'a-secret',528 alg: 'HS256',529 cookie: {530 key: 'cookie_name',531 prefixOptions: 'host',532 },
43 unmodified lines
576 app.use(577 '/auth/*',578 jwt({579 secret: 'a-secret',580 alg: 'HS256',581 cookie: {582 key: 'cookie_name',583 },584 })
28 unmodified lines
613 expect(await res.json()).toEqual({ message: 'hello world' })614 expect(handlerExecuted).toBeTruthy()615 })616 })617618 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 option622 jwt({ secret: 'a-secret' })623 }).toThrow('JWT auth middleware requires options for "alg"')624 })625626 it('Should reject tokens with mismatched algorithm', async () => {627 const app = new Hono()628629 // Configure middleware to expect RS256630 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'RS256' }))631 app.get('/auth/*', (c) => {632 return c.json(c.get('jwtPayload'))633 })634635 // Try to use a HS256 token (algorithm confusion attempt)636 const hs256Token =637 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'638639 const req = new Request('http://localhost/auth/a')640 req.headers.set('Authorization', `Bearer ${hs256Token}`)641 const res = await app.request(req)642643 // Should fail because the token algorithm doesn't match expected algorithm644 expect(res.status).toBe(401)645 })646647 it('Should require explicit alg specification in middleware options', () => {648 // This should work - explicit alg specified649 expect(() => {650 jwt({ secret: 'a-secret', alg: 'HS256' })651 }).not.toThrow()652653 // This should throw - alg not specified654 expect(() => {655 // @ts-expect-error - intentionally testing without alg option656 jwt({ secret: 'a-secret' })657 }).toThrow('JWT auth middleware requires options for "alg"')658 })659 })660})
modified:src/middleware/jwt/jwt.ts+7 added-2 removed
modified:src/utils/jwt/jwt.test.ts+121 added-4 removed
4 unmodified lines
5import { signing } from './jws'6import * as JWT from './jwt'7import { verifyWithJwks } from './jwt'8import {9 JwtAlgorithmMismatch,10 JwtAlgorithmNotImplemented,11 JwtAlgorithmRequired,12 JwtPayloadRequiresAud,13 JwtTokenAudience,14 JwtTokenExpired,15 JwtTokenInvalid,
548 unmodified lines
564565 let err = null566 let authorized567 try {566 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)568 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS512)569 } catch (e) {570 err = e571 }572 expect(authorized).toBeUndefined()
10 unmodified lines
583584 let err = null585 let authorized586 try {585 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)587 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS384)588 } catch (e) {589 err = e590 }591 expect(authorized).toBeUndefined()
19 unmodified lines
611 const expected =612 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.qunGhchNXH_unqWXN6hB0Elhzr5SykSXVhklLti1aFI'613 expect(tok).toEqual(expected)614613 const verifiedPayload = await JWT.verify(tok, secret)615 const verifiedPayload = await JWT.verify(tok, secret, AlgorithmTypes.HS256)616 expect(verifiedPayload).not.toBeUndefined()617 expect(verifiedPayload).toEqual(payload)618619 const invalidSecret = await crypto.subtle.importKey(
5 unmodified lines
625 )626 let err = null627 let authorized628 try {627 authorized = await JWT.verify(tok, invalidSecret)629 authorized = await JWT.verify(tok, invalidSecret, AlgorithmTypes.HS256)630 } catch (e) {631 err = e632 }633 expect(authorized).toBeUndefined()
298 unmodified lines
932 true,933 ['sign', 'verify']934 )935}936937describe('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)942943 let err: JwtAlgorithmRequired | undefined944 let authorized945 try {946 // @ts-expect-error - intentionally testing without alg parameter947 authorized = await JWT.verify(tok, secret)948 } catch (e) {949 err = e as JwtAlgorithmRequired950 }951 expect(err).toBeInstanceOf(JwtAlgorithmRequired)952 expect(err?.message).toBe('JWT verification requires "alg" option to be specified')953 expect(authorized).toBeUndefined()954 })955956 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)960961 let err: JwtAlgorithmRequired | undefined962 let authorized963 try {964 // @ts-expect-error - intentionally testing with undefined alg965 authorized = await JWT.verify(tok, secret, { alg: undefined })966 } catch (e) {967 err = e as JwtAlgorithmRequired968 }969 expect(err).toBeInstanceOf(JwtAlgorithmRequired)970 expect(authorized).toBeUndefined()971 })972973 it('Should prevent algorithm confusion attack (RS256 token verified with HS256 using public key)', async () => {974 // Generate RSA key pair975 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 )985986 const payload = { message: 'hello world' }987988 // Sign token with RS256 using private key989 const tok = await JWT.sign(payload, keyPair.privateKey, AlgorithmTypes.RS256)990991 // Verify should succeed with RS256 and public key992 const verified = await JWT.verify(tok, keyPair.publicKey, AlgorithmTypes.RS256)993 expect(verified).toEqual(payload)994995 // Attempting to verify with HS256 using the public key should fail with algorithm mismatch996 // This simulates the algorithm confusion attack scenario997 let err: Error | undefined998 let maliciousResult999 try {1000 maliciousResult = await JWT.verify(tok, keyPair.publicKey, AlgorithmTypes.HS256)1001 } catch (e) {1002 err = e as Error1003 }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 })10081009 it('Should throw JwtAlgorithmMismatch when header.alg does not match options.alg', async () => {1010 const payload = { message: 'hello world' }1011 const secret = 'a-secret'10121013 // Sign with HS5121014 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)10151016 // Try to verify with HS256 (wrong algorithm)1017 let err: Error | undefined1018 let result1019 try {1020 result = await JWT.verify(tok, secret, AlgorithmTypes.HS256)1021 } catch (e) {1022 err = e as Error1023 }10241025 expect(result).toBeUndefined()1026 expect(err).toBeInstanceOf(JwtAlgorithmMismatch)1027 })10281029 it('Should require explicit alg specification to prevent default fallback attack', async () => {1030 const payload = { message: 'hello world' }1031 const secret = 'a-secret'10321033 // Create a token with HS2561034 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)10351036 // Verify with explicit HS256 should work1037 const verified = await JWT.verify(tok, secret, AlgorithmTypes.HS256)1038 expect(verified).toEqual(payload)10391040 // Verify without alg should throw error (no default fallback)1041 let err: Error | undefined1042 try {1043 // @ts-expect-error - intentionally testing without alg parameter1044 await JWT.verify(tok, secret)1045 } catch (e) {1046 err = e as Error1047 }1048 expect(err).toBeInstanceOf(JwtAlgorithmRequired)1049 })1050})
modified:src/utils/jwt/jwt.ts+17 added-4 removed
8 unmodified lines
9import type { SignatureAlgorithm } from './jwa'10import { signing, verifying } from './jws'11import type { HonoJsonWebKey, SignatureKey } from './jws'12import {13 JwtAlgorithmMismatch,14 JwtAlgorithmRequired,15 JwtHeaderInvalid,16 JwtHeaderRequiresKid,17 JwtPayloadRequiresAud,18 JwtTokenAudience,
68 unmodified lines
87}8889export type VerifyOptionsWithAlg = {90 /** The algorithm used for decoding the token */89 alg?: SignatureAlgorithm91 alg: SignatureAlgorithm92} & VerifyOptions9394export const verify = async (95 token: string,96 publicKey: SignatureKey,95 algOrOptions?: SignatureAlgorithm | VerifyOptionsWithAlg97 algOrOptions: SignatureAlgorithm | VerifyOptionsWithAlg98): Promise<JWTPayload> => {99 if (!algOrOptions) {100 throw new JwtAlgorithmRequired()101 }102103 const {98 alg = 'HS256',104 alg,105 iss,106 nbf = true,107 exp = true,108 iat = true,109 aud,104 } = typeof algOrOptions === 'string' ? { alg: algOrOptions } : algOrOptions || {}110 } = typeof algOrOptions === 'string' ? { alg: algOrOptions } : algOrOptions111112 if (!alg) {113 throw new JwtAlgorithmRequired()114 }115116 const tokenParts = token.split('.')117 if (tokenParts.length !== 3) {118 throw new JwtTokenInvalid(token)119 }
1 unmodified line
121 const { header, payload } = decode(token)122 if (!isTokenHeader(header)) {123 throw new JwtHeaderInvalid(header)124 }125 if (header.alg !== alg) {126 throw new JwtAlgorithmMismatch(alg, header.alg)127 }128 const now = (Date.now() / 1000) | 0129 if (nbf && payload.nbf && payload.nbf > now) {130 throw new JwtTokenNotBefore(token)131 }
124 unmodified lines
modified:src/utils/jwt/types.ts+14 added
8 unmodified lines
9 this.name = 'JwtAlgorithmNotImplemented'10 }11}1213export class JwtAlgorithmRequired extends Error {14 constructor() {15 super('JWT verification requires "alg" option to be specified')16 this.name = 'JwtAlgorithmRequired'17 }18}1920export class JwtAlgorithmMismatch extends Error {21 constructor(expected: string, actual: string) {22 super(`JWT algorithm mismatch: expected "${expected}", got "${actual}"`)23 this.name = 'JwtAlgorithmMismatch'24 }25}2627export class JwtTokenInvalid extends Error {28 constructor(token: string) {29 super(`invalid JWT token: ${token}`)30 this.name = 'JwtTokenInvalid'
112 unmodified lines