fix(bearer-auth, basic-auth): handler should not be executed when unauthorized (#608)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(bearer-auth): handler should not be executed when unauthorized * fix(basic-auth): also fix basic auth
authored by Shawn · committed by GitHub · parent 0da7835 · Browse files · 4 files·+73 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+73 added−28 removed
- tests:+69 added−23 removed
- other:+4 added−5 removed
Provenance
- Commit
dc82384- Tree
0786b04- Author
Shawn <admin@mail.xrlian.com>- Committer
GitHub <noreply@github.com>- Parent
0da7835
4 files changed+73 added−28 removed
modified:src/middleware/basic-auth/index.test.ts+40 added-10 removed
2 unmodified lines3456789101112131415161718192049 unmodified lines70717273747570767778798081828384858687888990919293949596977576777898991001011028081103104105106107108109881101111121131141151161171181191201211221231243 unmodified lines1281291301311321331341351363 unmodified lines1401411421431441451461471481491501511521531541551561571583 unmodified lines1621631641651661671681691701711441721731741751761771781791801811823 unmodified lines1861871881891901911921931641941952 unmodified linesimport { basicAuth } from '.'
describe('Basic Auth by Middleware', () => { const crypto = global.crypto let handlerExecuted: boolean beforeAll(() => { global.crypto = require('crypto').webcrypto }) afterAll(() => { global.crypto = crypto }) beforeEach(() => { handlerExecuted = false })
const app = new Hono()
const username = 'hono-user-a'49 unmodified lines hashFunction: (data: string) => SHA256(data).toString(), }) )
// To Hono maintainers: I don't think we can support nested middleware when the middleware returns early // since `next()` is never called in this case. Feel free to correct me app.use('/nested/*', async (c, next) => { /* app.use('/nested/*', async (c, next) => { const auth = basicAuth({ username: username, password: password }) await auth(c, next) }) */
app.get('/auth/*', (c) => { handlerExecuted = true return c.text('auth') }) app.get('/auth-unicode/*', (c) => { handlerExecuted = true return c.text('auth') }) app.get('/auth-multi/*', (c) => { handlerExecuted = true return c.text('auth') }) app.get('/auth-override-func/*', (c) => { handlerExecuted = true return c.text('auth') })
app.get('/auth/*', (c) => c.text('auth')) app.get('/auth-unicode/*', (c) => c.text('auth')) app.get('/auth-multi/*', (c) => c.text('auth')) app.get('/auth-override-func/*', (c) => c.text('auth')) /* app.get('/nested/*', (c) => { handlerExecuted = true return c.text('nested') }) */
app.get('/nested/*', (c) => c.text('nested'))
it('Should not authorize', async () => { const req = new Request('http://localhost/auth/a') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(handlerExecuted).toBeFalsy() expect(await res.text()).toBe('Unauthorized') expect(res.headers.get('x-custom')).toBe('foo') expect(res.headers.get('x-custom')).toBeNull() })
it('Should authorize', async () => { const credential = Buffer.from(username + ':' + password).toString('base64')
const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.request(req) expect(res).not.toBeNull() expect(handlerExecuted).toBeTruthy() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') expect(res.headers.get('x-custom')).toBe('foo') })3 unmodified lines
const req = new Request('http://localhost/auth-unicode/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.request(req) expect(handlerExecuted).toBeTruthy() expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })3 unmodified lines
let req = new Request('http://localhost/auth-multi/b') req.headers.set('Authorization', `Basic ${credential}`) let res = await app.request(req) expect(handlerExecuted).toBeTruthy() expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth')
handlerExecuted = false; credential = Buffer.from(usernameC + ':' + passwordC).toString('base64') req = new Request('http://localhost/auth-multi/c') req.headers.set('Authorization', `Basic ${credential}`) res = await app.request(req) expect(handlerExecuted).toBeTruthy() expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })3 unmodified lines
const req = new Request('http://localhost/auth-override-func/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.request(req) expect(handlerExecuted).toBeTruthy() expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Should authorize - nested', async () => { /* it('Should authorize - nested', async () => { const credential = Buffer.from(username + ':' + password).toString('base64')
const req = new Request('http://localhost/nested') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.request(req) expect(handlerExecuted).toBeTruthy() expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('nested') })3 unmodified lines
const req = new Request('http://localhost/nested') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.request(req) expect(handlerExecuted).toBeFalsy() expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') }) }) */})modified:src/middleware/basic-auth/index.ts+1 added-2 removed
51 unmodified lines52 return53 }54 }55 }56- ctx.res = new Response('Unauthorized', {56+ return new Response('Unauthorized', {57 status: 401,58 headers: {59 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',60 },61 })62- await next()62 }63 }modified:src/middleware/bearer-auth/index.test.ts+29 added-13 removed
1 import { Hono } from '../../hono'2 import { bearerAuth } from '.'3 4 describe('Bearer Auth by Middleware', () => {5- const app = new Hono()5+ let app: Hono6+ let handlerExecuted: boolean7+ let token: string8 9+ beforeEach(async () => {10+ app = new Hono()11+ handlerExecuted = false7- const token = 'abcdefg12345-._~+/='12+ token = 'abcdefg12345-._~+/='13+ app.use('/auth/*', bearerAuth({ token }))14+ app.use('/auth/*', async (c, next) => {15+ c.header('x-custom', 'foo')16+ await next()17+ })18+ app.get('/auth/*', (c) => {19+ handlerExecuted = true20+ return c.text('auth')21+ })22 9- app.use('/auth/*', bearerAuth({ token }))10- app.use('/auth/*', async (c, next) => {11- c.header('x-custom', 'foo')12- await next()23+ app.use('/authBot/*', bearerAuth({ token, prefix: 'Bot' }))24+ app.get('/authBot/*', (c) => {25+ handlerExecuted = true26+ return c.text('auth bot')27+ })28 })14- app.get('/auth/*', (c) => c.text('auth'))29 16- app.use('/authBot/*', bearerAuth({ token, prefix: 'Bot' }))17- app.get('/authBot/*', (c) => c.text('auth bot'))18-30 it('Should authorize', async () => {31 const req = new Request('http://localhost/auth/a')32 req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=')33 const res = await app.request(req)34 expect(res).not.toBeNull()35 expect(res.status).toBe(200)36+ expect(handlerExecuted).toBeTruthy()37 expect(await res.text()).toBe('auth')38 expect(res.headers.get('x-custom')).toBe('foo')39 })40 1 unmodified line42 const req = new Request('http://localhost/auth/a')43 const res = await app.request(req)44 expect(res).not.toBeNull()45 expect(res.status).toBe(401)46+ expect(handlerExecuted).toBeFalsy()47 expect(await res.text()).toBe('Unauthorized')35- expect(res.headers.get('x-custom')).toBe('foo')48+ expect(res.headers.get('x-custom')).toBeNull()49 })50 51 it('Should not authorize - invalid request', async () => {52 const req = new Request('http://localhost/auth/a')53 req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')54 const res = await app.request(req)55 expect(res).not.toBeNull()56+ expect(handlerExecuted).toBeFalsy()57 expect(res.status).toBe(400)58 expect(await res.text()).toBe('Bad Request')45- expect(res.headers.get('x-custom')).toBe('foo')59+ expect(res.headers.get('x-custom')).toBeNull()60 })61 62 it('Should not authorize - invalid token', async () => {63 const req = new Request('http://localhost/auth/a')1 unmodified line65 const res = await app.request(req)66 expect(res).not.toBeNull()67 expect(res.status).toBe(401)68 expect(await res.text()).toBe('Unauthorized')55- expect(res.headers.get('x-custom')).toBe('foo')69+ expect(res.headers.get('x-custom')).toBeNull()70 })71 72 it('Should authorize', async () => {73 const req = new Request('http://localhost/authBot/a')74 req.headers.set('Authorization', 'Bot abcdefg12345-._~+/=')75 const res = await app.request(req)76 expect(res).not.toBeNull()77 expect(res.status).toBe(200)78+ expect(handlerExecuted).toBeTruthy()79 expect(await res.text()).toBe('auth bot')80 })81 82 it('Should not authorize - invalid request', async () => {83 const req = new Request('http://localhost/authBot/a')84 req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=')85 const res = await app.request(req)86 expect(res).not.toBeNull()87+ expect(handlerExecuted).toBeFalsy()88 expect(res.status).toBe(400)89 expect(await res.text()).toBe('Bad Request')90 })91 })modified:src/middleware/bearer-auth/index.ts+3 added-3 removed
25 unmodified lines26 const headerToken = c.req.headers.get('Authorization')27 28 if (!headerToken) {29 // No Authorization header30- c.res = new Response('Unauthorized', {30+ return new Response('Unauthorized', {31 status: 401,32 headers: {33 'WWW-Authenticate': `${options.prefix} realm="` + realm + '"',34 },2 unmodified lines37 const regexp = new RegExp('^' + options.prefix + ' +(' + TOKEN_STRINGS + ') *$')38 const match = regexp.exec(headerToken)39 if (!match) {40 // Invalid Request41- c.res = new Response('Bad Request', {41+ return new Response('Bad Request', {42 status: 400,43 headers: {44 'WWW-Authenticate': `${options.prefix} error="invalid_request"`,45 },1 unmodified line47 } else {48 const equal = await timingSafeEqual(options.token, match[1], options.hashFunction)49 if (!equal) {50 // Invalid Token51- c.res = new Response('Unauthorized', {51+ return new Response('Unauthorized', {52 status: 401,53 headers: {54 'WWW-Authenticate': `${options.prefix} error="invalid_token"`,55 },7 unmodified lines