Skip to content
Myr

feat(jwt,jwk): add a configurable WWW-Authenticate realm (#5141)

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

* feat(jwt): add a realm option and escape challenge values The 401 challenge hardcoded `ctx.req.url` as the `realm`. RFC 6750 describes realm as a stable, human-readable name for the protection space, so reflecting the full URL produces a different realm for every path and query string. bearer-auth already exposes a `realm` option; jwt had no equivalent and its `unauthorizedResponse()` helper is private, leaving no way to override it. `realm` and `error_description` are also interpolated into a quoted-string without escaping, so a `"` in either truncates the header. Both are now escaped the way bearer-auth does it. The default is unchanged to stay backward compatible. Refs honojs/hono#4989 * feat(jwk): add a realm option and escape challenge values Mirrors the preceding jwt change; jwk carries an identical copy of `unauthorizedResponse()` with the same hardcoded realm and unescaped interpolation. Refs honojs/hono#4989 * test(jwt,jwk): cover realm configuration and quote escaping Asserts the configured realm reaches the WWW-Authenticate header for both the missing-credentials and invalid-token paths, that embedded double quotes are escaped, and that the default is still the request URL. The realm and escaping cases fail without the preceding commits; the default cases guard against regressing existing behavior. * add a test ---------

authored by Arham Amin · committed by GitHub · parent 1f707c5 · Browse files · 4 files+137 added−2 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

4 files+137 added−2 removed

  • tests:+110 added−0 removed
  • other:+27 added−2 removed

4 files+137 added−2 removed

modified:src/middleware/jwk/index.test.ts+55 added
1075 unmodified lines
10761077 // Note: Test for "no whitelist" was removed because alg is now required.1078 // This is a breaking change that enforces explicit algorithm specification for security.1079 })1080 describe('WWW-Authenticate realm', () => {1081 it('Should default to the request URL', async () => {1082 const app = new Hono()1083 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'] }))1084 app.get('/auth/*', (c) => c.text('ok'))10851086 const res = await app.request('http://localhost/auth/page?a=1')10871088 expect(res.status).toBe(401)1089 expect(res.headers.get('WWW-Authenticate')).toBe(1090 'Bearer realm="http://localhost/auth/page?a=1",error="invalid_request",error_description="no authorization included in request"'1091 )1092 })10931094 it('Should use the configured realm', async () => {1095 const app = new Hono()1096 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my-api' }))1097 app.get('/auth/*', (c) => c.text('ok'))10981099 const res = await app.request('http://localhost/auth/page?a=1')11001101 expect(res.status).toBe(401)1102 expect(res.headers.get('WWW-Authenticate')).toBe(1103 'Bearer realm="my-api",error="invalid_request",error_description="no authorization included in request"'1104 )1105 })11061107 it('Should use the configured realm for an invalid token', async () => {1108 const app = new Hono()1109 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my-api' }))1110 app.get('/auth/*', (c) => c.text('ok'))11111112 const req = new Request('http://localhost/auth/page')1113 req.headers.set('Authorization', 'Bearer invalid-token')1114 const res = await app.request(req)11151116 expect(res.status).toBe(401)1117 expect(res.headers.get('WWW-Authenticate')).toBe(1118 'Bearer realm="my-api",error="invalid_token",error_description="token verification failure"'1119 )1120 })11211122 it('Should escape double quotes in the realm', async () => {1123 const app = new Hono()1124 app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my "quoted" api' }))1125 app.get('/auth/*', (c) => c.text('ok'))11261127 const res = await app.request('http://localhost/auth/page')11281129 expect(res.status).toBe(401)1130 expect(res.headers.get('WWW-Authenticate')).toBe(1131 'Bearer realm="my \\"quoted\\" api",error="invalid_request",error_description="no authorization included in request"'1132 )1133 })1134 })1135})
modified:src/middleware/jwk/jwk.ts+14 added-1 removed
modified:src/middleware/jwt/index.test.ts+55 added
742 unmodified lines
743 return c.json(payload)744 })745 })746 })747 describe('WWW-Authenticate realm', () => {748 it('Should default to the request URL', async () => {749 const app = new Hono()750 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256' }))751 app.get('/auth/*', (c) => c.text('ok'))752753 const res = await app.request('http://localhost/auth/page?a=1')754755 expect(res.status).toBe(401)756 expect(res.headers.get('WWW-Authenticate')).toBe(757 'Bearer realm="http://localhost/auth/page?a=1",error="invalid_request",error_description="no authorization included in request"'758 )759 })760761 it('Should use the configured realm', async () => {762 const app = new Hono()763 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my-api' }))764 app.get('/auth/*', (c) => c.text('ok'))765766 const res = await app.request('http://localhost/auth/page?a=1')767768 expect(res.status).toBe(401)769 expect(res.headers.get('WWW-Authenticate')).toBe(770 'Bearer realm="my-api",error="invalid_request",error_description="no authorization included in request"'771 )772 })773774 it('Should use the configured realm for an invalid token', async () => {775 const app = new Hono()776 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my-api' }))777 app.get('/auth/*', (c) => c.text('ok'))778779 const req = new Request('http://localhost/auth/page')780 req.headers.set('Authorization', 'Bearer invalid-token')781 const res = await app.request(req)782783 expect(res.status).toBe(401)784 expect(res.headers.get('WWW-Authenticate')).toBe(785 'Bearer realm="my-api",error="invalid_token",error_description="token verification failure"'786 )787 })788789 it('Should escape double quotes in the realm', async () => {790 const app = new Hono()791 app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my "quoted" api' }))792 app.get('/auth/*', (c) => c.text('ok'))793794 const res = await app.request('http://localhost/auth/page')795796 expect(res.status).toBe(401)797 expect(res.headers.get('WWW-Authenticate')).toBe(798 'Bearer realm="my \\"quoted\\" api",error="invalid_request",error_description="no authorization included in request"'799 )800 })801 })802})
modified:src/middleware/jwt/jwt.ts+13 added-1 removed
27 unmodified lines
28 * @param {SignatureKey} options.secret - A value of your secret key.29 * @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 - 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`.31 * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.32 * @param {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL.33 * @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification.34 * @returns {MiddlewareHandler} The middleware handler function.35 *36 * @example
20 unmodified lines
57 | string58 | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }59 alg: SignatureAlgorithm60 headerName?: string61 realm?: string62 verification?: VerifyOptions63}): MiddlewareHandler => {64 const verifyOpts = options.verification || {}65
23 unmodified lines
89 res: unauthorizedResponse({90 ctx,91 error: 'invalid_request',92 errDescription,93 realm: options.realm,94 }),95 })96 } else {97 token = parts[1]
28 unmodified lines
126 res: unauthorizedResponse({127 ctx,128 error: 'invalid_request',129 errDescription,130 realm: options.realm,131 }),132 })133 }134
14 unmodified lines
149 ctx,150 error: 'invalid_token',151 statusText: 'Unauthorized',152 errDescription: 'token verification failure',153 realm: options.realm,154 }),155 cause,156 })157 }
8 unmodified lines
166 ctx: Context167 error: string168 errDescription: string169 statusText?: string170 realm?: string171}) {172 // `realm` and `error_description` end up inside a quoted-string, so any `"`173 // they contain has to be escaped or the header is cut short. Same handling as174 // the bearer-auth middleware.175 const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')176 const errDescription = opts.errDescription.replace(/"/g, '\\"')177178 return new Response('Unauthorized', {179 status: 401,180 statusText: opts.statusText,181 headers: {170 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,182 'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`,183 },184 })185}186
4 unmodified lines