-
Notifications
You must be signed in to change notification settings - Fork 3
Fix/otp attempts verification #1466
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
Draft
adriangohjw
wants to merge
8
commits into
develop
Choose a base branch
from
fix/otp-attempts-verification
base: develop
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.
Draft
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b4eb07f
feat: add attempts_by_ip column to otps table for per-IP tracking
adriangohjw 771f6e3
feat: implement per-IP OTP attempt tracking in UsersService
adriangohjw 3cd6eb9
feat: enhance OTP verification by including user IP tracking
adriangohjw b19d2fc
refactor: remove user IP validation from AuthRouter and UsersRouter, …
adriangohjw f44908c
test: add unit tests for OTP verification with per-IP tracking in Use…
adriangohjw c651aeb
feat: implement OTP request blocking for existing valid OTPs in Users…
adriangohjw b8c5c1b
fix: use > instead of >= when comparing attempts count
adriangohjw 9f90a78
chore: extract get user IP address as standalone function
dcshzj 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
13 changes: 13 additions & 0 deletions
13
src/database/migrations/20251017090000-add-attempts-by-ip-to-otps.js
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,13 @@ | ||
| /** @type {import('sequelize-cli').Migration} */ | ||
| module.exports = { | ||
| async up(queryInterface, Sequelize) { | ||
| await queryInterface.addColumn("otps", "attempts_by_ip", { | ||
| allowNull: false, | ||
| type: Sequelize.JSONB, | ||
| defaultValue: {}, | ||
| }) | ||
| }, | ||
| async down(queryInterface, Sequelize) { | ||
| await queryInterface.removeColumn("otps", "attempts_by_ip") | ||
| }, | ||
| } |
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 |
|---|---|---|
|
|
@@ -212,13 +212,40 @@ class UsersService { | |
|
|
||
| async sendEmailOtp(email: string) { | ||
| const normalizedEmail = email.toLowerCase() | ||
|
|
||
| // Check if there's already a valid OTP for this email | ||
| // This prevents creating new OTPs while a valid one exists, mitigating | ||
| // the attack vector where an attacker spam OTP requests | ||
| // to prevent the user from logging in | ||
| const existingOtp = await this.otpRepository.findOne({ | ||
| where: { | ||
| email: normalizedEmail, | ||
| hashedOtp: { | ||
| [Op.regexp]: "\\S+", // at least one non-whitespace character (i.e. is truthy!) | ||
| }, | ||
| }, | ||
| }) | ||
| if (existingOtp && existingOtp.expiresAt >= new Date()) { | ||
| logger.info({ | ||
| message: "OTP request blocked: valid OTP already exists", | ||
| meta: { | ||
| email: normalizedEmail, | ||
| expiresAt: existingOtp.expiresAt, | ||
| }, | ||
| }) | ||
| // Return silently to avoid revealing whether an OTP exists | ||
| // This maintains security by not leaking information about existing OTPs | ||
| return | ||
|
Comment on lines
+236
to
+238
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. issue: I don't think we are able to directly return here because it is possible that the user is requesting for the OTP to be resent if the email did not reach their inbox. Instead we should be able to resend the email with the same OTP. |
||
| } | ||
|
|
||
| const { otp, hashedOtp } = await this.otpService.generateLoginOtpWithHash() | ||
|
|
||
| // Reset attempts to login | ||
| await this.otpRepository.upsert({ | ||
| email: normalizedEmail, | ||
| hashedOtp, | ||
| attempts: 0, | ||
| attemptsByIp: {}, | ||
| expiresAt: this.getOtpExpiry(), | ||
| }) | ||
|
|
||
|
|
@@ -239,6 +266,7 @@ class UsersService { | |
| mobileNumber, | ||
| hashedOtp, | ||
| attempts: 0, | ||
| attemptsByIp: {}, | ||
| expiresAt: this.getOtpExpiry(), | ||
| }) | ||
|
|
||
|
|
@@ -271,10 +299,12 @@ class UsersService { | |
| otp, | ||
| findConditions, | ||
| findErrorMessage, | ||
| clientIp = "unknown", // default to 'unknown' bucket when IP missing to ensure users are not locked out | ||
| }: { | ||
| otp: string | undefined | ||
| findConditions: { email: string } | { mobileNumber: string } | ||
| findErrorMessage: string | ||
| clientIp?: string | ||
| }) { | ||
| if (!otp) { | ||
| return errAsync(new BadRequestError("Empty OTP provided")) | ||
|
|
@@ -316,17 +346,27 @@ class UsersService { | |
| ) | ||
| } | ||
|
|
||
| if (otpEntry.attempts >= MAX_NUM_OTP_ATTEMPTS) { | ||
| // GTA-80-009 WP2: Enforce per-IP attempts; | ||
| const attemptsByIp = otpEntry.attemptsByIp || {} | ||
| const attemptsForIp = attemptsByIp[clientIp] ?? 0 | ||
| if (attemptsForIp > MAX_NUM_OTP_ATTEMPTS) { | ||
| // should this delete the otpEntry as well? | ||
| return errAsync(new BadRequestError("Max number of attempts reached")) | ||
| } | ||
|
|
||
| // We must successfully be able to increment the otp record attempts before any processing, to prevent brute-force race condition | ||
| // Consult GTA-24-012 WP3 for details | ||
| // atomically increment attempts for this IP using JSONB concatenation guarded by current value | ||
| const newAttemptsForIp = attemptsForIp + 1 | ||
| const attemptsByIpUpdated = { ...(otpEntry.attemptsByIp || {}) } | ||
| attemptsByIpUpdated[clientIp] = newAttemptsForIp | ||
|
|
||
| return ResultAsync.fromPromise( | ||
| this.otpRepository.update( | ||
| { | ||
| // maintain legacy aggregate attempts for monitoring, but do not enforce with it | ||
| attempts: otpEntry.attempts + 1, | ||
| attemptsByIp: attemptsByIpUpdated, | ||
| }, | ||
| { | ||
| where: { | ||
|
|
@@ -377,21 +417,27 @@ class UsersService { | |
| /* eslint-enable @typescript-eslint/no-non-null-assertion */ | ||
| } | ||
|
|
||
| verifyEmailOtp(email: string, otp: string | undefined) { | ||
| verifyEmailOtp(email: string, otp: string | undefined, clientIp?: string) { | ||
| const normalizedEmail = email.toLowerCase() | ||
|
|
||
| return this.verifyOtp({ | ||
| otp, | ||
| findConditions: { email: normalizedEmail }, | ||
| findErrorMessage: "Error finding OTP entry when verifying email OTP", | ||
| clientIp, | ||
| }) | ||
| } | ||
|
|
||
| verifyMobileOtp(mobileNumber: string, otp: string | undefined) { | ||
| verifyMobileOtp( | ||
| mobileNumber: string, | ||
| otp: string | undefined, | ||
| clientIp?: string | ||
| ) { | ||
| return this.verifyOtp({ | ||
| otp, | ||
| findConditions: { mobileNumber }, | ||
| findErrorMessage: "Error finding OTP entry when verifying mobile OTP", | ||
| clientIp, | ||
| }) | ||
| } | ||
|
|
||
|
|
||
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,7 +1,9 @@ | ||
| import { ModelStatic } from "sequelize/types" | ||
| import { Sequelize } from "sequelize-typescript" | ||
|
|
||
| import { config } from "@root/config/config" | ||
| import { Otp, User, Whitelist } from "@root/database/models" | ||
| import { BadRequestError } from "@root/errors/BadRequestError" | ||
| import SmsClient from "@services/identity/SmsClient" | ||
| import TotpGenerator from "@services/identity/TotpGenerator" | ||
| import MailClient from "@services/utilServices/MailClient" | ||
|
|
@@ -39,8 +41,30 @@ const MockWhitelist = { | |
| findAll: jest.fn(), | ||
| } | ||
|
|
||
| let dbAttempts = 0 | ||
| let dbAttemptsByIp: Record<string, number> = {} | ||
|
|
||
| const futureDate = new Date(Date.now() + 60 * 60 * 1000) | ||
|
|
||
| const MockOtp = { | ||
| findOne: jest.fn(), | ||
| findOne: jest.fn().mockImplementation(() => | ||
| Promise.resolve({ | ||
| id: 1, | ||
| email: mockEmail, | ||
| hashedOtp: "hashed", | ||
| attempts: dbAttempts, | ||
| attemptsByIp: { ...dbAttemptsByIp }, | ||
| expiresAt: futureDate, | ||
| destroy: jest.fn(), | ||
| }) | ||
| ), | ||
| update: jest.fn().mockImplementation((values: any, options: any) => { | ||
| if (options?.where?.attempts !== dbAttempts) return Promise.resolve([0]) | ||
|
|
||
| dbAttempts = values.attempts | ||
| dbAttemptsByIp = { ...(values.attemptsByIp || {}) } | ||
| return Promise.resolve([1]) | ||
| }), | ||
| } | ||
|
|
||
| const UsersService = new _UsersService({ | ||
|
|
@@ -57,7 +81,11 @@ const mockEmail = "[email protected]" | |
| const mockGithubId = "sudowoodo" | ||
|
|
||
| describe("User Service", () => { | ||
| afterEach(() => jest.clearAllMocks()) | ||
| afterEach(() => { | ||
| jest.clearAllMocks() | ||
| dbAttempts = 0 | ||
| dbAttemptsByIp = {} | ||
| }) | ||
|
|
||
| it("should return the result of calling the findOne method by email on the db model", () => { | ||
| // Arrange | ||
|
|
@@ -74,6 +102,56 @@ describe("User Service", () => { | |
| }) | ||
| }) | ||
|
|
||
| describe("verifyOtp per-IP behavior", () => { | ||
| const maxAttempts = config.get("auth.maxNumOtpAttempts") | ||
| const wrongOtp = "000000" | ||
|
|
||
| it("increments attempts for provided IP and returns invalid until max", async () => { | ||
| (MockOtpService.verifyOtp as jest.Mock).mockResolvedValue(false) | ||
| const ip = "1.1.1.1" | ||
|
|
||
| for (let i = 1; i <= maxAttempts; i += 1) { | ||
| // eslint-disable-next-line no-await-in-loop | ||
| const result = await UsersService.verifyEmailOtp(mockEmail, wrongOtp, ip) | ||
| expect(result.isErr()).toBe(true) | ||
| const err = result._unsafeUnwrapErr() | ||
| expect(err).toBeInstanceOf(BadRequestError) | ||
| if (i < maxAttempts) { | ||
| expect((err as BadRequestError).message).toBe("OTP is not valid") | ||
| } else { | ||
| expect((err as BadRequestError).message).toBe( | ||
| "Max number of attempts reached" | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| expect(MockOtp.update).toHaveBeenCalled() | ||
| expect(dbAttemptsByIp[ip]).toBe(maxAttempts - 1) // last call rejected before increment | ||
| }) | ||
|
|
||
| it("uses 'unknown' bucket when clientIp is missing", async () => { | ||
| (MockOtpService.verifyOtp as jest.Mock).mockResolvedValue(false) | ||
|
|
||
| const result = await UsersService.verifyEmailOtp(mockEmail, wrongOtp) | ||
| expect(result.isErr()).toBe(true) | ||
| result._unsafeUnwrapErr() // ensure unwrap doesn't throw | ||
| expect(dbAttemptsByIp.unknown).toBe(1) | ||
| }) | ||
|
|
||
| it("tracks per-IP separately", async () => { | ||
| (MockOtpService.verifyOtp as jest.Mock).mockResolvedValue(false) | ||
| const ipA = "1.1.1.1" | ||
| const ipB = "2.2.2.2" | ||
|
|
||
| await UsersService.verifyEmailOtp(mockEmail, wrongOtp, ipA) | ||
| await UsersService.verifyEmailOtp(mockEmail, wrongOtp, ipA) | ||
| await UsersService.verifyEmailOtp(mockEmail, wrongOtp, ipB) | ||
|
|
||
| expect(dbAttemptsByIp[ipA]).toBe(2) | ||
| expect(dbAttemptsByIp[ipB]).toBe(1) | ||
| }) | ||
| }) | ||
|
|
||
| it("should return the result of calling the findOne method by githubId on the db model", () => { | ||
| // Arrange | ||
| const expected = "user1" | ||
|
|
||
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
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.
nit: this line is making an assumption about Cloudflare's existence which we know may not necessarily be true. Noting this down as a nit for us to follow up as a separate fix as part of the Cloudflare post-mortem action items.
FYI will extract this out into a common function and add a comment there for follow-up.
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.
Extracted in 9f90a78.