-
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 all 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
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
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
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.
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.