/** * 1.51.17 security fix: nothing public says whether an account exists. Forgot-password answers * the same for every email (before doing any per-account work), and sign-in with an unknown email * answers exactly like a wrong password. */ const mockDb = { user: { findUnique: jest.fn(), findFirst: jest.fn(), update: jest.fn() }, passwordReset: { updateMany: jest.fn(), create: jest.fn() }, }; jest.mock('../src/config/db', () => mockDb); const mockCompare = jest.fn(async () => false); const mockNeedsRehash = jest.fn(() => false); jest.mock('../src/config/auth', () => ({ comparePassword: (...a: unknown[]) => (mockCompare as jest.Mock)(...a), hashPassword: async () => 'stand-in-hash', generateToken: () => 't', needsRehash: (...a: unknown[]) => (mockNeedsRehash as jest.Mock)(...a) })); const mockSendMail = jest.fn(async () => undefined); jest.mock('../src/utils/email', () => ({ sendMail: (...a: unknown[]) => (mockSendMail as jest.Mock)(...a), buildPasswordResetEmail: () => ({ html: '', text: 'reset' }) })); jest.mock('../src/utils/notify', () => ({ waText: async () => undefined })); jest.mock('../src/utils/securityEvents', () => ({ logSecurityEvent: async () => undefined, getRecentSecurityEvents: async () => [] })); jest.mock('../src/utils/whatsapp', () => ({ normalizeZAPhone: () => null, isValidZAPhone: () => false })); import { logIn } from '../src/services/auth'; import { ServiceError } from '../src/services/errors'; // eslint-disable-next-line @typescript-eslint/no-require-imports const { requestPasswordReset } = require('../src/controllers/userController'); type Answer = { status: number; body: unknown }; function call(handler: (req: unknown, res: unknown) => Promise, body: object): Promise { return new Promise(resolve => { let status = 200; const res = { statusCode: 200, status(n: number) { status = n; this.statusCode = n; return this; }, json(b: unknown) { resolve({ status, body: b }); return this; }, }; handler({ body, headers: {}, ip: '127.0.0.1' }, res); }); } const realUser = { id: 'u1', name: 'Thandi', email: 'thandi@example.org', isActive: true, password: 'real-hash', failedAttempts: 0, lockUntil: null, role: 'user' }; beforeEach(() => jest.clearAllMocks()); describe('forgot password', () => { test('answers the same, with the same status, for an email with and without an account', async () => { mockDb.user.findUnique.mockResolvedValueOnce(null); const unknown = await call(requestPasswordReset, { email: 'nobody@example.org' }); mockDb.user.findUnique.mockResolvedValueOnce(realUser); const known = await call(requestPasswordReset, { email: realUser.email }); expect(unknown).toEqual(known); expect(known.status).toBe(200); }); test('only a real account gets a link, made after the answer is sent', async () => { mockDb.user.findUnique.mockResolvedValueOnce(null); await call(requestPasswordReset, { email: 'nobody@example.org' }); await new Promise(r => setImmediate(r)); expect(mockDb.passwordReset.create).not.toHaveBeenCalled(); expect(mockSendMail).not.toHaveBeenCalled(); mockDb.user.findUnique.mockResolvedValueOnce(realUser); const answered = call(requestPasswordReset, { email: realUser.email }); await answered; await new Promise(r => setImmediate(r)); expect(mockDb.passwordReset.create).toHaveBeenCalledTimes(1); expect(mockSendMail).toHaveBeenCalledWith(expect.objectContaining({ to: realUser.email })); }); }); describe('sign-in', () => { const failure = async (p: Promise) => { try { await p; } catch (e) { return e as ServiceError; } throw new Error('expected a refusal'); }; test('an unknown email is refused exactly like a wrong password', async () => { mockDb.user.findFirst.mockResolvedValueOnce(null); const unknown = await failure(logIn({ identifier: 'nobody@example.org', password: 'x' }, { ip: '1', userAgent: 'jest' })); mockDb.user.findFirst.mockResolvedValueOnce(realUser); const wrong = await failure(logIn({ identifier: realUser.email, password: 'x' }, { ip: '1', userAgent: 'jest' })); expect({ message: unknown.message, status: unknown.statusCode, v1: unknown.v1Status }).toEqual({ message: wrong.message, status: wrong.statusCode, v1: wrong.v1Status }); }); test('an unknown email still does a password check, so it takes as long', async () => { mockDb.user.findFirst.mockResolvedValueOnce(null); await failure(logIn({ identifier: 'nobody@example.org', password: 'guess' }, { ip: '1', userAgent: 'jest' })); expect(mockCompare).toHaveBeenCalledWith('guess', 'stand-in-hash'); }); }); describe('password re-hashing (2.0)', () => { // Stop logIn at its first save, to see what it saves. const firstSave = () => new Promise>(resolve => { mockDb.user.update.mockImplementationOnce(async (args: { data: Record }) => { resolve(args.data); throw new Error('stop'); }); }); test('a right password on an old hash saves a new hash', async () => { mockDb.user.findFirst.mockResolvedValueOnce({ ...realUser, password: '$2a$10$old' }); mockCompare.mockResolvedValueOnce(true as never); mockNeedsRehash.mockReturnValueOnce(true); const saved = firstSave(); await logIn({ identifier: realUser.email, password: 'right' }, { ip: '127.0.0.1', userAgent: 'test' } as never).catch(() => undefined); expect(await saved).toMatchObject({ failedAttempts: 0, password: 'stand-in-hash' }); }); test('a current hash is left as it is', async () => { mockDb.user.findFirst.mockResolvedValueOnce(realUser); mockCompare.mockResolvedValueOnce(true as never); const saved = firstSave(); await logIn({ identifier: realUser.email, password: 'right' }, { ip: '127.0.0.1', userAgent: 'test' } as never).catch(() => undefined); expect(await saved).not.toHaveProperty('password'); }); });