overleaf/services/web/app/coffee/infrastructure/RateLimiter.coffee
Simon Detheridge 64f69529e0 Merge pull request #1406 from sharelatex/spd-more-rate-limits
Add additional rate limits to prevent resource-exhaustion attacks

GitOrigin-RevId: 428cf8a16e062267dd92e7fba73ef5c192a8e668
2019-01-18 10:37:18 +00:00

29 lines
990 B
CoffeeScript

settings = require("settings-sharelatex")
Metrics = require('metrics-sharelatex')
RedisWrapper = require('./RedisWrapper')
rclient = RedisWrapper.client('ratelimiter')
RollingRateLimiter = require('rolling-rate-limiter')
module.exports = RateLimiter =
addCount: (opts, callback = (err, shouldProcess)->)->
namespace = "RateLimit:#{opts.endpointName}:"
k = "{#{opts.subjectName}}"
limiter = RollingRateLimiter({
redis: rclient,
namespace: namespace,
interval: opts.timeInterval * 1000,
maxInInterval: opts.throttle
})
limiter k, (err, timeLeft, actionsLeft) ->
if err?
return callback(err)
allowed = timeLeft == 0
Metrics.inc "rate-limit-hit.#{opts.endpointName}", 1, {path: opts.endpointName} unless allowed
callback(null, allowed)
clearRateLimit: (endpointName, subject, callback) ->
# same as the key which will be built by RollingRateLimiter (namespace+k)
keyName = "RateLimit:#{endpointName}:{#{subject}}"
rclient.del keyName, callback