-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add forgot password rate limiting #385
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,41 @@ | ||
| import { getClient } from "@/server/services/redis"; | ||
|
|
||
| export function getClientIp(req: Request): string { | ||
| const forwarded = req.headers.get("x-forwarded-for"); | ||
| return ( | ||
| (forwarded ? forwarded.split(",")[0].trim() : null) ?? | ||
| req.headers.get("x-real-ip") ?? | ||
| "unknown" | ||
| ); | ||
| } | ||
|
|
||
| const WINDOW_SECONDS = 15 * 60; // 15 minutes | ||
| const MAX_ATTEMPTS = 5; | ||
| const LOGIN_MAX_ATTEMPTS = 5; | ||
| const FORGOT_PASSWORD_MAX_ATTEMPTS = 5; | ||
|
|
||
| export async function checkLoginRateLimit(ip: string): Promise<boolean> { | ||
| async function checkRateLimit( | ||
| key: string, | ||
| maxAttempts: number, | ||
| ): Promise<boolean> { | ||
| const redis = getClient(); | ||
| const key = `rate_limit:login:${ip}`; | ||
| const results = await redis | ||
| .multi() | ||
| .incr(key) | ||
| .expire(key, WINDOW_SECONDS) | ||
| .exec(); | ||
| const count = results && results[0] ? (results[0][1] as number) : 0; | ||
| return count <= MAX_ATTEMPTS; | ||
| return count <= maxAttempts; | ||
| } | ||
|
|
||
| export async function checkLoginRateLimit(ip: string): Promise<boolean> { | ||
| return checkRateLimit(`rate_limit:login:${ip}`, LOGIN_MAX_ATTEMPTS); | ||
| } | ||
|
|
||
| export async function checkForgotPasswordRateLimit( | ||
| ip: string, | ||
| ): Promise<boolean> { | ||
| return checkRateLimit( | ||
| `rate_limit:forgot_password:${ip}`, | ||
| FORGOT_PASSWORD_MAX_ATTEMPTS, | ||
| ); | ||
| } |
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,67 @@ | ||
| import { beforeEach, describe, expect, test, vi } from "vitest"; | ||
|
|
||
| vi.mock("@/server/utils/ratelimit", () => ({ | ||
| checkForgotPasswordRateLimit: vi.fn(), | ||
| })); | ||
joaquimds marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| vi.mock("@/server/repositories/User", () => ({ | ||
| findUserByEmail: vi.fn(), | ||
| })); | ||
| vi.mock("@/server/services/mailer", () => ({ | ||
| sendEmail: vi.fn(), | ||
| })); | ||
| vi.mock("@/server/services/logger", () => ({ | ||
| default: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, | ||
| })); | ||
|
|
||
| import { findUserByEmail } from "@/server/repositories/User"; | ||
| import { authRouter } from "@/server/trpc/routers/auth"; | ||
| import { checkForgotPasswordRateLimit } from "@/server/utils/ratelimit"; | ||
|
|
||
| const mockCheckRateLimit = vi.mocked(checkForgotPasswordRateLimit); | ||
| const mockFindUserByEmail = vi.mocked(findUserByEmail); | ||
|
|
||
| function makeCaller(ip = "1.2.3.4") { | ||
| return authRouter.createCaller({ user: null, ip }); | ||
| } | ||
|
|
||
| describe("auth.forgotPassword", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| mockCheckRateLimit.mockResolvedValue(true); | ||
| mockFindUserByEmail.mockResolvedValue(undefined); | ||
| }); | ||
|
|
||
| describe("rate limiting", () => { | ||
| test("allows request when rate limit is not exceeded", async () => { | ||
| mockCheckRateLimit.mockResolvedValue(true); | ||
| const caller = makeCaller("1.2.3.4"); | ||
| await expect( | ||
| caller.forgotPassword({ email: "user@example.com" }), | ||
| ).resolves.toBe(true); | ||
| expect(mockCheckRateLimit).toHaveBeenCalledWith("1.2.3.4"); | ||
| }); | ||
|
|
||
| test("throws TOO_MANY_REQUESTS when rate limit is exceeded", async () => { | ||
| mockCheckRateLimit.mockResolvedValue(false); | ||
| const caller = makeCaller("1.2.3.4"); | ||
| await expect( | ||
| caller.forgotPassword({ email: "user@example.com" }), | ||
| ).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" }); | ||
| }); | ||
|
|
||
| test("passes the caller IP to the rate limiter", async () => { | ||
| const caller = makeCaller("9.8.7.6"); | ||
| await caller.forgotPassword({ email: "user@example.com" }); | ||
| expect(mockCheckRateLimit).toHaveBeenCalledWith("9.8.7.6"); | ||
| }); | ||
|
|
||
| test("does not look up user when rate limit is exceeded", async () => { | ||
| mockCheckRateLimit.mockResolvedValue(false); | ||
| const caller = makeCaller(); | ||
| await expect( | ||
| caller.forgotPassword({ email: "user@example.com" }), | ||
| ).rejects.toThrow(); | ||
| expect(mockFindUserByEmail).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Throwing
TRPCErrorwithcode: "TOO_MANY_REQUESTS"here will be treated like any other tRPC error by the API handler and (currently) gets logged at error level and sent to Sentry (seesrc/app/api/trpc/[trpc]/route.ts:16-51, whereACCEPTED_ERROR_CODESis empty). For rate-limiting, this can generate high-volume noise during normal throttling or attacks. Consider handling this case so it’s not captured/logged as an error (e.g., addTOO_MANY_REQUESTSto an accepted/ignored list, or adjust the handler/logging strategy for this error code).