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 JwtAlgorithmMismatch and JwtSymmetricAlgorithmNotAllowed error types * fix(utils/jwt): prevent algorithm confusion attacks in verifyWithJwks - Reject symmetric algorithms (HS256/HS384/HS512) in JWK verification - Verify JWK alg matches JWT header alg when JWK has alg field - Use header.alg for verification instead of JWK alg fallback * test(utils/jwt): add security tests for verifyWithJwks - Update header.alg fallback test to use asymmetric algorithm (RS256) - Add tests for symmetric algorithm rejection (HS256/HS384/HS512) - Add test for algorithm mismatch between JWK and JWT header - Add test for algorithm confusion attack prevention * feat(utils/jwt): add JwtAlgorithmNotAllowed error type Add new error class for algorithm whitelist validation. This error is thrown when JWT's algorithm is not in the allowed list. * feat(utils/jwt): add algorithm whitelist support to verifyWithJwks Add optional allowedAlgorithms parameter to verifyWithJwks function. When specified, only tokens signed with algorithms in the whitelist will be accepted. This provides an additional layer of security by explicitly defining which algorithms are permitted. Validation order: 1. Check algorithm against whitelist (if specified) 2. Reject symmetric algorithms (HS256/HS384/HS512) 3. Validate JWK alg matches header alg (if JWK has alg field) * feat(middleware/jwk): add alg option for algorithm whitelist Add alg option to JWK middleware to specify allowed algorithms. This option is passed to verifyWithJwks as allowedAlgorithms. Example usage: jwk({ keys, alg: ['RS256', 'ES256'] }) * test(utils/jwt): add algorithm whitelist tests for verifyWithJwks Add tests for: - Reject algorithm not in whitelist - Accept algorithm in whitelist - Accept any asymmetric algorithm when whitelist not specified - Accept any asymmetric algorithm when whitelist is empty - Reject symmetric algorithm even if in whitelist * test(middleware/jwk): add algorithm whitelist tests Add tests for JWK middleware alg option: - Authorize RS256 token when RS256 is in whitelist - Reject token when algorithm is not in whitelist - Authorize RS256 token when multiple algorithms are in whitelist - Authorize RS256 token when no whitelist is specified * feat(utils/jwt): add AsymmetricAlgorithm and SymmetricAlgorithm type definitions - Added SymmetricAlgorithm type for HMAC algorithms: HS256, HS384, HS512 - Added AsymmetricAlgorithm type for RSA/ECDSA/EdDSA algorithms - Enables compile-time prevention of algorithm confusion attacks * fix(utils/jwt): make allowedAlgorithms required in verifyWithJwks BREAKING CHANGE: allowedAlgorithms is now a required parameter with type AsymmetricAlgorithm[] - Changed allowedAlgorithms from optional to required - Changed type from SignatureAlgorithm[] to AsymmetricAlgorithm[] - Reordered validation: symmetric algorithm rejection before whitelist check - Prevents algorithm confusion attacks at both runtime and compile-time * fix(middleware/jwk): make alg option required BREAKING CHANGE: alg option is now required with type AsymmetricAlgorithm[] - Changed alg from optional to required - Changed type from SignatureAlgorithm[] to AsymmetricAlgorithm[] - Updated JSDoc to reflect breaking change - Ensures users must explicitly specify allowed algorithms * test(utils/jwt): update tests for required allowedAlgorithms - Added allowedAlgorithms: ['RS256'] to all verifyWithJwks calls - Removed tests for 'whitelist not specified' and 'empty whitelist' scenarios - Added comments explaining breaking changes - Renamed test to 'Should reject symmetric algorithm (HS256) in JWT header' * test(middleware/jwk): update tests for required alg option - Added alg: ['RS256'] to all jwk() middleware calls - Removed test for 'no whitelist' scenario (no longer applicable) - Added comments explaining breaking changes - Updated verifyWithJwks test to include allowedAlgorithms * test(utils/jwt): add type tests for algorithm type definitions - Added tests for SymmetricAlgorithm type (HS256, HS384, HS512) - Added tests for AsymmetricAlgorithm type (RS*, PS*, ES*, EdDSA) - Added tests for SignatureAlgorithm type (all 13 algorithms) - Tests verify type constraints at runtime * fix(test): resolve TypeScript errors in JWK middleware tests - Removed unused @ts-expect-error directive on line 40 - Added @ts-expect-error for empty object test (line 210) - Added required alg option to crypto.subtle test (line 220) - All 115 tests still passing * refactor: use SymmetricAlgorithm type for symmetricAlgorithms array * fix(utils/jwt): cast header.alg to SymmetricAlgorithm to prevent type errors * fix(utils/jwt): update comment for clarity on algorithm validation ---------

authored by calloc134 · committed by GitHub · parent a48ef18 · Browse files · 7 files+673 added−30 removed
This commit

State

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

Trailers

  • Co-authored-by: Yusuke Wada <yusuke@kamawada.com>

Diff stats

7 files+673 added−30 removed

  • tests:+609 added−27 removed
  • other:+64 added−3 removed

7 files+673 added−30 removed

modified:src/middleware/jwk/index.test.ts+136 added-16 removed
33 unmodified lines
34 afterEach(() => server.resetHandlers())35 afterAll(() => server.close())3637 describe('verifyWithJwks', () => {38 it('Should throw error on missing options', async () => {38 it('Should throw error on missing keys/jwks_uri options', async () => {39 const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])40 await expect(verifyWithJwks(credential, {})).rejects.toThrow(40 await expect(verifyWithJwks(credential, { allowedAlgorithms: ['RS256'] })).rejects.toThrow(41 'verifyWithJwks requires options for either "keys" or "jwks_uri" or both'42 )43 })44 })
6 unmodified lines
51 })5253 const app = new Hono()5455 app.use('/backend-auth-or-anon/*', jwk({ keys: verify_keys, allow_anon: true }))55 app.use('/backend-auth-or-anon/*', jwk({ keys: verify_keys, allow_anon: true, alg: ['RS256'] }))5657 app.get('/backend-auth-or-anon/*', (c) => {58 handlerExecuted = true59 const payload = c.get('jwtPayload')
44 unmodified lines
104 })105106 const app = new Hono()107108 app.use('/auth-with-keys/*', jwk({ keys: verify_keys }))109 app.use('/auth-with-keys-unicode/*', jwk({ keys: verify_keys }))108 app.use('/auth-with-keys/*', jwk({ keys: verify_keys, alg: ['RS256'] }))109 app.use('/auth-with-keys-unicode/*', jwk({ keys: verify_keys, alg: ['RS256'] }))110 app.use('/auth-with-keys-nested/*', async (c, next) => {111 const auth = jwk({ keys: verify_keys })111 const auth = jwk({ keys: verify_keys, alg: ['RS256'] })112 return auth(c, next)113 })114 app.use(115 '/auth-with-keys-fn/*',
2 unmodified lines
118 const response = await fetch('http://localhost/.well-known/jwks.json')119 const data = await response.json()120 return data.keys121 },122 alg: ['RS256'],123 })124 )125 app.use(126 '/auth-with-jwks_uri/*',127 jwk({128 jwks_uri: 'http://localhost/.well-known/jwks.json',129 alg: ['RS256'],130 })131 )132 app.use(133 '/auth-with-keys-and-jwks_uri/*',134 jwk({135 keys: verify_keys,136 jwks_uri: () => 'http://localhost/.well-known/jwks.json',137 alg: ['RS256'],138 })139 )140 app.use(141 '/auth-with-missing-jwks_uri/*',142 jwk({143 jwks_uri: 'http://localhost/.well-known/missing-jwks.json',144 alg: ['RS256'],145 })146 )147 app.use(148 '/auth-with-404-jwks_uri/*',149 jwk({150 jwks_uri: 'http://localhost/.well-known/404-jwks.json',151 alg: ['RS256'],152 })153 )154 app.use(155 '/auth-with-bad-jwks_uri/*',156 jwk({157 jwks_uri: 'http://localhost/.well-known/bad-jwks.json',158 alg: ['RS256'],159 })160 )161162 app.get('/auth-with-keys/*', (c) => {
42 unmodified lines
205 return c.json(payload)206 })207208 it('Should throw an error if the middleware is missing both keys and jwks_uri (empty)', async () => {209 // @ts-expect-error - Testing runtime error with missing required alg option210 expect(() => app.use('/auth-with-empty-middleware/*', jwk({}))).toThrow(211 'JWK auth middleware requires options for either "keys" or "jwks_uri"'212 )213 })
2 unmodified lines
216 const subtleSpy = vi.spyOn(global.crypto, 'subtle', 'get').mockReturnValue({217 importKey: undefined,218 // eslint-disable-next-line @typescript-eslint/no-explicit-any219 } as any)213 expect(() => app.use('/auth-with-bad-env/*', jwk({ keys: verify_keys }))).toThrow()220 expect(() =>221 app.use('/auth-with-bad-env/*', jwk({ keys: verify_keys, alg: ['RS256'] }))222 ).toThrow()223 subtleSpy.mockRestore()224 })225226 it('Should return a server error if options.jwks_uri returns a 404', async () => {
224 unmodified lines
451 })452453 const app = new Hono()454446 app.use('/auth-with-keys/*', jwk({ keys: verify_keys, headerName: 'x-custom-auth-header' }))455 app.use(456 '/auth-with-keys/*',457 jwk({ keys: verify_keys, headerName: 'x-custom-auth-header', alg: ['RS256'] })458 )459460 app.get('/auth-with-keys/*', (c) => {461 handlerExecuted = true462 const payload = c.get('jwtPayload')
42 unmodified lines
505 })506507 const app = new Hono()508497 app.use('/auth-with-keys/*', jwk({ keys: verify_keys, cookie: 'access_token' }))498 app.use('/auth-with-keys-unicode/*', jwk({ keys: verify_keys, cookie: 'access_token' }))509 app.use('/auth-with-keys/*', jwk({ keys: verify_keys, cookie: 'access_token', alg: ['RS256'] }))510 app.use(511 '/auth-with-keys-unicode/*',512 jwk({ keys: verify_keys, cookie: 'access_token', alg: ['RS256'] })513 )514 app.use(515 '/auth-with-keys-prefixed/*',501 jwk({ keys: verify_keys, cookie: { key: 'access_token', prefixOptions: 'host' } })516 jwk({517 keys: verify_keys,518 cookie: { key: 'access_token', prefixOptions: 'host' },519 alg: ['RS256'],520 })521 )522 app.use(523 '/auth-with-keys-unprefixed/*',505 jwk({ keys: verify_keys, cookie: { key: 'access_token' } })524 jwk({ keys: verify_keys, cookie: { key: 'access_token' }, alg: ['RS256'] })525 )526527 app.get('/auth-with-keys/*', (c) => {528 handlerExecuted = true
126 unmodified lines
655 const test_secret = 'Shhh'656657 app.use(658 '/auth-with-signed-cookie/*',640 jwk({ keys: verify_keys, cookie: { key: 'access_token', secret: test_secret } })659 jwk({660 keys: verify_keys,661 cookie: { key: 'access_token', secret: test_secret },662 alg: ['RS256'],663 })664 )665 app.use(666 '/auth-with-signed-with-prefix-options-cookie/*',667 jwk({668 keys: verify_keys,669 cookie: { key: 'access_token', secret: test_secret, prefixOptions: 'host' },670 alg: ['RS256'],671 })672 )673674 app.get('/sign-cookie', async (c) => {
69 unmodified lines
744745 describe('Error handling with `cause`', () => {746 const app = new Hono()747724 app.use('/auth-with-keys/*', jwk({ keys: verify_keys }))748 app.use('/auth-with-keys/*', jwk({ keys: verify_keys, alg: ['RS256'] }))749 app.get('/auth-with-keys/*', (c) => c.text('Authorized'))750751 app.onError((e, c) => {752 if (e instanceof HTTPException && e.cause instanceof Error) {
31 unmodified lines
784 }785786 const app = new Hono()787764 app.use('/auth-with-keys-default/*', jwk({ keys: verify_keys }))788 app.use('/auth-with-keys-default/*', jwk({ keys: verify_keys, alg: ['RS256'] }))789 app.use(790 '/auth-with-keys-and-issuer/*',767 jwk({ keys: verify_keys, verification: { iss: 'http://issuer.test' } })791 jwk({ keys: verify_keys, verification: { iss: 'http://issuer.test' }, alg: ['RS256'] })792 )793794 app.get('/auth-with-keys-default/*', (c) => {795 handlerExecuted = true
101 unmodified lines
897 expect(res.status).toBe(401)898 expect(handlerExecuted).toBeFalsy()899 })900 })901902 describe('Algorithm whitelist (options.alg)', () => {903 let handlerExecuted: boolean904905 beforeEach(() => {906 handlerExecuted = false907 })908909 const app = new Hono()910911 // Only allow RS256912 app.use('/auth-whitelist-rs256/*', jwk({ keys: verify_keys, alg: ['RS256'] }))913 app.get('/auth-whitelist-rs256/*', (c) => {914 handlerExecuted = true915 return c.json(c.get('jwtPayload'))916 })917918 // Allow multiple algorithms919 app.use('/auth-whitelist-multi/*', jwk({ keys: verify_keys, alg: ['RS256', 'ES256'] }))920 app.get('/auth-whitelist-multi/*', (c) => {921 handlerExecuted = true922 return c.json(c.get('jwtPayload'))923 })924925 // Note: Test for "no whitelist" was removed because alg is now required.926 // This is a breaking change that enforces explicit algorithm specification for security.927928 it('Should authorize RS256 token when RS256 is in whitelist', async () => {929 const payload = { message: 'hello world' }930 const credential = await Jwt.sign(payload, test_keys.private_keys[0]) // RS256 key931 const req = new Request('http://localhost/auth-whitelist-rs256/a')932 req.headers.set('Authorization', `Bearer ${credential}`)933 const res = await app.request(req)934 expect(res).not.toBeNull()935 expect(res.status).toBe(200)936 expect(await res.json()).toEqual(payload)937 expect(handlerExecuted).toBeTruthy()938 })939940 it('Should reject token when algorithm is not in whitelist', async () => {941 // Create a token with ES256 algorithm manually942 const kid = 'hono-test-kid-1' // Use existing kid but header will have different alg943 const payload = { message: 'hello world' }944945 // Generate ES256 key pair for signing946 const keyPair = await crypto.subtle.generateKey(947 {948 name: 'ECDSA',949 namedCurve: 'P-256',950 },951 true,952 ['sign', 'verify']953 )954955 // Create JWT with ES256956 const header = { alg: 'ES256', typ: 'JWT', kid }957 const encode = (obj: object) =>958 encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)959 const encodedHeader = encode(header)960 const encodedPayload = encode(payload)961 const signingInput = `${encodedHeader}.${encodedPayload}`962963 const signatureBuffer = await signing(964 keyPair.privateKey,965 'ES256',966 utf8Encoder.encode(signingInput)967 )968 const signature = encodeBase64Url(signatureBuffer)969970 const token = `${encodedHeader}.${encodedPayload}.${signature}`971972 const url = 'http://localhost/auth-whitelist-rs256/a'973 const req = new Request(url)974 req.headers.set('Authorization', `Bearer ${token}`)975 const res = await app.request(req)976 expect(res).not.toBeNull()977 expect(res.status).toBe(401)978 expect(res.headers.get('www-authenticate')).toMatch(/token verification failure/)979 expect(handlerExecuted).toBeFalsy()980 })981982 it('Should authorize RS256 token when multiple algorithms are in whitelist', async () => {983 const payload = { message: 'hello world' }984 const credential = await Jwt.sign(payload, test_keys.private_keys[0]) // RS256 key985 const req = new Request('http://localhost/auth-whitelist-multi/a')986 req.headers.set('Authorization', `Bearer ${credential}`)987 const res = await app.request(req)988 expect(res).not.toBeNull()989 expect(res.status).toBe(200)990 expect(await res.json()).toEqual(payload)991 expect(handlerExecuted).toBeTruthy()992 })993994 // Note: Test for "no whitelist" was removed because alg is now required.995 // This is a breaking change that enforces explicit algorithm specification for security.996 })997})
modified:src/middleware/jwk/jwk.ts+9 added-1 removed
modified:src/utils/jwt/jwa.test.ts+62 added
1import { AlgorithmTypes } from './jwa'2import type { AsymmetricAlgorithm, SymmetricAlgorithm, SignatureAlgorithm } from './jwa'34describe('Types', () => {5 it('AlgorithmTypes', () => {6 expect('HS256' as AlgorithmTypes).toBe(AlgorithmTypes.HS256)
14 unmodified lines
21 // @ts-ignore22 expect(undefined as AlgorithmTypes).toBe(undefined)23 expect('' as AlgorithmTypes).toBe('')24 })2526 it('SymmetricAlgorithm type should only include HMAC algorithms', () => {27 // These should be valid SymmetricAlgorithm values28 const hs256: SymmetricAlgorithm = 'HS256'29 const hs384: SymmetricAlgorithm = 'HS384'30 const hs512: SymmetricAlgorithm = 'HS512'3132 expect(hs256).toBe('HS256')33 expect(hs384).toBe('HS384')34 expect(hs512).toBe('HS512')3536 // Type-level test: these would cause compile errors if uncommented37 // const rs256: SymmetricAlgorithm = 'RS256' // Error: Type '"RS256"' is not assignable to type 'SymmetricAlgorithm'38 })3940 it('AsymmetricAlgorithm type should only include asymmetric algorithms', () => {41 // These should be valid AsymmetricAlgorithm values42 const asymmetricAlgs: AsymmetricAlgorithm[] = [43 'RS256',44 'RS384',45 'RS512',46 'PS256',47 'PS384',48 'PS512',49 'ES256',50 'ES384',51 'ES512',52 'EdDSA',53 ]5455 expect(asymmetricAlgs).toHaveLength(10)5657 // Verify all asymmetric algorithms are included58 expect(asymmetricAlgs).toContain('RS256')59 expect(asymmetricAlgs).toContain('ES256')60 expect(asymmetricAlgs).toContain('EdDSA')6162 // Type-level test: these would cause compile errors if uncommented63 // const hs256: AsymmetricAlgorithm = 'HS256' // Error: Type '"HS256"' is not assignable to type 'AsymmetricAlgorithm'64 })6566 it('SignatureAlgorithm type should include all algorithms', () => {67 // SignatureAlgorithm should include both symmetric and asymmetric algorithms68 const allAlgs: SignatureAlgorithm[] = [69 'HS256',70 'HS384',71 'HS512',72 'RS256',73 'RS384',74 'RS512',75 'PS256',76 'PS384',77 'PS512',78 'ES256',79 'ES384',80 'ES512',81 'EdDSA',82 ]8384 expect(allAlgs).toHaveLength(13)85 })86})
modified:src/utils/jwt/jwa.ts+14 added
19 unmodified lines
20 EdDSA = 'EdDSA',21}2223export type SignatureAlgorithm = keyof typeof AlgorithmTypes2425export type SymmetricAlgorithm = 'HS256' | 'HS384' | 'HS512'2627export type AsymmetricAlgorithm =28 | 'RS256'29 | 'RS384'30 | 'RS512'31 | 'PS256'32 | 'PS384'33 | 'PS512'34 | 'ES256'35 | 'ES384'36 | 'ES512'37 | 'EdDSA'
modified:src/utils/jwt/jwt.test.ts+411 added-11 removed
5 unmodified lines
6import * as JWT from './jwt'7import { verifyWithJwks } from './jwt'8import {9 JwtAlgorithmMismatch,10 JwtAlgorithmNotAllowed,11 JwtAlgorithmNotImplemented,12 JwtAlgorithmRequired,13 JwtPayloadRequiresAud,14 JwtSymmetricAlgorithmNotAllowed,15 JwtTokenAudience,16 JwtTokenExpired,17 JwtTokenInvalid,18 JwtTokenIssuedAt,
815 unmodified lines
834})835836describe('verifyWithJwks header.alg fallback', () => {837 it('Should use header.alg as fallback when matchingKey.alg is missing', async () => {836 // Setup: Create a JWT signed with HS384 (different from default HS256)838 // Setup: Create a JWT signed with RS256 (asymmetric algorithm)839 const payload = { message: 'hello world' }838 const headerAlg = 'HS384' // Non-default value839 const secret = 'secret'840 const headerAlg = 'RS256'841 const kid = 'dummy'842843 // Generate RSA key pair844 const keyPair = await crypto.subtle.generateKey(845 {846 name: 'RSASSA-PKCS1-v1_5',847 modulusLength: 2048,848 publicExponent: new Uint8Array([1, 0, 1]),849 hash: 'SHA-256',850 },851 true,852 ['sign', 'verify']853 )854842 // Create JWT (signed with HS384)855 // Create JWT (signed with RS256)856 const header = { alg: headerAlg, typ: 'JWT', kid }857 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)858 const encodedHeader = encode(header)859 const encodedPayload = encode(payload)860 const signingInput = `${encodedHeader}.${encodedPayload}`861849 // Use signing function from jws.ts instead of createHmac directly850 const signatureBuffer = await signing(secret, headerAlg, utf8Encoder.encode(signingInput))862 // Sign with private key863 const signatureBuffer = await signing(864 keyPair.privateKey,865 headerAlg,866 utf8Encoder.encode(signingInput)867 )868 const signature = encodeBase64Url(signatureBuffer)869870 const token = `${encodedHeader}.${encodedPayload}.${signature}`871855 // Create a key without alg property872 // Export public key as JWK without alg property873 const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)874 const keyWithoutAlg = {875 ...jwk,876 kid,877 use: 'sig',878 }879 delete keyWithoutAlg.alg // intentionally omit alg880881 const keys = [keyWithoutAlg]882883 // Execute: Verify the JWT token signed with RS256 with allowedAlgorithms required884 const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })885886 // If verification succeeds, it means header.alg was used887 expect(result).toEqual(payload)888 })889})890891describe('verifyWithJwks security', () => {892 it('Should reject symmetric algorithm HS256', async () => {893 const payload = { message: 'hello world' }894 const secret = 'secret'895 const kid = 'dummy'896897 // Create JWT (signed with HS256)898 const header = { alg: 'HS256', typ: 'JWT', kid }899 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)900 const encodedHeader = encode(header)901 const encodedPayload = encode(payload)902 const signingInput = `${encodedHeader}.${encodedPayload}`903904 const signatureBuffer = await signing(secret, 'HS256', utf8Encoder.encode(signingInput))905 const signature = encodeBase64Url(signatureBuffer)906907 const token = `${encodedHeader}.${encodedPayload}.${signature}`908909 const keys = [910 {911 kty: 'oct',912 kid,913 k: encodeBase64Url(utf8Encoder.encode(secret).buffer),914 use: 'sig',862 // alg is intentionally omitted915 alg: 'HS256',916 },917 ]918866 // Execute: Verify the JWT token signed with HS384867 const result = await verifyWithJwks(token, { keys })919 // HS256 is rejected before allowedAlgorithms check (symmetric algorithm rejection)920 await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(921 JwtSymmetricAlgorithmNotAllowed922 )923 })924869 // If verification succeeds, it means header.alg was used925 it('Should reject symmetric algorithm HS384', async () => {926 const payload = { message: 'hello world' }927 const secret = 'secret'928 const kid = 'dummy'929930 const header = { alg: 'HS384', typ: 'JWT', kid }931 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)932 const encodedHeader = encode(header)933 const encodedPayload = encode(payload)934 const signingInput = `${encodedHeader}.${encodedPayload}`935936 const signatureBuffer = await signing(secret, 'HS384', utf8Encoder.encode(signingInput))937 const signature = encodeBase64Url(signatureBuffer)938939 const token = `${encodedHeader}.${encodedPayload}.${signature}`940941 const keys = [942 {943 kty: 'oct',944 kid,945 k: encodeBase64Url(utf8Encoder.encode(secret).buffer),946 use: 'sig',947 alg: 'HS384',948 },949 ]950951 // HS384 is rejected before allowedAlgorithms check (symmetric algorithm rejection)952 await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(953 JwtSymmetricAlgorithmNotAllowed954 )955 })956957 it('Should reject symmetric algorithm HS512', async () => {958 const payload = { message: 'hello world' }959 const secret = 'secret'960 const kid = 'dummy'961962 const header = { alg: 'HS512', typ: 'JWT', kid }963 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)964 const encodedHeader = encode(header)965 const encodedPayload = encode(payload)966 const signingInput = `${encodedHeader}.${encodedPayload}`967968 const signatureBuffer = await signing(secret, 'HS512', utf8Encoder.encode(signingInput))969 const signature = encodeBase64Url(signatureBuffer)970971 const token = `${encodedHeader}.${encodedPayload}.${signature}`972973 const keys = [974 {975 kty: 'oct',976 kid,977 k: encodeBase64Url(utf8Encoder.encode(secret).buffer),978 use: 'sig',979 alg: 'HS512',980 },981 ]982983 // HS512 is rejected before allowedAlgorithms check (symmetric algorithm rejection)984 await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(985 JwtSymmetricAlgorithmNotAllowed986 )987 })988989 it('Should reject algorithm mismatch between JWK and JWT header', async () => {990 const payload = { message: 'hello world' }991 const kid = 'dummy'992993 // Generate RS256 key pair994 const keyPair = await crypto.subtle.generateKey(995 {996 name: 'RSASSA-PKCS1-v1_5',997 modulusLength: 2048,998 publicExponent: new Uint8Array([1, 0, 1]),999 hash: 'SHA-256',1000 },1001 true,1002 ['sign', 'verify']1003 )10041005 // Create JWT with RS384 in header (mismatch with RS256 key)1006 const header = { alg: 'RS384', typ: 'JWT', kid }1007 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1008 const encodedHeader = encode(header)1009 const encodedPayload = encode(payload)1010 const signingInput = `${encodedHeader}.${encodedPayload}`10111012 // Sign with RS256 key (but header says RS384)1013 const signatureBuffer = await signing(1014 keyPair.privateKey,1015 'RS256',1016 utf8Encoder.encode(signingInput)1017 )1018 const signature = encodeBase64Url(signatureBuffer)10191020 const token = `${encodedHeader}.${encodedPayload}.${signature}`10211022 // Export public key as JWK with RS256 alg1023 const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1024 const keyWithAlg = {1025 ...jwk,1026 kid,1027 use: 'sig',1028 alg: 'RS256', // JWK says RS256, but header says RS3841029 }10301031 const keys = [keyWithAlg]10321033 // RS384 in header doesn't match RS256 in JWK alg field1034 await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS384'] })).rejects.toThrow(1035 JwtAlgorithmMismatch1036 )1037 })10381039 it('Should allow asymmetric algorithm RS256 with matching alg', async () => {1040 const payload = { message: 'hello world' }1041 const kid = 'dummy'10421043 const keyPair = await crypto.subtle.generateKey(1044 {1045 name: 'RSASSA-PKCS1-v1_5',1046 modulusLength: 2048,1047 publicExponent: new Uint8Array([1, 0, 1]),1048 hash: 'SHA-256',1049 },1050 true,1051 ['sign', 'verify']1052 )10531054 const header = { alg: 'RS256', typ: 'JWT', kid }1055 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1056 const encodedHeader = encode(header)1057 const encodedPayload = encode(payload)1058 const signingInput = `${encodedHeader}.${encodedPayload}`10591060 const signatureBuffer = await signing(1061 keyPair.privateKey,1062 'RS256',1063 utf8Encoder.encode(signingInput)1064 )1065 const signature = encodeBase64Url(signatureBuffer)10661067 const token = `${encodedHeader}.${encodedPayload}.${signature}`10681069 const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1070 const keyWithAlg = {1071 ...jwk,1072 kid,1073 use: 'sig',1074 alg: 'RS256',1075 }10761077 const keys = [keyWithAlg]10781079 const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })1080 expect(result).toEqual(payload)1081 })10821083 it('Should reject algorithm confusion attack (HS256 with RSA public key)', async () => {1084 // This test simulates the algorithm confusion attack where an attacker1085 // tries to use HS256 with a public RSA key as the HMAC secret1086 const payload = { message: 'hello world' }1087 const kid = 'dummy'10881089 // Generate RSA key pair (normally used for RS256)1090 const keyPair = await crypto.subtle.generateKey(1091 {1092 name: 'RSASSA-PKCS1-v1_5',1093 modulusLength: 2048,1094 publicExponent: new Uint8Array([1, 0, 1]),1095 hash: 'SHA-256',1096 },1097 true,1098 ['sign', 'verify']1099 )11001101 // Attacker creates a JWT with HS256 in header1102 const header = { alg: 'HS256', typ: 'JWT', kid }1103 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1104 const encodedHeader = encode(header)1105 const encodedPayload = encode(payload)1106 const signingInput = `${encodedHeader}.${encodedPayload}`11071108 // Export public key as JWK (which would be used in a real attack)1109 const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)11101111 // Attacker would sign with the public key bytes as HMAC secret1112 // We don't need to actually sign for this test - just verify rejection1113 const signatureBuffer = await signing('fake-secret', 'HS256', utf8Encoder.encode(signingInput))1114 const signature = encodeBase64Url(signatureBuffer)11151116 const token = `${encodedHeader}.${encodedPayload}.${signature}`11171118 // JWK has RS256 alg, but JWT header has HS256 (confusion attack)1119 const keyWithAlg = {1120 ...jwk,1121 kid,1122 use: 'sig',1123 alg: 'RS256',1124 }11251126 const keys = [keyWithAlg]11271128 // Should reject because HS256 is a symmetric algorithm (checked before allowedAlgorithms)1129 await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(1130 JwtSymmetricAlgorithmNotAllowed1131 )1132 })1133})11341135describe('verifyWithJwks algorithm whitelist', () => {1136 it('Should reject algorithm not in whitelist', async () => {1137 const payload = { message: 'hello world' }1138 const kid = 'dummy'11391140 // Generate RS256 key pair1141 const keyPair = await crypto.subtle.generateKey(1142 {1143 name: 'RSASSA-PKCS1-v1_5',1144 modulusLength: 2048,1145 publicExponent: new Uint8Array([1, 0, 1]),1146 hash: 'SHA-256',1147 },1148 true,1149 ['sign', 'verify']1150 )11511152 // Create JWT with RS2561153 const header = { alg: 'RS256', typ: 'JWT', kid }1154 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1155 const encodedHeader = encode(header)1156 const encodedPayload = encode(payload)1157 const signingInput = `${encodedHeader}.${encodedPayload}`11581159 const signatureBuffer = await signing(1160 keyPair.privateKey,1161 'RS256',1162 utf8Encoder.encode(signingInput)1163 )1164 const signature = encodeBase64Url(signatureBuffer)11651166 const token = `${encodedHeader}.${encodedPayload}.${signature}`11671168 const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1169 const keyWithAlg = {1170 ...jwk,1171 kid,1172 use: 'sig',1173 alg: 'RS256',1174 }11751176 const keys = [keyWithAlg]11771178 // RS256 is not in the whitelist (only ES256 is allowed)1179 await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['ES256'] })).rejects.toThrow(1180 JwtAlgorithmNotAllowed1181 )1182 })11831184 it('Should accept algorithm in whitelist', async () => {1185 const payload = { message: 'hello world' }1186 const kid = 'dummy'11871188 // Generate RS256 key pair1189 const keyPair = await crypto.subtle.generateKey(1190 {1191 name: 'RSASSA-PKCS1-v1_5',1192 modulusLength: 2048,1193 publicExponent: new Uint8Array([1, 0, 1]),1194 hash: 'SHA-256',1195 },1196 true,1197 ['sign', 'verify']1198 )11991200 // Create JWT with RS2561201 const header = { alg: 'RS256', typ: 'JWT', kid }1202 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1203 const encodedHeader = encode(header)1204 const encodedPayload = encode(payload)1205 const signingInput = `${encodedHeader}.${encodedPayload}`12061207 const signatureBuffer = await signing(1208 keyPair.privateKey,1209 'RS256',1210 utf8Encoder.encode(signingInput)1211 )1212 const signature = encodeBase64Url(signatureBuffer)12131214 const token = `${encodedHeader}.${encodedPayload}.${signature}`12151216 const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1217 const keyWithAlg = {1218 ...jwk,1219 kid,1220 use: 'sig',1221 alg: 'RS256',1222 }12231224 const keys = [keyWithAlg]12251226 // RS256 is in the whitelist1227 const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256', 'ES256'] })1228 expect(result).toEqual(payload)1229 })12301231 // Note: Tests for "whitelist not specified" and "empty whitelist" were removed1232 // because allowedAlgorithms is now required (not optional).1233 // This is a breaking change that enforces explicit algorithm specification for security.12341235 it('Should reject symmetric algorithm (HS256) in JWT header', async () => {1236 // This test verifies that symmetric algorithms are rejected even when1237 // using verifyWithJwks with asymmetric algorithm whitelist.1238 // Note: HS256 cannot be added to allowedAlgorithms due to type constraints (AsymmetricAlgorithm[])1239 const payload = { message: 'hello world' }1240 const secret = 'secret'1241 const kid = 'dummy'12421243 // Create JWT with HS2561244 const header = { alg: 'HS256', typ: 'JWT', kid }1245 const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)1246 const encodedHeader = encode(header)1247 const encodedPayload = encode(payload)1248 const signingInput = `${encodedHeader}.${encodedPayload}`12491250 const signatureBuffer = await signing(secret, 'HS256', utf8Encoder.encode(signingInput))1251 const signature = encodeBase64Url(signatureBuffer)12521253 const token = `${encodedHeader}.${encodedPayload}.${signature}`12541255 const keys = [1256 {1257 kty: 'oct',1258 kid,1259 k: encodeBase64Url(utf8Encoder.encode(secret).buffer),1260 use: 'sig',1261 alg: 'HS256',1262 },1263 ]12641265 // HS256 in JWT header should be rejected as symmetric algorithm1266 // (symmetric algorithm check happens before allowedAlgorithms check)1267 await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(1268 JwtSymmetricAlgorithmNotAllowed1269 )1270 })1271})12721273async function exportPEMPrivateKey(key: CryptoKey): Promise<string> {1274 const exported = await crypto.subtle.exportKey('pkcs8', key)1275 const pem = `-----BEGIN PRIVATE KEY-----\n${encodeBase64(exported)}\n-----END PRIVATE KEY-----`1276 return pem
174 unmodified lines
modified:src/utils/jwt/jwt.ts+27 added-2 removed
4 unmodified lines
5 */67import { decodeBase64Url, encodeBase64Url } from '../../utils/encode'8import { AlgorithmTypes } from './jwa'9import type { SignatureAlgorithm } from './jwa'9import type { AsymmetricAlgorithm, SignatureAlgorithm, SymmetricAlgorithm } from './jwa'10import { signing, verifying } from './jws'11import type { HonoJsonWebKey, SignatureKey } from './jws'12import {13 JwtAlgorithmMismatch,14 JwtAlgorithmNotAllowed,15 JwtAlgorithmRequired,16 JwtHeaderInvalid,17 JwtHeaderRequiresKid,18 JwtPayloadRequiresAud,19 JwtSymmetricAlgorithmNotAllowed,20 JwtTokenAudience,21 JwtTokenExpired,22 JwtTokenInvalid,23 JwtTokenIssuedAt,
156 unmodified lines
180181 return payload182}183184// Symmetric algorithms that are not allowed for JWK verification185const symmetricAlgorithms: SymmetricAlgorithm[] = [186 AlgorithmTypes.HS256,187 AlgorithmTypes.HS384,188 AlgorithmTypes.HS512,189]190191export const verifyWithJwks = async (192 token: string,193 options: {194 keys?: HonoJsonWebKey[]195 jwks_uri?: string196 verification?: VerifyOptions197 allowedAlgorithms: AsymmetricAlgorithm[]198 },199 init?: RequestInit200): Promise<JWTPayload> => {201 const verifyOpts = options.verification || {}
6 unmodified lines
208 if (!header.kid) {209 throw new JwtHeaderRequiresKid(header)210 }211212 // Reject symmetric algorithms (HS256, HS384, HS512) to prevent algorithm confusion attacks213 if (symmetricAlgorithms.includes(header.alg as SymmetricAlgorithm)) {214 throw new JwtSymmetricAlgorithmNotAllowed(header.alg)215 }216217 // Validate against allowed algorithms218 if (!options.allowedAlgorithms.includes(header.alg as AsymmetricAlgorithm)) {219 throw new JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms)220 }221222 if (options.jwks_uri) {223 const response = await fetch(options.jwks_uri, init)224 if (!response.ok) {225 throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`)
18 unmodified lines
244 if (!matchingKey) {245 throw new JwtTokenInvalid(token)246 }247248 // Verify that JWK's alg matches JWT header's alg when JWK has alg field249 if (matchingKey.alg && matchingKey.alg !== header.alg) {250 throw new JwtAlgorithmMismatch(matchingKey.alg, header.alg)251 }252253 return await verify(token, matchingKey, {229 alg: (matchingKey.alg as SignatureAlgorithm) || header.alg,254 alg: header.alg,255 ...verifyOpts,256 })257}258
22 unmodified lines
modified:src/utils/jwt/types.ts+14 added
73 unmodified lines
74 this.name = 'JwtHeaderRequiresKid'75 }76}7778export class JwtSymmetricAlgorithmNotAllowed extends Error {79 constructor(alg: string) {80 super(`symmetric algorithm "${alg}" is not allowed for JWK verification`)81 this.name = 'JwtSymmetricAlgorithmNotAllowed'82 }83}8485export class JwtAlgorithmNotAllowed extends Error {86 constructor(alg: string, allowedAlgorithms: string[]) {87 super(`algorithm "${alg}" is not in the allowed list: [${allowedAlgorithms.join(', ')}]`)88 this.name = 'JwtAlgorithmNotAllowed'89 }90}9192export class JwtTokenSignatureMismatched extends Error {93 constructor(token: string) {94 super(`token(${token}) signature mismatched`)95 this.name = 'JwtTokenSignatureMismatched'
61 unmodified lines