/** * The 2FA verify limit counts wrong codes only (1.17.1, IAWL idea 27: "a limiter that reserves a place before it * compares must not lock on reservations"). Through real HTTP requests against a running Payload with the 2FA * package: an account that logs in correctly six times in the window is not refused; wrong codes still lock; * an attempt still being checked answers "try again in a moment", not the long wait. * Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts). */ import type { Payload } from 'payload' import { payloadTotp } from '@clocklimited/payload-2fa' import { lexicalEditor } from '@payloadcms/richtext-lexical' import { getPayload } from 'payload' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' import { totp } from './http/totp.js' vi.mock('server-only', () => ({})) vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) const SECRET = 'JBSWY3DPEHPK3PXP' const PASSWORD = 'a-long-test-password-1' let server: TestServer let payload: Payload const post = (p: string, body: unknown, cookie = '') => fetch(`${server.url}/api${p}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, method: 'POST' }) const passwordStep = async (email: string) => cookiesOf(await post('/users/login', { email, password: PASSWORD })).join('; ') /** A code that is surely wrong now (not the current one, nor one step either side). */ const wrongCode = () => { const near = new Set([-30_000, 0, 30_000].map((d) => totp(SECRET, Date.now() + d))) let n = 123456 while (near.has(String(n))) {n++} return String(n) } beforeAll(async () => { clearVerifyLimits() const config = buildTestConfig({ admin: { user: 'users' }, collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-verify-limit-media' } }], db: testDatabase('verifylimit'), editor: lexicalEditor(), plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp } })], secret: 'integration-test-secret-0123456789', telemetry: false, }) payload = await getPayload({ config }) server = await startPayloadServer(config) for (const email of ['office@example.com', 'guess@example.com', 'burst@example.com']) { await payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['editor'], totpSecret: SECRET } as never }) } }, 120_000) afterAll(async () => { await server?.close() await payload?.destroy?.() }) describe('the 2FA verify limit counts wrong codes, not right ones', () => { test('an account that logs in correctly seven times in the window is never refused', async () => { const answers: unknown[] = [] for (let i = 0; i < 7; i++) { const res = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('office@example.com')) answers.push([res.status, ((await res.json()) as { ok?: boolean }).ok]) } expect(answers).toEqual(Array.from({ length: 7 }, () => [200, true])) }) test('six correct codes at the same moment: the account is not locked, a retry gets in', async () => { const cookies: string[] = [] for (let i = 0; i < 6; i++) {cookies.push(await passwordStep('burst@example.com'))} const statuses = await Promise.all(cookies.map(async (cookie) => (await post('/verify-totp', { token: totp(SECRET) }, cookie)).status)) // all in, or one told to try again in a moment — never the long wait expect(statuses.filter((s) => s === 200).length).toBeGreaterThanOrEqual(5) const retry = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('burst@example.com')) expect([retry.status, ((await retry.json()) as { ok?: boolean }).ok]).toEqual([200, true]) }) test('five wrong codes still lock the account, also for the right code; a right code does not undo wrong ones', async () => { const cookie = await passwordStep('guess@example.com') expect(((await (await post('/verify-totp', { token: totp(SECRET) }, cookie)).json()) as { ok?: boolean }).ok).toBe(true) for (let i = 0; i < 5; i++) { const res = await post('/verify-totp', { token: wrongCode() }, await passwordStep('guess@example.com')) expect([res.status, ((await res.json()) as { ok?: boolean }).ok]).toEqual([200, false]) } const locked = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('guess@example.com')) expect(locked.status).toBe(429) expect(Number(locked.headers.get('retry-after'))).toBeGreaterThan(60) expect(((await locked.json()) as { message: string }).message).toMatch(/Too many codes/) // the stored count is the five wrong codes: the right one before them and the refused one gave their places back const user = (await payload.find({ collection: 'users' as never, overrideAccess: true, where: { email: { equals: 'guess@example.com' } } })).docs[0] as { id: number | string } expect(await payload.kv.get(verifyLimitKey('users', String(user.id)))).toMatchObject({ count: 5 }) }) }) describe('buildVerifyLimit: places, settle and "try again"', () => { const req = (id = 1) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never test('attempts still being checked fill the limit with "try again in a moment"; settled right codes free it', async () => { clearVerifyLimits() const limit = buildVerifyLimit('users', { store: 'memory' }) const running = Array.from({ length: 5 }, () => req()) for (const r of running) {expect(await limit(r)).toBeNull()} const busy = (await limit(req()))! expect(busy.status).toBe(429) expect(busy.headers.get('retry-after')).toBe('2') expect(((await busy.json()) as { message: string }).message).toMatch(/being checked right now/) for (const r of running) {await limit.settle(r, true)} const next = req() expect(await limit(next)).toBeNull() await limit.settle(next, true) }) test('wrong codes stay counted; the sixth attempt gets the long wait', async () => { clearVerifyLimits() const limit = buildVerifyLimit('users', { store: 'memory' }) for (let i = 0; i < 5; i++) { const r = req() expect(await limit(r)).toBeNull() await limit.settle(r, false) } const refused = (await limit(req()))! expect(refused.status).toBe(429) expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(60) expect(((await refused.json()) as { message: string }).message).toMatch(/Too many codes/) }) test('settle for a request the limit never saw, or twice, changes nothing', async () => { clearVerifyLimits() const limit = buildVerifyLimit('users', { max: 1, store: 'memory' }) await limit.settle(req(), true) const r = req() expect(await limit(r)).toBeNull() await limit.settle(r, false) await limit.settle(r, true) // already settled: the wrong code stays counted expect((await limit(req()))?.status).toBe(429) }) })