|
| 1 | +import chai from 'chai' |
| 2 | +import sinon from 'sinon' |
| 3 | +import sinonChai from 'sinon-chai' |
| 4 | + |
| 5 | +import { isAdminRateLimited } from '../../../src/utils/admin-rate-limit' |
| 6 | + |
| 7 | +chai.use(sinonChai) |
| 8 | +const { expect } = chai |
| 9 | + |
| 10 | +describe('isAdminRateLimited', () => { |
| 11 | + const baseSettings = { |
| 12 | + network: { |
| 13 | + remoteIpHeader: 'x-forwarded-for', |
| 14 | + }, |
| 15 | + limits: { |
| 16 | + admin: { |
| 17 | + rateLimits: [{ rate: 30, period: 60000 }], |
| 18 | + loginRateLimits: [{ rate: 10, period: 900000 }], |
| 19 | + ipWhitelist: [], |
| 20 | + }, |
| 21 | + }, |
| 22 | + } |
| 23 | + |
| 24 | + const makeRequest = (remoteAddress = '1.2.3.4') => |
| 25 | + ({ |
| 26 | + headers: {}, |
| 27 | + connection: { remoteAddress }, |
| 28 | + socket: { remoteAddress }, |
| 29 | + }) as any |
| 30 | + |
| 31 | + it('returns false when no rate limits are configured', async () => { |
| 32 | + const rateLimiter = { hit: sinon.stub().resolves(false) } |
| 33 | + const settings = { ...baseSettings, limits: { admin: { ipWhitelist: [] } } } |
| 34 | + |
| 35 | + const limited = await isAdminRateLimited(makeRequest(), settings as any, () => rateLimiter, 'admin') |
| 36 | + |
| 37 | + expect(limited).to.equal(false) |
| 38 | + expect(rateLimiter.hit).not.to.have.been.called |
| 39 | + }) |
| 40 | + |
| 41 | + it('returns true when login rate limit is exceeded', async () => { |
| 42 | + const rateLimiter = { hit: sinon.stub().resolves(true) } |
| 43 | + |
| 44 | + const limited = await isAdminRateLimited(makeRequest(), baseSettings as any, () => rateLimiter, 'login') |
| 45 | + |
| 46 | + expect(limited).to.equal(true) |
| 47 | + expect(rateLimiter.hit).to.have.been.calledOnceWithExactly('1.2.3.4:admin-login:900000', 1, { |
| 48 | + period: 900000, |
| 49 | + rate: 10, |
| 50 | + }) |
| 51 | + }) |
| 52 | + |
| 53 | + it('returns true when admin route rate limit is exceeded', async () => { |
| 54 | + const rateLimiter = { hit: sinon.stub().resolves(true) } |
| 55 | + |
| 56 | + const limited = await isAdminRateLimited(makeRequest(), baseSettings as any, () => rateLimiter, 'admin') |
| 57 | + |
| 58 | + expect(limited).to.equal(true) |
| 59 | + expect(rateLimiter.hit).to.have.been.calledOnceWithExactly('1.2.3.4:admin-admin:60000', 1, { |
| 60 | + period: 60000, |
| 61 | + rate: 30, |
| 62 | + }) |
| 63 | + }) |
| 64 | +}) |
0 commit comments