fix(bearer-auth): escape regex metacharacters in bearer auth prefix option (#4750)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix: escape regex metacharacters in bearer auth prefix option * Update index.ts * for nodejs 22 * Fixed to simple approaches ---------
authored by otoneko. · committed by GitHub · parent 488ea6a · Browse files · 2 files·+78 added−8 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: EdamAmex <121654029+EdamAme-x@users.noreply.github.com>
- Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
Diff stats
2 files+78 added−8 removed
- tests:+59 added−0 removed
- other:+19 added−8 removed
Provenance
- Commit
0c0bf8d- Tree
bc232a1- Author
otoneko. <116952822+otoneko1102@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
488ea6a
2 files changed+78 added−8 removed
modified:src/middleware/bearer-auth/index.test.ts+59 added
921 unmodified lines922 expect(handlerExecuted).toBeFalsy()923 expect(await res.text()).toBe('{"message":"Custom invalid token message as function object"}')924 })925 })926+927+describe('Bearer Auth with prefix containing regex metacharacters', () => {928+ let app: Hono929+ let handlerExecuted: boolean930+ const token = 'testtoken123'931+932+ beforeEach(() => {933+ app = new Hono()934+ handlerExecuted = false935+ })936+937+ it('Should not throw when prefix contains regex metacharacters', () => {938+ expect(() => {939+ bearerAuth({ token, prefix: 'Bearer (v2)' })940+ }).not.toThrow()941+ })942+943+ it('Should authorize with prefix containing parentheses', async () => {944+ app.use('/*', bearerAuth({ token, prefix: 'Bearer(v2)' }))945+ app.get('/*', (c) => {946+ handlerExecuted = true947+ return c.text('ok')948+ })949+950+ const req = new Request('http://localhost/')951+ req.headers.set('Authorization', `Bearer(v2) ${token}`)952+ const res = await app.request(req)953+ expect(res.status).toBe(200)954+ expect(handlerExecuted).toBeTruthy()955+ })956+957+ it('Should authorize with prefix containing dots and plus signs', async () => {958+ app.use('/*', bearerAuth({ token, prefix: 'X.Auth+v2' }))959+ app.get('/*', (c) => {960+ handlerExecuted = true961+ return c.text('ok')962+ })963+964+ const req = new Request('http://localhost/')965+ req.headers.set('Authorization', `X.Auth+v2 ${token}`)966+ const res = await app.request(req)967+ expect(res.status).toBe(200)968+ expect(handlerExecuted).toBeTruthy()969+ })970+971+ it('Should not match when prefix metacharacters are interpreted as regex', async () => {972+ app.use('/*', bearerAuth({ token, prefix: 'X.Y' }))973+ app.get('/*', (c) => {974+ handlerExecuted = true975+ return c.text('ok')976+ })977+978+ const req = new Request('http://localhost/')979+ req.headers.set('Authorization', `XZY ${token}`)980+ const res = await app.request(req)981+ expect(res.status).toBe(400)982+ expect(handlerExecuted).toBeFalsy()983+ })984+})modified:src/middleware/bearer-auth/index.ts+19 added-8 removed
110 unmodified lines111 options.prefix = PREFIX112 }113 114 const realm = options.realm?.replace(/"/g, '\\"')115- const prefixRegexStr = options.prefix === '' ? '' : `${options.prefix} +`116- const regexp = new RegExp(`^${prefixRegexStr}(${TOKEN_STRINGS}) *$`, 'i')117- const wwwAuthenticatePrefix = options.prefix === '' ? '' : `${options.prefix} `115+ const prefix = options.prefix116+ const tokenRegexp = new RegExp(`^${TOKEN_STRINGS}$`)117+ const wwwAuthenticatePrefix = prefix === '' ? '' : `${prefix} `118 119 const throwHTTPException = async (120 c: Context,121 status: ContentfulStatusCode,41 unmodified lines163 options.noAuthenticationHeaderMessage ||164 'Unauthorized'165 )166 } else {167- const match = regexp.exec(headerToken)168- if (!match) {167+ let tokenValue: string | undefined168+169+ if (prefix === '') {170+ tokenValue = headerToken171+ } else {172+ const headerLower = headerToken.toLowerCase()173+ const prefixLower = prefix.toLowerCase()174+ if (headerLower.startsWith(prefixLower) && headerToken[prefix.length] === ' ') {175+ tokenValue = headerToken.slice(prefix.length).trimStart()176+ }177+ }178+179+ if (!tokenValue || !tokenRegexp.test(tokenValue)) {180 // Invalid Request181 await throwHTTPException(182 c,183 400,5 unmodified lines189 )190 } else {191 let equal = false192 if ('verifyToken' in options) {182- equal = await options.verifyToken(match[1], c)193+ equal = await options.verifyToken(tokenValue, c)194 } else if (typeof options.token === 'string') {184- equal = await timingSafeEqual(options.token, match[1], options.hashFunction)195+ equal = await timingSafeEqual(options.token, tokenValue, options.hashFunction)196 } else if (Array.isArray(options.token) && options.token.length > 0) {197 for (const token of options.token) {187- if (await timingSafeEqual(token, match[1], options.hashFunction)) {198+ if (await timingSafeEqual(token, tokenValue, options.hashFunction)) {199 equal = true200 break201 }202 }16 unmodified lines