Skip to content

Commit 30277ae

Browse files
arhxamyusukebe
andauthored
feat(jwt,jwk): add a configurable WWW-Authenticate realm (#5141)
* 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 #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 #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 --------- Co-authored-by: Yusuke Wada <[email protected]>
1 parent 1f707c5 commit 30277ae

4 files changed

Lines changed: 137 additions & 2 deletions

File tree

‎src/middleware/jwk/index.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1077,4 +1077,59 @@ describe('JWK', () => {
10771077
// Note: Test for "no whitelist" was removed because alg is now required.
10781078
// This is a breaking change that enforces explicit algorithm specification for security.
10791079
})
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+
})
10801135
})

‎src/middleware/jwk/jwk.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import type { VerifyOptions } from '../../utils/jwt/jwt'
2525
* @param {boolean} [options.allow_anon] - If set to `true`, the middleware allows requests without a token to proceed without authentication.
2626
* @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.
2727
* @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.
28+
* @param {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL.
2829
* @param {AsymmetricAlgorithm[]} options.alg - An array of allowed asymmetric algorithms for JWT verification. Only tokens signed with these algorithms will be accepted.
2930
* @param {RequestInit} [init] - Optional init options for the `fetch` request when retrieving JWKS from a URI.
3031
* @param {VerifyOptions} [options.verification] - Additional options for JWK payload verification.
@@ -58,6 +59,8 @@ export const jwk = (
5859

5960
alg: AsymmetricAlgorithm[]
6061

62+
realm?: string
63+
6164
verification?: VerifyOptions
6265
},
6366
init?: RequestInit
@@ -87,6 +90,7 @@ export const jwk = (
8790
ctx,
8891
error: 'invalid_request',
8992
errDescription,
93+
realm: options.realm,
9094
}),
9195
})
9296
} else {
@@ -126,6 +130,7 @@ export const jwk = (
126130
ctx,
127131
error: 'invalid_request',
128132
errDescription,
133+
realm: options.realm,
129134
}),
130135
})
131136
}
@@ -156,6 +161,7 @@ export const jwk = (
156161
error: 'invalid_token',
157162
statusText: 'Unauthorized',
158163
errDescription: 'token verification failure',
164+
realm: options.realm,
159165
}),
160166
cause,
161167
})
@@ -172,12 +178,19 @@ function unauthorizedResponse(opts: {
172178
error: string
173179
errDescription: string
174180
statusText?: string
181+
realm?: string
175182
}) {
183+
// `realm` and `error_description` end up inside a quoted-string, so any `"`
184+
// they contain has to be escaped or the header is cut short. Same handling as
185+
// the bearer-auth middleware.
186+
const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')
187+
const errDescription = opts.errDescription.replace(/"/g, '\\"')
188+
176189
return new Response('Unauthorized', {
177190
status: 401,
178191
statusText: opts.statusText,
179192
headers: {
180-
'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,
193+
'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`,
181194
},
182195
})
183196
}

‎src/middleware/jwt/index.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,4 +744,59 @@ describe('JWT', () => {
744744
})
745745
})
746746
})
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+
})
747802
})

‎src/middleware/jwt/jwt.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export type JwtVariables<T = any> = {
2929
* @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.
3030
* @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`.
3131
* @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.
3233
* @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification.
3334
* @returns {MiddlewareHandler} The middleware handler function.
3435
*
@@ -57,6 +58,7 @@ export const jwt = (options: {
5758
| { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }
5859
alg: SignatureAlgorithm
5960
headerName?: string
61+
realm?: string
6062
verification?: VerifyOptions
6163
}): MiddlewareHandler => {
6264
const verifyOpts = options.verification || {}
@@ -88,6 +90,7 @@ export const jwt = (options: {
8890
ctx,
8991
error: 'invalid_request',
9092
errDescription,
93+
realm: options.realm,
9194
}),
9295
})
9396
} else {
@@ -124,6 +127,7 @@ export const jwt = (options: {
124127
ctx,
125128
error: 'invalid_request',
126129
errDescription,
130+
realm: options.realm,
127131
}),
128132
})
129133
}
@@ -146,6 +150,7 @@ export const jwt = (options: {
146150
error: 'invalid_token',
147151
statusText: 'Unauthorized',
148152
errDescription: 'token verification failure',
153+
realm: options.realm,
149154
}),
150155
cause,
151156
})
@@ -162,12 +167,19 @@ function unauthorizedResponse(opts: {
162167
error: string
163168
errDescription: string
164169
statusText?: string
170+
realm?: string
165171
}) {
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 as
174+
// the bearer-auth middleware.
175+
const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')
176+
const errDescription = opts.errDescription.replace(/"/g, '\\"')
177+
166178
return new Response('Unauthorized', {
167179
status: 401,
168180
statusText: opts.statusText,
169181
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}"`,
171183
},
172184
})
173185
}

0 commit comments

Comments
 (0)