2FA verify limit: a right code gives its place back; exempt by an admin-only field, not e-mail (docs)
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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e821d52d19
commit
91770ec17f
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* The documented way to exempt a service account from 2FA setup (security.md "Decide `exempt` from a field only an
|
||||
* administrator can write"), checked through real HTTP requests: an editor can rename itself to any e-mail, so an
|
||||
* e-mail list is no boundary; an admin-only checkbox is — the editor's own save leaves it as it is (REST and GraphQL).
|
||||
* 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 { adminOnlyField } from '../src/index.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
|
||||
let editorId: number | string
|
||||
let cookie: string
|
||||
|
||||
const call = (p: string, init: RequestInit = {}) =>
|
||||
fetch(`${server.url}/api${p}`, { ...init, headers: { 'content-type': 'application/json', cookie, ...(init.headers as Record<string, string>) } })
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [{ name: 'serviceAccount', type: 'checkbox', access: { create: adminOnlyField, update: adminOnlyField }, defaultValue: false }] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-exempt-media' } },
|
||||
],
|
||||
db: testDatabase('exemptfield'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp, requireSetup: { exempt: ({ user }) => user.serviceAccount === true } },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
const editor = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: SECRET } as never })
|
||||
editorId = (editor as { id: number | string }).id
|
||||
const login = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
const first = cookiesOf(login)
|
||||
cookie = first.join('; ')
|
||||
const verify = await call('/verify-totp', { body: JSON.stringify({ token: totp(SECRET) }), method: 'POST' })
|
||||
expect(((await verify.json()) as { ok?: boolean }).ok).toBe(true)
|
||||
cookie = [...first, ...cookiesOf(verify)].join('; ')
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
describe('exempt from 2FA setup: by an admin-only field, not by e-mail', () => {
|
||||
test('an editor cannot set the field on itself (REST and GraphQL); the value stays false', async () => {
|
||||
const rest = await call(`/users/${editorId}`, { body: JSON.stringify({ serviceAccount: true }), method: 'PATCH' })
|
||||
expect(rest.status).toBe(200)
|
||||
await call('/graphql', { body: JSON.stringify({ query: `mutation { updateUser(id: ${JSON.stringify(editorId)}, data: { serviceAccount: true }) { id } }` }), method: 'POST' })
|
||||
const stored = (await payload.findByID({ id: editorId, collection: 'users' as never, overrideAccess: true })) as { serviceAccount?: boolean }
|
||||
expect(stored.serviceAccount).toBe(false)
|
||||
})
|
||||
|
||||
test('…while the same editor can change its own e-mail to anything: an e-mail list is no boundary', async () => {
|
||||
const res = await call(`/users/${editorId}`, { body: JSON.stringify({ email: '[email protected]' }), method: 'PATCH' })
|
||||
expect(res.status).toBe(200)
|
||||
const stored = (await payload.findByID({ id: editorId, collection: 'users' as never, overrideAccess: true })) as { email: string }
|
||||
expect(stored.email).toBe('[email protected]')
|
||||
})
|
||||
})
|
||||
@@ -391,7 +391,7 @@ describe('stored names', () => {
|
||||
expect(await limit(req())).toBeNull()
|
||||
expect((await limit(req()))?.status).toBe(429)
|
||||
expect([...data.keys()]).toEqual(['iapl:2fa-verify:users:1'])
|
||||
expect(data.get('iapl:2fa-verify:users:1')).toMatchObject({ count: 3 })
|
||||
expect(data.get('iapl:2fa-verify:users:1')).toMatchObject({ count: 2 }) // the refused third gave its place back (1.17.1)
|
||||
// an empty or undefined prefix is "not given", never a third key
|
||||
for (const keyPrefix of [undefined, '', ' ']) {
|
||||
data.clear()
|
||||
|
||||
@@ -316,8 +316,12 @@ describe('iapl and the 2FA plugin', () => {
|
||||
test('verify attempts are limited per account, and the limit can be changed or switched off', async () => {
|
||||
clearVerifyLimits()
|
||||
const req = (id: unknown) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never
|
||||
const limit = buildVerifyLimit('users') // 5 in 10 minutes
|
||||
for (let i = 0; i < 5; i++) {expect(await limit(req(1))).toBeNull()}
|
||||
const limit = buildVerifyLimit('users') // 5 wrong codes in 10 minutes
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const attempt = req(1)
|
||||
expect(await limit(attempt)).toBeNull()
|
||||
await limit.settle(attempt, false) // a wrong code (1.17.1: a right one gives its place back)
|
||||
}
|
||||
const refused = (await limit(req(1)))!
|
||||
expect(refused.status).toBe(429)
|
||||
expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(0)
|
||||
@@ -360,7 +364,8 @@ describe('iapl and the 2FA plugin', () => {
|
||||
expect(await limit(req(kv))).toBeNull() // 4th
|
||||
expect(await limit(req(kv))).toBeNull() // 5th
|
||||
expect((await limit(req(kv)))!.status).toBe(429)
|
||||
expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 6 })
|
||||
// five attempts; the refused sixth compared nothing and gave its place back (1.17.1)
|
||||
expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 5 })
|
||||
// and a restart while refused keeps refusing, with the stored window's Retry-After
|
||||
clearVerifyLimits()
|
||||
const again = (await limit(req(kv)))!
|
||||
@@ -468,7 +473,7 @@ describe('iapl and the 2FA plugin', () => {
|
||||
})
|
||||
|
||||
test('wired by default on verify and setup, before the limit; not on other endpoints; sameOrigin: false turns it off', async () => {
|
||||
const handler = vi.fn(() => Response.json({ ok: true }))
|
||||
const handler = vi.fn(() => Response.json({ ok: false })) // wrong codes: they stay counted (a right one gives its place back)
|
||||
const warn = vi.fn()
|
||||
clearReportedOrigins()
|
||||
const withEndpoints = (o: { collection: string }) => (c: Config) => ({
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* 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)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user