The verify limit took a place for every attempt and kept it, so the sixth
correct login of one account within 10 minutes was refused (IAWL idea 27).
Now an attempt takes its place before the compare (a parallel burst still
cannot slip under the limit), a right code gives it back, an attempt refused
without a compare gives it back at once, and a new attempt held out only by
attempts still being checked gets 429 + Retry-After: 2 "try again in a
moment". buildVerifyLimit returns limit.settle(req, correct); the plugin's
guard calls it with the package's answer. No schema change: payload-kv keeps
{ count, resetAt }.
Docs: the exempt example keyed on e-mail, which every account may change
itself (shown over REST and GraphQL): now an admin-only checkbox, with a test.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
144 lines
7.3 KiB
TypeScript
144 lines
7.3 KiB
TypeScript
/**
|
|
* 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 ['[email protected]', '[email protected]', '[email protected]']) {
|
|
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('[email protected]'))
|
|
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('[email protected]'))}
|
|
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('[email protected]'))
|
|
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('[email protected]')
|
|
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('[email protected]'))
|
|
expect([res.status, ((await res.json()) as { ok?: boolean }).ok]).toEqual([200, false])
|
|
}
|
|
const locked = await post('/verify-totp', { token: totp(SECRET) }, await passwordStep('[email protected]'))
|
|
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: '[email protected]' } } })).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)
|
|
})
|
|
})
|