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 ---------
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
Provenance
- Commit
30277ae- Tree
3e28e07- Author
Arham Amin <132888838+arhxam@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
1f707c5
4 files changed+137 added−2 removed
modified:src/middleware/jwk/index.test.ts+55 added
1075 unmodified lines1076 1077 // 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'))1085+1086+ const res = await app.request('http://localhost/auth/page?a=1')1087+1088+ 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+ })1093+1094+ 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'))1098+1099+ const res = await app.request('http://localhost/auth/page?a=1')1100+1101+ 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+ })1106+1107+ 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'))1111+1112+ const req = new Request('http://localhost/auth/page')1113+ req.headers.set('Authorization', 'Bearer invalid-token')1114+ const res = await app.request(req)1115+1116+ 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+ })1121+1122+ 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'))1126+1127+ const res = await app.request('http://localhost/auth/page')1128+1129+ 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
23 unmodified lines24252627282930313225 unmodified lines5859606162636465666721 unmodified lines89909192939495969731 unmodified lines12913013113213313413513613722 unmodified lines1601611621631641651661671688 unmodified lines17717817918018118218318418518618718818919019119218019319419519623 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 {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL. * @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.25 unmodified lines headerName?: string
alg: AsymmetricAlgorithm[]
realm?: string
verification?: VerifyOptions }, init?: RequestInit): MiddlewareHandler => {21 unmodified lines res: unauthorizedResponse({ ctx, error: 'invalid_request', errDescription, realm: options.realm, }), }) } else { token = parts[1]31 unmodified lines res: unauthorizedResponse({ ctx, error: 'invalid_request', errDescription, realm: options.realm, }), }) }
22 unmodified lines ctx, error: 'invalid_token', statusText: 'Unauthorized', errDescription: 'token verification failure', realm: options.realm, }), cause, }) }8 unmodified lines ctx: Context error: string errDescription: string statusText?: string realm?: string}) { // `realm` and `error_description` end up inside a quoted-string, so any `"` // they contain has to be escaped or the header is cut short. Same handling as // the bearer-auth middleware. const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"') const errDescription = opts.errDescription.replace(/"/g, '\\"')
return new Response('Unauthorized', { status: 401, statusText: opts.statusText, headers: { 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`, 'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`, }, })}modified:src/middleware/jwt/index.test.ts+55 added
742 unmodified lines743 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'))752+753+ const res = await app.request('http://localhost/auth/page?a=1')754+755+ 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+ })760+761+ 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'))765+766+ const res = await app.request('http://localhost/auth/page?a=1')767+768+ 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+ })773+774+ 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'))778+779+ const req = new Request('http://localhost/auth/page')780+ req.headers.set('Authorization', 'Bearer invalid-token')781+ const res = await app.request(req)782+783+ 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+ })788+789+ 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'))793+794+ const res = await app.request('http://localhost/auth/page')795+796+ 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 lines28 * @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 * @example20 unmodified lines57 | 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 lines89 res: unauthorizedResponse({90 ctx,91 error: 'invalid_request',92 errDescription,93+ realm: options.realm,94 }),95 })96 } else {97 token = parts[1]28 unmodified lines126 res: unauthorizedResponse({127 ctx,128 error: 'invalid_request',129 errDescription,130+ realm: options.realm,131 }),132 })133 }134 14 unmodified lines149 ctx,150 error: 'invalid_token',151 statusText: 'Unauthorized',152 errDescription: 'token verification failure',153+ realm: options.realm,154 }),155 cause,156 })157 }8 unmodified lines166 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, '\\"')177+178 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