Node.js based forum software built for the modern web
refactor: one owner for db-backed rate limit counters (#14868)
palmoni5dfb22b7699ff
diff --git a/src/controllers/write/intents.js b/src/controllers/write/intents.jsindex ab4a8de694..1e067f541f 100644--- a/src/controllers/write/intents.js+++ b/src/controllers/write/intents.js@@ -1,7 +1,5 @@'use strict';-const db = require('../../database');-const Intents = module.exports;const activitypub = require('../../activitypub');@@ -9,17 +7,18 @@ const meta = require('../../meta');const helpers = require('../helpers');const clientIp = require('../../ip');+const ratelimit = require('../../ratelimit');const RATE_LIMIT_WINDOW = 5000; // 5 secondsasync function checkRateLimit(ip) {- const key = `locks:intents:query:${ip}`;- const exists = await db.exists(key);- if (exists) {+ const withinLimit = await ratelimit.check(`locks:intents:query:${ip}`, {+ window: RATE_LIMIT_WINDOW,+ max: 1,+ });+ if (!withinLimit) {throw new Error('[[error:api.429]]');}- await db.set(key, '1');- await db.pexpire(key, RATE_LIMIT_WINDOW);}Intents.query = async (req, res, next) => {diff --git a/src/ratelimit.js b/src/ratelimit.jsnew file mode 100644index 0000000000..28fd126435--- /dev/null+++ b/src/ratelimit.js@@ -0,0 +1,17 @@+'use strict';++const db = require('./database');++const Ratelimit = module.exports;++Ratelimit.check = async function (key, { window, max }) {+ const count = await db.increment(key);+ if (count === 1) {+ await db.pexpire(key, window);+ }+ return count <= max;+};++Ratelimit.clear = async function (key) {+ await db.delete(key);+};diff --git a/src/routes/feeds.js b/src/routes/feeds.jsindex a4df06e561..287867164c 100644--- a/src/routes/feeds.js+++ b/src/routes/feeds.js@@ -14,10 +14,14 @@ const db = require('../database');const utils = require('../utils');const controllers404 = require('../controllers/404');const clientIp = require('../ip');+const ratelimit = require('../ratelimit');const routeHelpers = require('./helpers');const { terms } = controllerHelpers;+const RSS_TOKEN_RATE_LIMIT_WINDOW = 3600000; // one hour+const RSS_TOKEN_RATE_LIMIT_MAX = 5;+module.exports = function (app, middleware) {function handle404(req, res, next) {if (meta.config['feeds:disableRSS']) {@@ -448,11 +452,11 @@ async function getUidFromToken(req, res) {const queryUid = parseInt(req.query.uid, 10) || 0;const { token } = req.query;const rateLimitKey = getRssTokenRateLimitKey(req);- const count = await db.increment(rateLimitKey);- if (count === 1) {- await db.pexpire(rateLimitKey, 3600000);- }- if (count > 5 || queryUid <= 0 || !token) {+ const withinLimit = await ratelimit.check(rateLimitKey, {+ window: RSS_TOKEN_RATE_LIMIT_WINDOW,+ max: RSS_TOKEN_RATE_LIMIT_MAX,+ });+ if (!withinLimit || queryUid <= 0 || !token) {await controllerHelpers.notAllowed(req, res);return { uid: authUid, ok: false };}@@ -463,7 +467,7 @@ async function getUidFromToken(req, res) {return { uid: authUid, ok: false };}- await db.delete(rateLimitKey);+ await ratelimit.clear(rateLimitKey);req.uid = queryUid;req.loggedIn = queryUid > 0;return { uid: queryUid, ok: true };diff --git a/test/ratelimit.js b/test/ratelimit.jsnew file mode 100644index 0000000000..958a59ebe4--- /dev/null+++ b/test/ratelimit.js@@ -0,0 +1,40 @@+'use strict';+++const assert = require('assert');++const db = require('./mocks/databasemock');++const ratelimit = require('../src/ratelimit');++describe('ratelimit', () => {+ const key = 'test:ratelimit';++ afterEach(async () => {+ await db.delete(key);+ });++ it('should allow hits up to the maximum and refuse the next one', async () => {+ assert.strictEqual(await ratelimit.check(key, { window: 5000, max: 2 }), true);+ assert.strictEqual(await ratelimit.check(key, { window: 5000, max: 2 }), true);+ assert.strictEqual(await ratelimit.check(key, { window: 5000, max: 2 }), false);+ });++ it('should set the expiry on the first hit only', async () => {+ await ratelimit.check(key, { window: 5000, max: 5 });+ const ttl = await db.pttl(key);+ assert(ttl > 0 && ttl <= 5000);++ await ratelimit.check(key, { window: 60000, max: 5 });+ const nextTtl = await db.pttl(key);+ assert(nextTtl <= ttl);+ });++ it('should start over once cleared', async () => {+ await ratelimit.check(key, { window: 5000, max: 1 });+ assert.strictEqual(await ratelimit.check(key, { window: 5000, max: 1 }), false);++ await ratelimit.clear(key);+ assert.strictEqual(await ratelimit.check(key, { window: 5000, max: 1 }), true);+ });+});