feat: basic auth middleware supports overriding `hashFunction` (#128)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent ccf27fb · Browse files · 7 files·+78 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+78 added−10 removed
- tests:+24 added−0 removed
- other:+54 added−10 removed
Provenance
- Commit
7a31de5- Tree
dbf9227- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
ccf27fb
7 files changed+78 added−10 removed
modified:src/middleware/basic-auth/basic-auth.test.ts+22 added
123456744 unmodified lines52535455565758596061626364656667686970717241 unmodified lines114115116117118119120121122123124125126127128129import { Hono } from '../../hono'import { basicAuth } from './basic-auth'import { SHA256 } from 'crypto-js'
describe('Basic Auth by Middleware', () => { const crypto = global.crypto beforeAll(() => {44 unmodified lines } ) )
app.use( '/auth-override-func/*', basicAuth({ username: username, password: password, hashFunction: (data: string) => SHA256(data).toString(), }) )
app.get('/auth/*', () => new Response('auth')) app.get('/auth-unicode/*', () => new Response('auth')) app.get('/auth-multi/*', () => new Response('auth')) app.get('/auth-override-func/*', () => new Response('auth'))
it('Unauthorized', async () => { const req = new Request('http://localhost/auth/a') const res = await app.dispatch(req)41 unmodified lines expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('should authorize with sha256 function override', async () => { const credential = Buffer.from(username + ':' + password).toString('base64')
const req = new Request('http://localhost/auth-override-func/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.dispatch(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })})modified:src/middleware/basic-auth/basic-auth.ts+11 added-4 removed
31 unmodified lines32333435363637383940414243444546464748495051525455535455565758596061626364656612 unmodified lines31 unmodified lines return { username: userPass[1], password: userPass[2] }}
export const basicAuth = ( options: { username: string; password: string; realm?: string }, options: { username: string; password: string; realm?: string; hashFunction?: Function }, ...users: { username: string; password: string }[]) => { if (!options) { throw new Error('basic auth middleware requires options for "username and password"') }
if (!options.realm) { options.realm = 'Secure Area' }
users.unshift({ username: options.username, password: options.password })
return async (ctx: Context, next: Function) => { const requestUser = auth(ctx.req)
if (requestUser) { for (const user of users) { const usernameEqual = await timingSafeEqual(user.username, requestUser.username) const passwordEqual = await timingSafeEqual(user.password, requestUser.password) const usernameEqual = await timingSafeEqual( user.username, requestUser.username, options.hashFunction ) const passwordEqual = await timingSafeEqual( user.password, requestUser.password, options.hashFunction ) if (usernameEqual && passwordEqual) { // Authorized OK return next() }12 unmodified linesmodified:src/middleware/basic-auth/README.md+23 added-2 removed
1 # Basic Auth Middleware2 3 ## Usage4 5-index.js:6-5 ```js6 import { Hono } from 'hono'7 import { basicAuth } from 'hono/basic-auth'8 12 unmodified lines21 })22 23 app.fire()24 ```25+26+For Fastly Compute@Edge, polyfill `crypto` or use `crypto-js`.27+28+Install:29+30+```31+npm i crypto-js32+```33+34+Override `hashFunction`:35+36+```js37+import { SHA256 } from 'crypto-js'38+39+app.use(40+ '/auth/*',41+ basicAuth({42+ username: 'hono',43+ password: 'acoolproject',44+ hashFunction: (d: string) => SHA256(d).toString(), // <---45+ })46+)47+```modified:src/utils/buffer.test.ts+2 added
1 import { timingSafeEqual } from './buffer'2+import { SHA256 as sha256CryptoJS } from 'crypto-js'3 4 describe('buffer', () => {5 it('positive', async () => {6 expect(6 unmodified lines13 expect(await timingSafeEqual('', '')).toBe(true)14 expect(await timingSafeEqual(undefined, undefined)).toBe(true)15 expect(await timingSafeEqual(true, true)).toBe(true)16 expect(await timingSafeEqual(false, false)).toBe(true)17+ expect(await timingSafeEqual(true, true, (d: string) => sha256CryptoJS(d).toString()))18 })19 20 it('negative', async () => {21 expect(await timingSafeEqual('a', 'b')).toBe(false)22 unmodified linesmodified:src/utils/buffer.ts+7 added-3 removed
21 unmodified lines22 }23 24 export const timingSafeEqual = async (25 a: string | object | boolean,26- b: string | object | boolean26+ b: string | object | boolean,27+ hashFunction?: Function28 ) => {29+ if (!hashFunction) {30+ hashFunction = sha25631+ }28- const sa = await sha256(a)29- const sb = await sha256(b)32+ const sa = await hashFunction(a)33+ const sb = await hashFunction(b)34 return sa === sb && a === b35 }modified:package.json+3 added-1 removed
76 unmodified lines77 "compute@edge"78 ],79 "devDependencies": {80 "@cloudflare/workers-types": "^3.3.0",81+ "@types/crypto-js": "^4.1.1",82 "@types/jest": "^27.4.0",83 "@types/mustache": "^4.1.2",84 "@types/node": "^17.0.8",85 "@typescript-eslint/eslint-plugin": "^5.9.0",86 "@typescript-eslint/parser": "^5.9.0",87+ "crypto-js": "^4.1.1",88 "eslint": "^7.26.0",89 "eslint-config-prettier": "^8.3.0",90 "eslint-define-config": "^1.2.1",91 "eslint-import-resolver-typescript": "^2.0.0",12 unmodified lines104 },105 "engines": {106 "node": ">=11.0.0"107 }106-}108+}modified:yarn.lock+10 added
726 unmodified lines727 integrity sha512-K2waXdXBi2302XUdcHcR1jCeU0LL4TD9HRs/gk0N2Xvrht+G/BfJa4QObBQZfhMdxiCpV3COl5Nfq4uKTeTnJA==728 dependencies:729 "@babel/types" "^7.3.0"730 731+"@types/crypto-js@^4.1.1":732+ version "4.1.1"733+ resolved "https://registry.yarnpkg.com/@types/crypto-js/-/crypto-js-4.1.1.tgz#602859584cecc91894eb23a4892f38cfa927890d"734+ integrity sha512-BG7fQKZ689HIoc5h+6D2Dgq1fABRa0RbBWKBd9SP/MVRVXROflpm5fhwyATX5duFmbStzyzyycPB8qUYKDH3NA==735+736 "@types/graceful-fs@^4.1.2":737 version "4.1.5"738 resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.5.tgz#21ffba0d98da4350db64891f92a9e5db3cdb4e15"739 integrity sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==563 unmodified lines1303 path-key "^3.1.0"1304 shebang-command "^2.0.0"1305 which "^2.0.1"1306 1307+crypto-js@^4.1.1:1308+ version "4.1.1"1309+ resolved "https://registry.yarnpkg.com/crypto-js/-/crypto-js-4.1.1.tgz#9e485bcf03521041bd85844786b83fb7619736cf"1310+ integrity sha512-o2JlM7ydqd3Qk9CA0L4NL6mTzU2sdx96a+oOfPu8Mkl/PK51vSyoi8/rQ8NknZtk44vq15lmhAj9CIAGwgeWKw==1311+1312 cssom@^0.4.4:1313 version "0.4.4"1314 resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.4.4.tgz#5a66cf93d2d0b661d80bf6a44fb65f5c2e4e0a10"1315 integrity sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw==2571 unmodified lines