Files
ipal-kit/test/exemptByField.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 91770ec17f 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]>
2026-11-26 20:15:51 +01:00

86 lines
4.3 KiB
TypeScript

/**
* 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]')
})
})