Browse Source

generate envVarDic once

yuken 3 years ago
parent
commit
0009f09f70

+ 3 - 12
packages/app/src/server/middlewares/api-rate-limiter.ts

@@ -23,22 +23,13 @@ const consumePoints = async(rateLimiter: RateLimiterMemory, key: string, points:
     });
 };
 
-module.exports = (rateLimiter: RateLimiterMemory, defaultPoints: number) => {
+module.exports = (rateLimiter: RateLimiterMemory, defaultPoints: number, envVarDic: {[key: string]: string}) => {
 
   return async(req: Request, res: Response, next: NextFunction) => {
 
-    // e.g. /_api/v3/page/info?pageId=628c64f2b78c8d7e084ee979 => /_api/v3/page/info
-    const endpoint = req.url.replace(/\?.*$/, '');
+    const endpoint = req.path;
     const key = req.ip + req.url;
 
-    const envVarDic = process.env;
-
-    // pick up API_RATE_LIMIT_*_ENDPOINT from ENV
-    const apiRateEndpointKeys = Object.keys(envVarDic).filter((key) => {
-      const endpointRegExp = /^API_RATE_LIMIT_.*_ENDPOINT/;
-      return endpointRegExp.test(key);
-    });
-
     const matchedEndpointKeys = apiRateEndpointKeys.filter((key) => {
       return envVarDic[key] === endpoint;
     });
@@ -48,7 +39,7 @@ module.exports = (rateLimiter: RateLimiterMemory, defaultPoints: number) => {
       return;
     }
 
-    const customizedConsumePoints = getCustomApiRateLimit(matchedEndpointKeys, req.method);
+    const customizedConsumePoints = getCustomApiRateLimit(matchedEndpointKeys, req.method, envVarDic);
 
     await consumePoints(rateLimiter, key, customizedConsumePoints ?? defaultPoints, next);
     return;

+ 10 - 4
packages/app/src/server/routes/index.js

@@ -9,6 +9,7 @@ import * as registerFormValidator from '../middlewares/register-form-validator';
 import {
   generateUnavailableWhenMaintenanceModeMiddleware, generateUnavailableWhenMaintenanceModeMiddlewareForApi,
 } from '../middlewares/unavailable-when-maintenance-mode';
+import generateEnvVarDicForApiRateLimiter from '../util/generateEnvVarDicForApiRateLimiter';
 
 
 import * as allInAppNotifications from './all-in-app-notifications';
@@ -19,13 +20,18 @@ import * as userActivation from './user-activation';
 const multer = require('multer');
 const autoReap = require('multer-autoreap');
 
+const defaultMaxPoints = 100;
+const defaultConsumePoints = 10;
+const defaultDuration = 1;
 const opts = {
-  points: 100, // set default value
-  duration: 1, // set default value
+  points: defaultMaxPoints, // set default value
+  duration: defaultDuration, // set default value
 };
-
 const rateLimiter = new RateLimiterMemory(opts);
 
+// generate EnvVarDic For
+const envVarDicForApiRateLimiter = generateEnvVarDicForApiRateLimiter();
+
 autoReap.options.reapOnError = true; // continue reaping the file even if an error occurs
 
 module.exports = function(crowi, app) {
@@ -39,7 +45,7 @@ module.exports = function(crowi, app) {
   const certifySharedFile = require('../middlewares/certify-shared-file')(crowi);
   const csrf = require('../middlewares/csrf')(crowi);
   const injectUserUISettings = require('../middlewares/inject-user-ui-settings-to-localvars')();
-  const apiRateLimiter = require('../middlewares/api-rate-limiter')(rateLimiter, 10);
+  const apiRateLimiter = require('../middlewares/api-rate-limiter')(rateLimiter, defaultConsumePoints, envVarDicForApiRateLimiter);
 
   const uploads = multer({ dest: `${crowi.tmpDir}uploads` });
   const page = require('./page')(crowi, app);

+ 20 - 0
packages/app/src/server/util/generateEnvVarDicForApiRateLimiter.ts

@@ -0,0 +1,20 @@
+const generateEnvVarDicForApiRateLimiter = (): {[key: string]: string} => {
+  const envVarDic = process.env;
+
+  // pick up API_RATE_LIMIT_* from ENV
+  const apiRateEndpointKeys = Object.keys(envVarDic).filter((key) => {
+    const endpointRegExp = /^API_RATE_LIMIT_.*/;
+    return endpointRegExp.test(key);
+  });
+
+  let apiRateEndpointDic;
+  apiRateEndpointKeys.forEach((key) => {
+    apiRateEndpointDic[key] = envVarDic[key];
+  });
+
+  // default setting e.g. healthchack
+
+  return apiRateEndpointDic;
+};
+
+export default generateEnvVarDicForApiRateLimiter;

+ 1 - 3
packages/app/src/server/util/getCustomApiRateLimit.ts

@@ -1,4 +1,4 @@
-const getCustomApiRateLimit = (matchedEndpointKeys: string[], method: string): number | null => {
+const getCustomApiRateLimit = (matchedEndpointKeys: string[], method: string, envVarDic: {[key: string]: string}): number | null => {
 
   let prioritizedTarget: [string, string] | null = null; // priprity and keyword
   matchedEndpointKeys.forEach((key) => {
@@ -14,8 +14,6 @@ const getCustomApiRateLimit = (matchedEndpointKeys: string[], method: string): n
     return null;
   }
 
-  const envVarDic = process.env;
-
   const targetMethodsKey = `API_RATE_LIMIT_${prioritizedTarget[0]}_${prioritizedTarget[1]}_METHODS`;
   const targetConsumePointsKey = `API_RATE_LIMIT_${prioritizedTarget[0]}_${prioritizedTarget[1]}_CONSUME_POINTS`;