fix: fix otp security issue and race condition
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
import { Repository } from 'typeorm';
|
||||
import { OTP } from '../entities/otp.entity';
|
||||
import { OtpService } from './otp.service';
|
||||
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
|
||||
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
|
||||
|
||||
describe('OTP verification', () => {
|
||||
let otp: OTP;
|
||||
let service: OtpService;
|
||||
let compare: jest.Mock<HashingProvider['compare']>;
|
||||
let save: jest.Mock<(record: OTP) => Promise<OTP>>;
|
||||
let findOne: jest.Mock<() => Promise<OTP | null>>;
|
||||
let transactionCommitted: boolean;
|
||||
|
||||
beforeEach(() => {
|
||||
otp = Object.assign(new OTP(), {
|
||||
id: 1,
|
||||
phone: '09121111111',
|
||||
code: 'hashed-code',
|
||||
used: false,
|
||||
failedAttempts: 0,
|
||||
expiresAt: new Date(Date.now() + 120_000),
|
||||
});
|
||||
compare = jest.fn<HashingProvider['compare']>().mockResolvedValue(true);
|
||||
save = jest
|
||||
.fn<(record: OTP) => Promise<OTP>>()
|
||||
.mockImplementation((record: OTP) => Promise.resolve(record));
|
||||
findOne = jest.fn<() => Promise<OTP | null>>().mockResolvedValue(otp);
|
||||
transactionCommitted = false;
|
||||
const repository = {
|
||||
manager: {
|
||||
transaction: async (
|
||||
callback: (manager: unknown) => Promise<unknown>,
|
||||
) => {
|
||||
const result = await callback({
|
||||
getRepository: () => ({ findOne, save }),
|
||||
});
|
||||
transactionCommitted = true;
|
||||
return result;
|
||||
},
|
||||
},
|
||||
} as unknown as Repository<OTP>;
|
||||
service = new OtpService(repository, {
|
||||
compare,
|
||||
} as unknown as HashingProvider);
|
||||
});
|
||||
|
||||
it('consumes the latest OTP under a database write lock and rejects reuse', async () => {
|
||||
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
|
||||
expect(findOne).toHaveBeenCalledWith({
|
||||
where: { phone: otp.phone },
|
||||
order: { createdAt: 'DESC', id: 'DESC' },
|
||||
lock: { mode: 'pessimistic_write' },
|
||||
});
|
||||
expect(otp.used).toBe(true);
|
||||
await expect(service.verifyOTP(otp.phone, '12345')).rejects.toThrow();
|
||||
expect(compare).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('commits ten wrong guesses and then rejects even the correct code', async () => {
|
||||
compare.mockResolvedValue(false);
|
||||
for (let attempt = 1; attempt <= 10; attempt++) {
|
||||
transactionCommitted = false;
|
||||
await expect(service.verifyOTP(otp.phone, 'wrong')).rejects.toThrow();
|
||||
expect(transactionCommitted).toBe(true);
|
||||
expect(otp.failedAttempts).toBe(attempt);
|
||||
}
|
||||
compare.mockResolvedValue(true);
|
||||
await expect(service.verifyOTP(otp.phone, '12345')).rejects.toThrow();
|
||||
expect(compare).toHaveBeenCalledTimes(10);
|
||||
expect(save).toHaveBeenCalledTimes(10);
|
||||
});
|
||||
|
||||
it('allows a correct code after nine wrong guesses', async () => {
|
||||
otp.failedAttempts = 9;
|
||||
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
|
||||
expect(otp.used).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects expired or missing codes without comparing hashes', async () => {
|
||||
otp.expiresAt = new Date(Date.now() - 1);
|
||||
await expect(service.verifyOTP(otp.phone, '12345')).rejects.toThrow();
|
||||
findOne.mockResolvedValue(null);
|
||||
await expect(service.verifyOTP(otp.phone, '12345')).rejects.toThrow();
|
||||
expect(compare).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a code that expires while its hash is being compared', async () => {
|
||||
compare.mockImplementation(() => {
|
||||
otp.expiresAt = new Date(Date.now() - 1);
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
await expect(service.verifyOTP(otp.phone, '12345')).rejects.toThrow();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { LessThan, MoreThanOrEqual, Repository } from 'typeorm';
|
||||
import { LessThan, Repository } from 'typeorm';
|
||||
import { randomInt } from 'crypto';
|
||||
import { OTP } from '../entities/otp.entity';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
@@ -9,6 +10,7 @@ import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
|
||||
|
||||
@Injectable()
|
||||
export class OtpService {
|
||||
private readonly maxFailedAttempts = 10;
|
||||
constructor(
|
||||
/**
|
||||
* Inject OTP Repository
|
||||
@@ -26,7 +28,7 @@ export class OtpService {
|
||||
* Generate OTP 5-digit code
|
||||
*/
|
||||
private generateOTPCode(): string {
|
||||
return Math.floor(10_000 + Math.random() * 90_000).toString();
|
||||
return randomInt(10_000, 100_000).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,7 +40,7 @@ export class OtpService {
|
||||
// OTP request Rate limit
|
||||
const lastOTP = await this.otpRepository.findOne({
|
||||
where: { phone },
|
||||
order: { createdAt: 'DESC' },
|
||||
order: { createdAt: 'DESC', id: 'DESC' },
|
||||
});
|
||||
|
||||
if (lastOTP && Date.now() - lastOTP.createdAt.getTime() < 60_000) {
|
||||
@@ -63,29 +65,51 @@ export class OtpService {
|
||||
* Verify OTP
|
||||
*/
|
||||
public async verifyOTP(phone: string, code: string): Promise<OTP> {
|
||||
let otp: OTP | null = null;
|
||||
let verifiedOTP: OTP | null;
|
||||
|
||||
try {
|
||||
otp = await this.otpRepository.findOne({
|
||||
where: { phone, used: false, expiresAt: MoreThanOrEqual(new Date()) },
|
||||
order: { createdAt: 'DESC' },
|
||||
});
|
||||
verifiedOTP = await this.otpRepository.manager.transaction(
|
||||
async (manager) => {
|
||||
const repository = manager.getRepository(OTP);
|
||||
const otp = await repository.findOne({
|
||||
where: { phone },
|
||||
order: { createdAt: 'DESC', id: 'DESC' },
|
||||
lock: { mode: 'pessimistic_write' },
|
||||
});
|
||||
|
||||
if (
|
||||
!otp ||
|
||||
otp.used ||
|
||||
otp.failedAttempts >= this.maxFailedAttempts ||
|
||||
otp.expiresAt.getTime() <= Date.now()
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const matches = await this.hashingProvider.compare(code, otp.code);
|
||||
|
||||
if (!matches) {
|
||||
otp.failedAttempts += 1;
|
||||
await repository.save(otp);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (otp.expiresAt.getTime() <= Date.now()) return null;
|
||||
|
||||
otp.used = true;
|
||||
await repository.save(otp);
|
||||
return otp;
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
throw new AppTimeoutException(err);
|
||||
}
|
||||
|
||||
if (!otp) throw new UnauthorizedException('auth.errors.invalidOTP');
|
||||
|
||||
const isOTPCorrect = await this.hashingProvider.compare(code, otp.code);
|
||||
|
||||
if (!isOTPCorrect) {
|
||||
if (!verifiedOTP) {
|
||||
throw new UnauthorizedException('auth.errors.invalidOTP');
|
||||
}
|
||||
|
||||
otp.used = true;
|
||||
await this.otpRepository.save(otp);
|
||||
|
||||
return otp;
|
||||
return verifiedOTP;
|
||||
}
|
||||
|
||||
@Cron(CronExpression.EVERY_10_MINUTES)
|
||||
|
||||
Reference in New Issue
Block a user