-
Notifications
You must be signed in to change notification settings - Fork 26
[#155244960] add rate limiter #585
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
Open
gunzip
wants to merge
13
commits into
master
Choose a base branch
from
155244960-rate-limit
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
b96597d
[#155244960] add rate limiter
gunzip 20f4311
fix tests
gunzip c6c0ac2
fix tests
gunzip 7d986aa
Update src/utils/middleware/rateLimiter.ts
gunzip 4072eca
adds tests
gunzip dc20a0f
expand rate limiter points
gunzip 3040a41
fixed env.examples
gunzip 7438f2c
Update src/utils/middleware/rateLimiter.ts
gunzip 8edca44
Merge branch 'master' into 155244960-rate-limit
gunzip cef4a66
Merge branch 'master' into 155244960-rate-limit
gunzip 025b028
Merge branch 'master' into 155244960-rate-limit
gunzip a39e438
Merge branch 'master' into 155244960-rate-limit
gunzip 7906d67
fix import order
gunzip File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import { RateLimiterMemory } from "rate-limiter-flexible"; | ||
| import mockReq from "../../../__mocks__/request"; | ||
| import mockRes from "../../../__mocks__/response"; | ||
| import { makeRateLimiterMiddleware } from "../rateLimiter"; | ||
|
|
||
| import * as rip from "request-ip"; | ||
| jest.spyOn(rip, "getClientIp").mockReturnValue("127.0.0.1"); | ||
|
|
||
| describe("Rate limiter middleware", () => { | ||
| it("should apply rate limit and return 429 if limit is reached", async () => { | ||
| const rateLimiterMiddleware = makeRateLimiterMiddleware( | ||
| new RateLimiterMemory({ | ||
| duration: 1, | ||
| points: 1 | ||
| }) | ||
| ); | ||
| const next = jest.fn(); | ||
| const aResponse = mockRes(); | ||
| await rateLimiterMiddleware(mockReq(), aResponse, next); | ||
| await rateLimiterMiddleware(mockReq(), aResponse, next); | ||
| expect(aResponse.set).toHaveBeenCalledWith("Retry-After", "1"); | ||
| expect(aResponse.status).toHaveBeenCalledWith(429); | ||
| }); | ||
| it("should NOT apply rate limit if limit is NOT reached", async () => { | ||
| const rateLimiterMiddleware = makeRateLimiterMiddleware( | ||
| new RateLimiterMemory({ | ||
| duration: 1, | ||
| points: 2 | ||
| }) | ||
| ); | ||
| const next = jest.fn(); | ||
| const aResponse = mockRes(); | ||
| await rateLimiterMiddleware(mockReq(), aResponse, next); | ||
| await rateLimiterMiddleware(mockReq(), aResponse, next); | ||
| expect(aResponse.set).toHaveBeenCalledWith("X-RateLimit-Remaining", "1"); | ||
| expect(aResponse.status).not.toHaveBeenCalledWith(429); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import { NextFunction, Request, Response } from "express"; | ||
| import { RateLimiterStoreAbstract } from "rate-limiter-flexible"; | ||
| import * as requestIp from "request-ip"; | ||
|
|
||
| import { ProblemJson } from "italia-ts-commons/lib/responses"; | ||
| import { log } from "../../utils/logger"; | ||
|
|
||
| export const makeRateLimiterMiddleware = ( | ||
| rateLimiter: RateLimiterStoreAbstract | ||
| ) => async (req: Request, res: Response, next: NextFunction) => { | ||
| const ip = requestIp.getClientIp(req); | ||
| try { | ||
| const rl = await rateLimiter.consume(ip); | ||
| res | ||
| .set("X-RateLimit-Remaining", rl.remainingPoints.toString()) | ||
| .set( | ||
| "X-RateLimit-Reset", | ||
| new Date(Date.now() + Number(rl.msBeforeNext)).toString() | ||
| ) | ||
| .set( | ||
| "X-RateLimit-Limit", | ||
| (Number(rl.remainingPoints) + Number(rl.consumedPoints)).toString() | ||
| ); | ||
| next(); | ||
| } catch (_) { | ||
| const retryAfter = Math.ceil(_.msBeforeNext / 1000); | ||
| const problem: ProblemJson = { | ||
| detail: "Rate limit reached", | ||
| status: 429, | ||
| title: "Too Many requests" | ||
| }; | ||
| log.warn("Rate limiter is blocking ip (%s)", ip); | ||
| res | ||
| .set("X-RateLimit-Remaining", _.remainingPoints.toString()) | ||
| .set( | ||
| "X-RateLimit-Reset", | ||
| new Date(Date.now() + Number(_.msBeforeNext)).toString() | ||
| ) | ||
| .set( | ||
| "X-RateLimit-Limit", | ||
| (Number(_.remainingPoints) + Number(_.consumedPoints)).toString() | ||
| ) | ||
| .set("Retry-After", retryAfter.toString()) | ||
| .status(429) | ||
| .json(problem); | ||
| } | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.