Skip to content
Myr

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

2 files+78 added−8 removed

modified:src/middleware/bearer-auth/index.test.ts+59 added
921 unmodified lines
922 expect(handlerExecuted).toBeFalsy()923 expect(await res.text()).toBe('{"message":"Custom invalid token message as function object"}')924 })925})926927describe('Bearer Auth with prefix containing regex metacharacters', () => {928 let app: Hono929 let handlerExecuted: boolean930 const token = 'testtoken123'931932 beforeEach(() => {933 app = new Hono()934 handlerExecuted = false935 })936937 it('Should not throw when prefix contains regex metacharacters', () => {938 expect(() => {939 bearerAuth({ token, prefix: 'Bearer (v2)' })940 }).not.toThrow()941 })942943 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 })949950 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 })956957 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 })963964 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 })970971 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 })977978 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 lines
111 options.prefix = PREFIX112 }113114 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} `118119 const throwHTTPException = async (120 c: Context,121 status: ContentfulStatusCode,
41 unmodified lines
163 options.noAuthenticationHeaderMessage ||164 'Unauthorized'165 )166 } else {167 const match = regexp.exec(headerToken)168 if (!match) {167 let tokenValue: string | undefined168169 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 }178179 if (!tokenValue || !tokenRegexp.test(tokenValue)) {180 // Invalid Request181 await throwHTTPException(182 c,183 400,
5 unmodified lines
189 )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