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 ---------
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
Provenance
- Commit
190f6e2- Tree
1057f48- Author
calloc134 <115209243+calloc134@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a48ef18
7 files changed+673 added−30 removed
modified:src/middleware/jwk/index.test.ts+136 added-16 removed
33 unmodified lines34 afterEach(() => server.resetHandlers())35 afterAll(() => server.close())36 37 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 lines51 })52 53 const app = new Hono()54 55- 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'] }))56 57 app.get('/backend-auth-or-anon/*', (c) => {58 handlerExecuted = true59 const payload = c.get('jwtPayload')44 unmodified lines104 })105 106 const app = new Hono()107 108- 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 lines118 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 )161 162 app.get('/auth-with-keys/*', (c) => {42 unmodified lines205 return c.json(payload)206 })207 208 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 lines216 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 })225 226 it('Should return a server error if options.jwks_uri returns a 404', async () => {224 unmodified lines451 })452 453 const app = new Hono()454 446- 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+ )459 460 app.get('/auth-with-keys/*', (c) => {461 handlerExecuted = true462 const payload = c.get('jwtPayload')42 unmodified lines505 })506 507 const app = new Hono()508 497- 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 )526 527 app.get('/auth-with-keys/*', (c) => {528 handlerExecuted = true126 unmodified lines655 const test_secret = 'Shhh'656 657 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 )673 674 app.get('/sign-cookie', async (c) => {69 unmodified lines744 745 describe('Error handling with `cause`', () => {746 const app = new Hono()747 724- 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'))750 751 app.onError((e, c) => {752 if (e instanceof HTTPException && e.cause instanceof Error) {31 unmodified lines784 }785 786 const app = new Hono()787 764- 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 )793 794 app.get('/auth-with-keys-default/*', (c) => {795 handlerExecuted = true101 unmodified lines897 expect(res.status).toBe(401)898 expect(handlerExecuted).toBeFalsy()899 })900 })901+902+ describe('Algorithm whitelist (options.alg)', () => {903+ let handlerExecuted: boolean904+905+ beforeEach(() => {906+ handlerExecuted = false907+ })908+909+ const app = new Hono()910+911+ // 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+ })917+918+ // 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+ })924+925+ // 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.927+928+ 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+ })939+940+ 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' }944+945+ // 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+ )954+955+ // 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}`962+963+ const signatureBuffer = await signing(964+ keyPair.privateKey,965+ 'ES256',966+ utf8Encoder.encode(signingInput)967+ )968+ const signature = encodeBase64Url(signatureBuffer)969+970+ const token = `${encodedHeader}.${encodedPayload}.${signature}`971+972+ 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+ })981+982+ 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+ })993+994+ // 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
8 unmodified lines910111213141516176 unmodified lines24252627282930313222 unmodified lines5556575859606162636470 unmodified lines13513613713813513914014114214314414514614736 unmodified lines8 unmodified linesimport type { MiddlewareHandler } from '../../types'import type { CookiePrefixOptions } from '../../utils/cookie'import { Jwt } from '../../utils/jwt'import '../../context'import type { AsymmetricAlgorithm } from '../../utils/jwt/jwa'import type { HonoJsonWebKey } from '../../utils/jwt/jws'import type { VerifyOptions } from '../../utils/jwt/jwt'
/**6 unmodified lines * @param {string | ((ctx: Context) => Promise<string> | string)} [options.jwks_uri] - If set to a URI string or a function that returns a URI string, attempt to fetch JWKs from it. The response must be a JSON object containing a `keys` array, which will be merged with the `keys` option. * @param {boolean} [options.allow_anon] - If set to `true`, the middleware allows requests without a token to proceed without authentication. * @param {string} [options.cookie] - If set, the middleware attempts to retrieve the token from a cookie with these options (optionally signed) only if no token is found in the header. * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'. * @param {AsymmetricAlgorithm[]} options.alg - An array of allowed asymmetric algorithms for JWT verification. Only tokens signed with these algorithms will be accepted. * @param {RequestInit} [init] - Optional init options for the `fetch` request when retrieving JWKS from a URI. * @param {VerifyOptions} [options.verification] - Additional options for JWK payload verification. * @returns {MiddlewareHandler} The middleware handler function. *22 unmodified lines | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }
headerName?: string
alg: AsymmetricAlgorithm[]
verification?: VerifyOptions }, init?: RequestInit): MiddlewareHandler => {70 unmodified lines try { const keys = typeof options.keys === 'function' ? await options.keys(ctx) : options.keys const jwks_uri = typeof options.jwks_uri === 'function' ? await options.jwks_uri(ctx) : options.jwks_uri payload = await Jwt.verifyWithJwks(token, { keys, jwks_uri, verification: verifyOpts }, init) payload = await Jwt.verifyWithJwks( token, { keys, jwks_uri, verification: verifyOpts, allowedAlgorithms: options.alg }, init ) } catch (e) { cause = e }
36 unmodified linesmodified:src/utils/jwt/jwa.test.ts+62 added
1 import { AlgorithmTypes } from './jwa'2+import type { AsymmetricAlgorithm, SymmetricAlgorithm, SignatureAlgorithm } from './jwa'3 4 describe('Types', () => {5 it('AlgorithmTypes', () => {6 expect('HS256' as AlgorithmTypes).toBe(AlgorithmTypes.HS256)14 unmodified lines21 // @ts-ignore22 expect(undefined as AlgorithmTypes).toBe(undefined)23 expect('' as AlgorithmTypes).toBe('')24 })25+26+ 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'31+32+ expect(hs256).toBe('HS256')33+ expect(hs384).toBe('HS384')34+ expect(hs512).toBe('HS512')35+36+ // Type-level test: these would cause compile errors if uncommented37+ // const rs256: SymmetricAlgorithm = 'RS256' // Error: Type '"RS256"' is not assignable to type 'SymmetricAlgorithm'38+ })39+40+ 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+ ]54+55+ expect(asymmetricAlgs).toHaveLength(10)56+57+ // Verify all asymmetric algorithms are included58+ expect(asymmetricAlgs).toContain('RS256')59+ expect(asymmetricAlgs).toContain('ES256')60+ expect(asymmetricAlgs).toContain('EdDSA')61+62+ // Type-level test: these would cause compile errors if uncommented63+ // const hs256: AsymmetricAlgorithm = 'HS256' // Error: Type '"HS256"' is not assignable to type 'AsymmetricAlgorithm'64+ })65+66+ 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+ ]83+84+ expect(allAlgs).toHaveLength(13)85+ })86 })modified:src/utils/jwt/jwa.ts+14 added
19 unmodified lines20 EdDSA = 'EdDSA',21 }22 23 export type SignatureAlgorithm = keyof typeof AlgorithmTypes24+25+export type SymmetricAlgorithm = 'HS256' | 'HS384' | 'HS512'26+27+export 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 lines6 import * as JWT from './jwt'7 import { verifyWithJwks } from './jwt'8 import {9 JwtAlgorithmMismatch,10+ JwtAlgorithmNotAllowed,11 JwtAlgorithmNotImplemented,12 JwtAlgorithmRequired,13 JwtPayloadRequiresAud,14+ JwtSymmetricAlgorithmNotAllowed,15 JwtTokenAudience,16 JwtTokenExpired,17 JwtTokenInvalid,18 JwtTokenIssuedAt,815 unmodified lines834 })835 836 describe('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'842 843+ // 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+ )854+842- // 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}`861 849- // 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)869 870 const token = `${encodedHeader}.${encodedPayload}.${signature}`871 855- // 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 alg880+881+ const keys = [keyWithoutAlg]882+883+ // Execute: Verify the JWT token signed with RS256 with allowedAlgorithms required884+ const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })885+886+ // If verification succeeds, it means header.alg was used887+ expect(result).toEqual(payload)888+ })889+})890+891+describe('verifyWithJwks security', () => {892+ it('Should reject symmetric algorithm HS256', async () => {893+ const payload = { message: 'hello world' }894+ const secret = 'secret'895+ const kid = 'dummy'896+897+ // 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}`903+904+ const signatureBuffer = await signing(secret, 'HS256', utf8Encoder.encode(signingInput))905+ const signature = encodeBase64Url(signatureBuffer)906+907+ const token = `${encodedHeader}.${encodedPayload}.${signature}`908+909 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 ]918 866- // 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+ })924 869- // 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'929+930+ 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}`935+936+ const signatureBuffer = await signing(secret, 'HS384', utf8Encoder.encode(signingInput))937+ const signature = encodeBase64Url(signatureBuffer)938+939+ const token = `${encodedHeader}.${encodedPayload}.${signature}`940+941+ const keys = [942+ {943+ kty: 'oct',944+ kid,945+ k: encodeBase64Url(utf8Encoder.encode(secret).buffer),946+ use: 'sig',947+ alg: 'HS384',948+ },949+ ]950+951+ // HS384 is rejected before allowedAlgorithms check (symmetric algorithm rejection)952+ await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(953+ JwtSymmetricAlgorithmNotAllowed954+ )955+ })956+957+ it('Should reject symmetric algorithm HS512', async () => {958+ const payload = { message: 'hello world' }959+ const secret = 'secret'960+ const kid = 'dummy'961+962+ 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}`967+968+ const signatureBuffer = await signing(secret, 'HS512', utf8Encoder.encode(signingInput))969+ const signature = encodeBase64Url(signatureBuffer)970+971+ const token = `${encodedHeader}.${encodedPayload}.${signature}`972+973+ const keys = [974+ {975+ kty: 'oct',976+ kid,977+ k: encodeBase64Url(utf8Encoder.encode(secret).buffer),978+ use: 'sig',979+ alg: 'HS512',980+ },981+ ]982+983+ // HS512 is rejected before allowedAlgorithms check (symmetric algorithm rejection)984+ await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })).rejects.toThrow(985+ JwtSymmetricAlgorithmNotAllowed986+ )987+ })988+989+ it('Should reject algorithm mismatch between JWK and JWT header', async () => {990+ const payload = { message: 'hello world' }991+ const kid = 'dummy'992+993+ // 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+ )1004+1005+ // 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}`1011+1012+ // 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)1019+1020+ const token = `${encodedHeader}.${encodedPayload}.${signature}`1021+1022+ // 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+ }1030+1031+ const keys = [keyWithAlg]1032+1033+ // RS384 in header doesn't match RS256 in JWK alg field1034+ await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['RS384'] })).rejects.toThrow(1035+ JwtAlgorithmMismatch1036+ )1037+ })1038+1039+ it('Should allow asymmetric algorithm RS256 with matching alg', async () => {1040+ const payload = { message: 'hello world' }1041+ const kid = 'dummy'1042+1043+ 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+ )1053+1054+ 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}`1059+1060+ const signatureBuffer = await signing(1061+ keyPair.privateKey,1062+ 'RS256',1063+ utf8Encoder.encode(signingInput)1064+ )1065+ const signature = encodeBase64Url(signatureBuffer)1066+1067+ const token = `${encodedHeader}.${encodedPayload}.${signature}`1068+1069+ const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1070+ const keyWithAlg = {1071+ ...jwk,1072+ kid,1073+ use: 'sig',1074+ alg: 'RS256',1075+ }1076+1077+ const keys = [keyWithAlg]1078+1079+ const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256'] })1080 expect(result).toEqual(payload)1081 })1082+1083+ 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'1088+1089+ // 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+ )1100+1101+ // 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}`1107+1108+ // Export public key as JWK (which would be used in a real attack)1109+ const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1110+1111+ // 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)1115+1116+ const token = `${encodedHeader}.${encodedPayload}.${signature}`1117+1118+ // 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+ }1125+1126+ const keys = [keyWithAlg]1127+1128+ // 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 })1134+1135+describe('verifyWithJwks algorithm whitelist', () => {1136+ it('Should reject algorithm not in whitelist', async () => {1137+ const payload = { message: 'hello world' }1138+ const kid = 'dummy'1139+1140+ // 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+ )1151+1152+ // 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}`1158+1159+ const signatureBuffer = await signing(1160+ keyPair.privateKey,1161+ 'RS256',1162+ utf8Encoder.encode(signingInput)1163+ )1164+ const signature = encodeBase64Url(signatureBuffer)1165+1166+ const token = `${encodedHeader}.${encodedPayload}.${signature}`1167+1168+ const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1169+ const keyWithAlg = {1170+ ...jwk,1171+ kid,1172+ use: 'sig',1173+ alg: 'RS256',1174+ }1175+1176+ const keys = [keyWithAlg]1177+1178+ // RS256 is not in the whitelist (only ES256 is allowed)1179+ await expect(verifyWithJwks(token, { keys, allowedAlgorithms: ['ES256'] })).rejects.toThrow(1180+ JwtAlgorithmNotAllowed1181+ )1182+ })1183+1184+ it('Should accept algorithm in whitelist', async () => {1185+ const payload = { message: 'hello world' }1186+ const kid = 'dummy'1187+1188+ // 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+ )1199+1200+ // 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}`1206+1207+ const signatureBuffer = await signing(1208+ keyPair.privateKey,1209+ 'RS256',1210+ utf8Encoder.encode(signingInput)1211+ )1212+ const signature = encodeBase64Url(signatureBuffer)1213+1214+ const token = `${encodedHeader}.${encodedPayload}.${signature}`1215+1216+ const jwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey)1217+ const keyWithAlg = {1218+ ...jwk,1219+ kid,1220+ use: 'sig',1221+ alg: 'RS256',1222+ }1223+1224+ const keys = [keyWithAlg]1225+1226+ // RS256 is in the whitelist1227+ const result = await verifyWithJwks(token, { keys, allowedAlgorithms: ['RS256', 'ES256'] })1228+ expect(result).toEqual(payload)1229+ })1230+1231+ // 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.1234+1235+ 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'1242+1243+ // 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}`1249+1250+ const signatureBuffer = await signing(secret, 'HS256', utf8Encoder.encode(signingInput))1251+ const signature = encodeBase64Url(signatureBuffer)1252+1253+ const token = `${encodedHeader}.${encodedPayload}.${signature}`1254+1255+ const keys = [1256+ {1257+ kty: 'oct',1258+ kid,1259+ k: encodeBase64Url(utf8Encoder.encode(secret).buffer),1260+ use: 'sig',1261+ alg: 'HS256',1262+ },1263+ ]1264+1265+ // 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+})1272+1273 async 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 pem174 unmodified linesmodified:src/utils/jwt/jwt.ts+27 added-2 removed
4 unmodified lines5 */6 7 import { decodeBase64Url, encodeBase64Url } from '../../utils/encode'8 import { AlgorithmTypes } from './jwa'9-import type { SignatureAlgorithm } from './jwa'9+import type { AsymmetricAlgorithm, SignatureAlgorithm, SymmetricAlgorithm } from './jwa'10 import { signing, verifying } from './jws'11 import type { HonoJsonWebKey, SignatureKey } from './jws'12 import {13 JwtAlgorithmMismatch,14+ JwtAlgorithmNotAllowed,15 JwtAlgorithmRequired,16 JwtHeaderInvalid,17 JwtHeaderRequiresKid,18 JwtPayloadRequiresAud,19+ JwtSymmetricAlgorithmNotAllowed,20 JwtTokenAudience,21 JwtTokenExpired,22 JwtTokenInvalid,23 JwtTokenIssuedAt,156 unmodified lines180 181 return payload182 }183 184+// Symmetric algorithms that are not allowed for JWK verification185+const symmetricAlgorithms: SymmetricAlgorithm[] = [186+ AlgorithmTypes.HS256,187+ AlgorithmTypes.HS384,188+ AlgorithmTypes.HS512,189+]190+191 export 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 lines208 if (!header.kid) {209 throw new JwtHeaderRequiresKid(header)210 }211 212+ // 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+ }216+217+ // Validate against allowed algorithms218+ if (!options.allowedAlgorithms.includes(header.alg as AsymmetricAlgorithm)) {219+ throw new JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms)220+ }221+222 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 lines244 if (!matchingKey) {245 throw new JwtTokenInvalid(token)246 }247 248+ // 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+ }252+253 return await verify(token, matchingKey, {229- alg: (matchingKey.alg as SignatureAlgorithm) || header.alg,254+ alg: header.alg,255 ...verifyOpts,256 })257 }258 22 unmodified linesmodified:src/utils/jwt/types.ts+14 added
73 unmodified lines74 this.name = 'JwtHeaderRequiresKid'75 }76 }77 78+export 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+}84+85+export 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+}91+92 export class JwtTokenSignatureMismatched extends Error {93 constructor(token: string) {94 super(`token(${token}) signature mismatched`)95 this.name = 'JwtTokenSignatureMismatched'61 unmodified lines