test: message/event rate limiting

This commit is contained in:
Ricardo Arturo Cabral Mejía
2022-11-15 15:02:12 -05:00
parent 760cb387bf
commit b36b62520e
22 changed files with 502 additions and 50 deletions

View File

@@ -72,6 +72,26 @@ describe('SettingsStatic', () => {
maxPositiveDelta: 900, // +15 min
maxNegativeDelta: 0, // disabled
},
'rateLimits': [
{
'kinds': [[0, 5], 7, [40, 49], [10000, 19999], [30000, 39999]],
'period': 60000,
'rate': 60,
},
{
'kinds': [[20000, 29999]],
'period': 60000,
'rate': 600,
},
{
'period': 3600000,
'rate': 3600,
},
{
'period': 86400000,
'rate': 86400,
},
],
},
client: {
subscription: {
@@ -80,9 +100,20 @@ describe('SettingsStatic', () => {
},
},
message: {
dailyRate: 86400,
hourlyRate: 3600,
minutelyRate: 240,
'rateLimits': [
{
'period': 60000,
'rate': 600,
},
{
'period': 3600000,
'rate': 3600,
},
{
'period': 86400000,
'rate': 86400,
},
],
ipWhitelist: [
'::1',
'::ffff:10.10.10.1',

View File

@@ -0,0 +1,64 @@
import { expect } from 'chai'
import Sinon from 'sinon'
import { ICacheAdapter } from '../../../src/@types/adapters'
import { IRateLimiter } from '../../../src/@types/utils'
import { SlidingWindowRateLimiter } from '../../../src/utils/sliding-window-rate-limiter'
describe('SlidingWindowRateLimiter', () => {
let clock: Sinon.SinonFakeTimers
let cache: ICacheAdapter
let rateLimiter: IRateLimiter
let removeRangeByScoreFromSortedSetStub: Sinon.SinonStub
let addToSortedSetStub: Sinon.SinonStub
let getRangeFromSortedSetStub: Sinon.SinonStub
let setKeyExpiryStub: Sinon.SinonStub
let sandbox: Sinon.SinonSandbox
beforeEach(() => {
sandbox = Sinon.createSandbox()
clock = sandbox.useFakeTimers(1665546189000)
removeRangeByScoreFromSortedSetStub = sandbox.stub()
addToSortedSetStub = sandbox.stub()
getRangeFromSortedSetStub = sandbox.stub()
setKeyExpiryStub = sandbox.stub()
cache = {
removeRangeByScoreFromSortedSet: removeRangeByScoreFromSortedSetStub,
addToSortedSet: addToSortedSetStub,
getRangeFromSortedSet: getRangeFromSortedSetStub,
setKeyExpiry: setKeyExpiryStub,
}
rateLimiter = new SlidingWindowRateLimiter(cache)
})
afterEach(() => {
clock.restore()
sandbox.restore()
})
it('returns true if rate limited', async () => {
const now = Date.now()
getRangeFromSortedSetStub.resolves([
`${now}:6`,
`${now}:4`,
`${now}:1`,
])
const actualResult = await rateLimiter.hit('key', 1, { period: 60000, rate: 10 })
expect(actualResult).to.be.true
})
it('returns false if not rate limited',async () => {
const now = Date.now()
getRangeFromSortedSetStub.resolves([
`${now}:10`,
])
const actualResult = await rateLimiter.hit('key', 1, { period: 60000, rate: 10 })
expect(actualResult).to.be.false
})
})