index.test.ts
This file
Path
src/middleware/basic-auth/index.test.ts
434 lines · 12.6 KiB · TypeScript
Last changed by
chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–2why, one step back1import { createHash } from 'crypto'2import { basicAuth } from '.'chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
line 3why, one step back3import { Hono } from '../../hono'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 4–434why, one step back45describe('Basic Auth by Middleware', () => {6 let handlerExecuted: boolean78 beforeEach(() => {9 handlerExecuted = false10 })1112 const app = new Hono()1314 const username = 'hono-user-a'15 const password = 'hono-password-a'16 const unicodePassword = '炎'1718 const usernameB = 'hono-user-b'19 const passwordB = 'hono-password-b'2021 const usernameC = 'hono-user-c'22 const passwordC = 'hono-password-c'2324 app.use(25 '/auth/*',26 basicAuth({27 username,28 password,29 })30 )31 // Test multiple handlers32 app.use('/auth/*', async (c, next) => {33 c.header('x-custom', 'foo')34 await next()35 })3637 app.use(38 '/auth-unicode/*',39 basicAuth({40 username: username,41 password: unicodePassword,42 })43 )4445 app.use(46 '/auth-multi/*',47 basicAuth(48 {49 username: usernameB,50 password: passwordB,51 },52 {53 username: usernameC,54 password: passwordC,55 }56 )57 )5859 app.use(60 '/auth-override-func/*',61 basicAuth({62 username: username,63 password: password,64 hashFunction: (data: string) => createHash('sha256').update(data).digest('hex'),65 })66 )6768 app.use('/nested/*', async (c, next) => {69 const auth = basicAuth({ username: username, password: password })70 return auth(c, next)71 })7273 app.use('/verify-user/*', async (c, next) => {74 const auth = basicAuth({75 verifyUser: (username, password, c) => {76 return (77 c.req.path === '/verify-user' &&78 username === 'dynamic-user' &&79 password === 'hono-password'80 )81 },82 })83 return auth(c, next)84 })8586 app.use(87 '/auth-custom-invalid-user-message-string/*',88 basicAuth({89 username,90 password,91 invalidUserMessage: 'Custom unauthorized message as string',92 })93 )9495 app.use(96 '/auth-custom-invalid-user-message-object/*',97 basicAuth({98 username,99 password,100 invalidUserMessage: { message: 'Custom unauthorized message as object' },101 })102 )103104 app.use(105 '/auth-custom-invalid-user-message-function-string/*',106 basicAuth({107 username,108 password,109 invalidUserMessage: () => 'Custom unauthorized message as function string',110 })111 )112113 app.use(114 '/auth-custom-invalid-user-message-function-object/*',115 basicAuth({116 username,117 password,118 invalidUserMessage: () => ({ message: 'Custom unauthorized message as function object' }),119 })120 )121122 app.get('/auth/*', (c) => {123 handlerExecuted = true124 return c.text('auth')125 })126 app.get('/auth-unicode/*', (c) => {127 handlerExecuted = true128 return c.text('auth')129 })130 app.get('/auth-multi/*', (c) => {131 handlerExecuted = true132 return c.text('auth')133 })134 app.get('/auth-override-func/*', (c) => {135 handlerExecuted = true136 return c.text('auth')137 })138139 app.get('/nested/*', (c) => {140 handlerExecuted = true141 return c.text('nested')142 })143144 app.get('/verify-user', (c) => {145 handlerExecuted = true146 return c.text('verify-user')147 })148149 app.get('/auth-custom-invalid-user-message-string/*', (c) => {150 handlerExecuted = true151 return c.text('auth')152 })153 app.get('/auth-custom-invalid-user-message-object/*', (c) => {154 handlerExecuted = true155 return c.text('auth')156 })157 app.get('/auth-custom-invalid-user-message-function-string/*', (c) => {158 handlerExecuted = true159 return c.text('auth')160 })161162 app.get('/auth-custom-invalid-user-message-function-object/*', (c) => {163 handlerExecuted = true164 return c.text('auth')165 })166167 it('Should not authorize', async () => {168 const req = new Request('http://localhost/auth/a')169 const res = await app.request(req)170 expect(res).not.toBeNull()171 expect(res.status).toBe(401)172 expect(handlerExecuted).toBeFalsy()173 expect(await res.text()).toBe('Unauthorized')174 expect(res.headers.get('x-custom')).toBeNull()175 })176177 it('Should authorize', async () => {178 const credential = Buffer.from(username + ':' + password).toString('base64')179180 const req = new Request('http://localhost/auth/a')181 req.headers.set('Authorization', `Basic ${credential}`)182 const res = await app.request(req)183 expect(res).not.toBeNull()184 expect(handlerExecuted).toBeTruthy()185 expect(res.status).toBe(200)186 expect(await res.text()).toBe('auth')187 expect(res.headers.get('x-custom')).toBe('foo')188 })189190 it('Should authorize Unicode', async () => {191 const credential = Buffer.from(username + ':' + unicodePassword).toString('base64')192193 const req = new Request('http://localhost/auth-unicode/a')194 req.headers.set('Authorization', `Basic ${credential}`)195 const res = await app.request(req)196 expect(handlerExecuted).toBeTruthy()197 expect(res).not.toBeNull()198 expect(res.status).toBe(200)199 expect(await res.text()).toBe('auth')200 })201202 it('Should authorize multiple users', async () => {203 let credential = Buffer.from(usernameB + ':' + passwordB).toString('base64')204205 let req = new Request('http://localhost/auth-multi/b')206 req.headers.set('Authorization', `Basic ${credential}`)207 let res = await app.request(req)208 expect(handlerExecuted).toBeTruthy()209 expect(res).not.toBeNull()210 expect(res.status).toBe(200)211 expect(await res.text()).toBe('auth')212213 handlerExecuted = false214 credential = Buffer.from(usernameC + ':' + passwordC).toString('base64')215 req = new Request('http://localhost/auth-multi/c')216 req.headers.set('Authorization', `Basic ${credential}`)217 res = await app.request(req)218 expect(handlerExecuted).toBeTruthy()219 expect(res).not.toBeNull()220 expect(res.status).toBe(200)221 expect(await res.text()).toBe('auth')222 })223224 it('Should authorize with sha256 function override', async () => {225 const credential = Buffer.from(username + ':' + password).toString('base64')226227 const req = new Request('http://localhost/auth-override-func/a')228 req.headers.set('Authorization', `Basic ${credential}`)229 const res = await app.request(req)230 expect(handlerExecuted).toBeTruthy()231 expect(res).not.toBeNull()232 expect(res.status).toBe(200)233 expect(await res.text()).toBe('auth')234 })235236 it('Should authorize - nested', async () => {237 const credential = Buffer.from(username + ':' + password).toString('base64')238239 const req = new Request('http://localhost/nested')240 req.headers.set('Authorization', `Basic ${credential}`)241 const res = await app.request(req)242 expect(handlerExecuted).toBeTruthy()243 expect(res).not.toBeNull()244 expect(res.status).toBe(200)245 expect(await res.text()).toBe('nested')246 })247248 it('Should not authorize - nested', async () => {249 const credential = Buffer.from('foo' + ':' + 'bar').toString('base64')250251 const req = new Request('http://localhost/nested')252 req.headers.set('Authorization', `Basic ${credential}`)253 const res = await app.request(req)254 expect(handlerExecuted).toBeFalsy()255 expect(res).not.toBeNull()256 expect(res.status).toBe(401)257 expect(await res.text()).toBe('Unauthorized')258 })259260 it('Should authorize - verifyUser', async () => {261 const credential = Buffer.from('dynamic-user' + ':' + 'hono-password').toString('base64')262263 const req = new Request('http://localhost/verify-user')264 req.headers.set('Authorization', `Basic ${credential}`)265 const res = await app.request(req)266 expect(handlerExecuted).toBeTruthy()267 expect(res).not.toBeNull()268 expect(res.status).toBe(200)269 expect(await res.text()).toBe('verify-user')270 })271272 it('Should not authorize - verifyUser', async () => {273 const credential = Buffer.from('foo' + ':' + 'bar').toString('base64')274275 const req = new Request('http://localhost/verify-user')276 req.headers.set('Authorization', `Basic ${credential}`)277 const res = await app.request(req)278 expect(handlerExecuted).toBeFalsy()279 expect(res).not.toBeNull()280 expect(res.status).toBe(401)281 expect(await res.text()).toBe('Unauthorized')282 })283284 it('Should not authorize - custom invalid user message as string', async () => {285 const req = new Request('http://localhost/auth-custom-invalid-user-message-string')286 const res = await app.request(req)287 expect(res).not.toBeNull()288 expect(res.status).toBe(401)289 expect(handlerExecuted).toBeFalsy()290 expect(await res.text()).toBe('Custom unauthorized message as string')291 })292293 it('Should not authorize - custom invalid user message as object', async () => {294 const req = new Request('http://localhost/auth-custom-invalid-user-message-object')295 const res = await app.request(req)296 expect(res).not.toBeNull()297 expect(res.status).toBe(401)298 expect(res.headers.get('Content-Type')).toMatch('application/json')299 expect(handlerExecuted).toBeFalsy()300 expect(await res.text()).toBe('{"message":"Custom unauthorized message as object"}')301 })302303 it('Should not authorize - custom invalid user message as function string', async () => {304 const req = new Request('http://localhost/auth-custom-invalid-user-message-function-string')305 const res = await app.request(req)306 expect(res).not.toBeNull()307 expect(res.status).toBe(401)308 expect(handlerExecuted).toBeFalsy()309 expect(await res.text()).toBe('Custom unauthorized message as function string')310 })311312 it('Should not authorize - custom invalid user message as function object', async () => {313 const req = new Request('http://localhost/auth-custom-invalid-user-message-function-object')314 const res = await app.request(req)315 expect(res).not.toBeNull()316 expect(res.status).toBe(401)317 expect(res.headers.get('Content-Type')).toMatch('application/json')318 expect(handlerExecuted).toBeFalsy()319 expect(await res.text()).toBe('{"message":"Custom unauthorized message as function object"}')320 })321})322323describe('Basic Auth with onAuthSuccess', () => {324 const username = 'callback-user'325 const password = 'callback-pass'326327 it('should call onAuthSuccess callback on successful auth', async () => {328 type Env = { Variables: { custom: string } }329 const app = new Hono<Env>()330 let callbackCalled = false331 let callbackUsername = ''332333 app.use(334 '/*',335 basicAuth({336 username,337 password,338 onAuthSuccess: (c, u) => {339 callbackCalled = true340 callbackUsername = u341 c.set('custom', 'value')342 },343 })344 )345 app.get('/', (c) => c.text(c.get('custom') || 'no-custom'))346347 const credential = Buffer.from(`${username}:${password}`).toString('base64')348 const res = await app.request('/', {349 headers: { Authorization: `Basic ${credential}` },350 })351352 expect(callbackCalled).toBe(true)353 expect(callbackUsername).toBe(username)354 expect(res.status).toBe(200)355 expect(await res.text()).toBe('value')356 })357358 it('should support async onAuthSuccess callback', async () => {359 type Env = { Variables: { asyncValue: string } }360 const app = new Hono<Env>()361362 app.use(363 '/*',364 basicAuth({365 username,366 password,367 onAuthSuccess: async (c) => {368 await new Promise((resolve) => setTimeout(resolve, 10))369 c.set('asyncValue', 'done')370 },371 })372 )373 app.get('/', (c) => c.text(c.get('asyncValue') || 'not-done'))374375 const credential = Buffer.from(`${username}:${password}`).toString('base64')376 const res = await app.request('/', {377 headers: { Authorization: `Basic ${credential}` },378 })379 expect(res.status).toBe(200)380 expect(await res.text()).toBe('done')381 })382383 it('should not call onAuthSuccess on failed auth', async () => {384 const app = new Hono()385 let callbackCalled = false386387 app.use(388 '/*',389 basicAuth({390 username,391 password,392 onAuthSuccess: () => {393 callbackCalled = true394 },395 })396 )397 app.get('/', (c) => c.text('ok'))398399 const credential = Buffer.from('wrong:wrong').toString('base64')400 const res = await app.request('/', {401 headers: { Authorization: `Basic ${credential}` },402 })403404 expect(callbackCalled).toBe(false)405 expect(res.status).toBe(401)406 })407408 it('should work with verifyUser mode', async () => {409 type Env = { Variables: { verified: string } }410 const app = new Hono<Env>()411 let callbackUsername = ''412413 app.use(414 '/*',415 basicAuth({416 verifyUser: (u, p) => u === username && p === password,417 onAuthSuccess: (c, u) => {418 callbackUsername = u419 c.set('verified', 'yes')420 },421 })422 )423 app.get('/', (c) => c.text(c.get('verified') || 'no'))424425 const credential = Buffer.from(`${username}:${password}`).toString('base64')426 const res = await app.request('/', {427 headers: { Authorization: `Basic ${credential}` },428 })429430 expect(callbackUsername).toBe(username)431 expect(res.status).toBe(200)432 expect(await res.text()).toBe('yes')433 })434})