forked from salesforce/refocus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrateLimit.js
97 lines (86 loc) · 3.01 KB
/
rateLimit.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or
* https://opensource.org/licenses/BSD-3-Clause
*/
/**
* ./rateLimit.js
*
* Rate limiting setup
*/
const conf = require('./config');
const activityLogUtil = require('./utils/activityLog');
const featureToggles = require('feature-toggles');
const limiterRedisClient = require('./cache/redisCache').client.limiter;
const Limiter = require('ratelimiter');
const Promise = require('bluebird');
Limiter.prototype.getAsync = Promise.promisify(Limiter.prototype.get);
module.exports = function (req, res, next) {
if (req.headers.IsAdmin) return next();
const limiterConfig1 = {
db: limiterRedisClient,
max: conf.expressLimiterTotal,
duration: conf.expressLimiterExpire,
};
const limiterConfig2 = {
db: limiterRedisClient,
max: conf.expressLimiterTotal2,
duration: conf.expressLimiterExpire2,
};
const lookupVals = [];
const lookups = conf.expressLimiterLookup;
lookups.forEach((lookupPath) => {
const lookupArr = lookupPath.split('.');
const lookupVal = lookupArr.reduce((prev, cur) => prev ? prev[cur] : null, req);
if (lookupVal) lookupVals.push(lookupVal);
});
const id = lookupVals.join('_');
if (id) {
limiterConfig1.id = `1__${id}`;
limiterConfig2.id = `2__${id}`;
}
// The order matters. The second one overwrites the limit headers.
Promise.resolve()
.then(() => applyLimits(limiterConfig2))
.then(() => applyLimits(limiterConfig1))
.then(next)
.catch(next);
function applyLimits(config) {
if (!config.max || !config.duration || !config.id) {
return Promise.resolve();
} else {
return new Limiter(config).getAsync()
.then((limit) => {
res.set('X-RateLimit-Limit', limit.total);
res.set('X-RateLimit-Remaining', limit.remaining - 1);
res.set('X-RateLimit-Reset', limit.reset);
if (limit.remaining === 0) {
res.set('X-RateLimit-Remaining', 0);
var after = limit.reset - (Date.now() / 1000) | 0;
res.set('Retry-After', after);
if (req && featureToggles.isFeatureEnabled('enableLimiterActivityLogs')) {
const logObject = {
activity: 'limiter',
ipAddress: activityLogUtil.getIPAddrFromReq(req),
limit: `${config.max}/${config.duration}`,
method: req.method,
requestBytes: JSON.stringify(req.body).length,
responseBytes: 0,
token: req.headers.TokenName,
totalTime: `${Date.now() - req.timestamp}ms`,
uri: req.url,
user: req.headers.UserName,
};
// Add "request_id" if available
if (req.request_id) logObject.request_id = req.request_id;
activityLogUtil.printActivityLogString(logObject, 'limiter');
}
res.status(429).end();
return Promise.reject();
}
});
}
}
};