Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ntrnl 451 add rate limit utils and mw to node web template #24

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"cors": "^2.8.5",
"crypto": "^1.0.1",
"express": "^4.18.2",
"express-rate-limit": "^7.3.1",
"govuk-frontend": "^4.8.0",
"helmet": "^7.0.0",
"nunjucks": "^3.2.4"
Expand Down
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { configureCors } from './config/cors';
import { errorHandler, errorNotFound } from './controller/error.controller';

import { setNonce } from './middleware/nonce.middleware';
import { configureRateLimit } from './config/rate-limit';

const app = express();

Expand All @@ -22,6 +23,7 @@ app.use(cookieParser());
app.use(setNonce);
configureHelmet(app);
configureCors(app);
configureRateLimit(app);

const viewPath = path.join(__dirname, 'views');
configureNunjucks(app, viewPath);
Expand Down
13 changes: 13 additions & 0 deletions src/config/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { rateLimit } from 'express-rate-limit';
import express from 'express';
import { rateLimitHandler } from '../middleware/rateLimitHandler.middleware';

export const configureRateLimit = (app: express.Application) => {
app.use(rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
limit: 100, // Limit each IP to 100 requests per window
standardHeaders: 'draft-7', // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
handler: rateLimitHandler
}));
};
8 changes: 8 additions & 0 deletions src/middleware/rateLimitHandler.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { errorHandler } from '../controller/error.controller';
import { Request, Response, NextFunction } from 'express';

export const rateLimitHandler = (req: Request, res: Response, next: NextFunction) => {
const err = new Error('Too Many Requests');
res.statusCode = 429;
errorHandler(err, req, res, next);
};
10 changes: 10 additions & 0 deletions test/mock/data.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { jest, expect } from '@jest/globals';

import * as config from '../../src/config';
import express from 'express';

Expand Down Expand Up @@ -34,6 +36,14 @@ export const MOCK_HELMET_VALUE = {
}
};

export const MOCK_RATE_LIMIT_VALUE = {
windowMs: 15 * 60 * 1000,
limit: 100,
standardHeaders: 'draft-7',
legacyHeaders: false,
handler: expect.any(Function)
};

export const MOCK_EXPRESS_APP = {
use: jest.fn()
} as unknown as express.Application;
18 changes: 18 additions & 0 deletions test/mock/express.mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { NextFunction, Request, Response } from 'express';

export const mockRequest = (body = {}) => {
const req = {} as Request;
req.body = { ...body };
return req;
};

export const mockBadRequest = {} as Request;

export const mockResponse = () => {
const res = {} as Response;
res.render = jest.fn().mockReturnValue(res) as any;
res.redirect = jest.fn().mockReturnValue(res) as any;
return res;
};

export const mockNext = jest.fn() as NextFunction;
43 changes: 43 additions & 0 deletions test/unit/middleware/rateLimitHandler.middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
jest.mock('../../../src/controller/error.controller.ts');

import { describe, expect, test, jest, afterEach } from '@jest/globals';
import { Request, Response, NextFunction } from 'express';

import { errorHandler } from '../../../src/controller/error.controller';
import { rateLimitHandler } from '../../../src/middleware/rateLimitHandler.middleware';
import { mockRequest, mockResponse, mockNext } from '../../mock/express.mock';

const mockErrorHandler = errorHandler as jest.Mock;

describe('Rate Limit Handler test suites', () => {

let req: Request;
let res: Response;
let next: NextFunction;

beforeEach(() => {
req = mockRequest();
res = mockResponse();
next = mockNext;
});

afterEach(() => {
jest.resetAllMocks();
});

test('Should call errorHandler with err, req, res and next parameters', () => {

const err = new Error('Too Many Requests');
rateLimitHandler(req, res, next);
expect(mockErrorHandler).toHaveBeenCalledTimes(1);
expect(mockErrorHandler).toHaveBeenCalledWith(err, req, res, next);

});

test('Should attach statusCode property to res object, with 429 value', () => {

rateLimitHandler(req, res, next);
expect(res.statusCode).toBe(429);

});
});
Loading