Security audit 2026-12, F0: inside an account's setup window its password alone enrolled an authenticator of the caller's choosing; the owner was locked out. - /setup-totp for an account without a factor: IAPL checks the code, keeps the secret pending (payload-kv), mails a single-use 30-min link to the account and ties it to the enrolling browser; the package's handler (and its -totp cookie) is never used for a first enrolment - GET /api/iapl/two-factor/confirm = a page with one button; POST confirms (own origin, same browser), ends the account's sessions, signs nobody in - notice mails on every enrolment, change, removal / reset (any path) - mail not working: link to the server log, admin confirms on the account page (POST /api/iapl/two-factor/confirm-pending), doctor rule 2fa-enrolment-mail - options and opt-out (confirmByEmail: false), building blocks exported - tests: HTTP suite on SQLite, MongoDB, Postgres; built-site spec in e2e:built; closed doors and judged routes; docs, AGENT.md, skills, changelog Co-Authored-By: Claude Opus 5.5 <[email protected]>
291 lines
15 KiB
TypeScript
291 lines
15 KiB
TypeScript
/**
|
|
* twoFactor.confirmByEmail (1.18.0; security audit 2026-12, finding F0): the first enrolment of a factor waits for a
|
|
* link sent to the account's own e-mail and opened in the browser that scanned the code. Real HTTP (Payload's REST
|
|
* and GraphQL handlers behind a server), a capturing mail transport, the 2FA package itself.
|
|
*/
|
|
import type { Payload } from 'payload'
|
|
|
|
import { payloadTotp } from '@clocklimited/payload-2fa'
|
|
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
|
import { createServer } from 'node:net'
|
|
import os from 'os'
|
|
import path from 'path'
|
|
import { getPayload } from 'payload'
|
|
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
|
|
|
|
import { pendingEnrolmentKey } from '../src/modules/security/totp/enrolmentConfirm.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 ADMIN_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'
|
|
const ATTACKER_SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
|
|
const OWNER_SECRET = 'KRSXG5CTMVRXEZLUKRSXG5CTMVRXEZLU'
|
|
const PASSWORD = 'a-long-test-password-1'
|
|
|
|
type Mail = { html?: string; subject?: string; text?: string; to?: string }
|
|
const mails: Mail[] = []
|
|
let mailBroken = false
|
|
let server: TestServer
|
|
let payload: Payload
|
|
let base = ''
|
|
|
|
const freePort = () => new Promise<number>((resolve) => {
|
|
const s = createServer().listen(0, '127.0.0.1', () => {
|
|
const { port } = s.address() as { port: number }
|
|
s.close(() => resolve(port))
|
|
})
|
|
})
|
|
|
|
beforeAll(async () => {
|
|
const port = await freePort()
|
|
base = `http://127.0.0.1:${port}`
|
|
const config = buildTestConfig({
|
|
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
|
|
db: testDatabase('enrol_confirm'),
|
|
editor: lexicalEditor(),
|
|
email: () => ({
|
|
name: 'capture',
|
|
defaultFromAddress: '[email protected]',
|
|
defaultFromName: 'Site',
|
|
sendEmail: async (message: unknown) => {
|
|
const m = message as Mail
|
|
if (mailBroken) {throw new Error('SMTP down')}
|
|
mails.push(m)
|
|
return { sent: true }
|
|
},
|
|
}),
|
|
plugins: [
|
|
iapl({
|
|
access: { authCollection: 'users' },
|
|
forms: {},
|
|
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
|
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
|
}),
|
|
],
|
|
secret: 'integration-test-secret-0123456789',
|
|
serverURL: base,
|
|
telemetry: false,
|
|
})
|
|
payload = await getPayload({ config })
|
|
server = await startPayloadServer(config, port)
|
|
// an administrator with a factor (made by a script, like a seed): for the admin's own actions
|
|
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: ADMIN_SECRET } as never })
|
|
}, 120_000)
|
|
|
|
afterAll(async () => {
|
|
await server?.close()
|
|
await payload?.destroy?.()
|
|
})
|
|
|
|
beforeEach(() => {
|
|
mails.length = 0
|
|
mailBroken = false
|
|
})
|
|
|
|
const json = { 'content-type': 'application/json', origin: () => base }
|
|
const headers = (cookie = '', extra: Record<string, string> = {}) => ({ 'content-type': 'application/json', cookie, origin: base, ...extra })
|
|
let accounts = 0
|
|
|
|
/** A new editor account without a factor (inside its setup window). */
|
|
async function newAccount(): Promise<{ email: string; id: number | string }> {
|
|
const email = `person-${++accounts}-${Date.now()}@example.com`
|
|
const doc = (await payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['editor'] } as never })) as unknown as { id: number | string }
|
|
return { id: doc.id, email }
|
|
}
|
|
const signIn = async (email: string) => {
|
|
const res = await fetch(`${base}/api/users/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: headers(), method: 'POST' })
|
|
expect(res.status).toBe(200)
|
|
return cookiesOf(res).join('; ')
|
|
}
|
|
const setup = (cookie: string, secret: string, token = totp(secret)) =>
|
|
fetch(`${base}/api/setup-totp`, { body: JSON.stringify({ secret, token }), headers: headers(cookie), method: 'POST' })
|
|
const storedSecret = async (id: number | string) =>
|
|
((await payload.findByID({ id, collection: 'users' as never, overrideAccess: true, showHiddenFields: true })) as unknown as { totpSecret?: null | string }).totpSecret ?? null
|
|
const linkIn = (mail: Mail | undefined) => {
|
|
const m = (mail?.text ?? '').match(/https?:\/\/\S+\/two-factor\/confirm\?u=\S+/)
|
|
return m ? new URL(m[0]) : null
|
|
}
|
|
const confirm = (link: URL, cookie = '', origin = base) =>
|
|
fetch(`${base}/api/iapl/two-factor/confirm`, {
|
|
body: new URLSearchParams({ t: link.searchParams.get('t')!, u: link.searchParams.get('u')! }).toString(),
|
|
headers: { 'content-type': 'application/x-www-form-urlencoded', cookie, origin },
|
|
method: 'POST',
|
|
})
|
|
void json
|
|
|
|
describe('F0: the password alone no longer enrols a factor', () => {
|
|
test('an attacker with the password: the set-up waits, a link goes to the OWNER\'s mailbox, nothing opens, no -totp cookie', async () => {
|
|
const victim = await newAccount()
|
|
const attacker = await signIn(victim.email)
|
|
const res = await setup(attacker, ATTACKER_SECRET)
|
|
expect(res.status).toBe(202)
|
|
const body = (await res.json()) as { mailed?: boolean; message?: string; ok?: boolean; pending?: boolean }
|
|
expect(body).toMatchObject({ mailed: true, ok: false, pending: true })
|
|
expect(body.message).toMatch(/p…@example\.com/)
|
|
// no factor stored, and the package's cookie was never set (it would turn valid once any secret is confirmed)
|
|
expect(await storedSecret(victim.id)).toBeNull()
|
|
const set = res.headers.getSetCookie().join('\n')
|
|
expect(set).not.toMatch(/payload-totp=/)
|
|
expect(set).toMatch(/payload-iapl-enrol=[^;]+;.*HttpOnly/)
|
|
// still nothing but setup
|
|
for (const p of ['/globals/site-integrations', '/users', '/form-submissions']) {
|
|
expect([p, (await fetch(`${base}/api${p}`, { headers: { cookie: attacker } })).status]).toEqual([p, 403])
|
|
}
|
|
// the mail: to the account, with the link, without the secret
|
|
expect(mails).toHaveLength(1)
|
|
expect(mails[0].to).toBe(victim.email)
|
|
expect(`${mails[0].html}${mails[0].text}`).not.toContain(ATTACKER_SECRET)
|
|
expect(linkIn(mails[0])?.origin).toBe(base)
|
|
})
|
|
|
|
test('the owner opens the attacker\'s link in THEIR browser: refused, the attacker\'s factor is not turned on', async () => {
|
|
const victim = await newAccount()
|
|
const attacker = await signIn(victim.email)
|
|
await setup(attacker, ATTACKER_SECRET)
|
|
const link = linkIn(mails[0])!
|
|
// opening the link (a mail scanner, a preview) changes nothing
|
|
const page = await fetch(link)
|
|
expect(page.status).toBe(200)
|
|
expect(await page.text()).toContain('<form method="post"')
|
|
expect(await storedSecret(victim.id)).toBeNull()
|
|
// the owner's browser has no enrolment cookie
|
|
const ownerSession = await signIn(victim.email)
|
|
const res = await confirm(link, ownerSession)
|
|
expect(res.status).toBe(403)
|
|
expect(await storedSecret(victim.id)).toBeNull()
|
|
})
|
|
|
|
test('the owner\'s own set-up replaces a waiting one; the older link stops working', async () => {
|
|
const victim = await newAccount()
|
|
const attacker = await signIn(victim.email)
|
|
const a = await setup(attacker, ATTACKER_SECRET)
|
|
const attackerLink = linkIn(mails[0])!
|
|
const attackerCookie = cookiesOf(a).find((c) => c.startsWith('payload-iapl-enrol='))!
|
|
const owner = await signIn(victim.email)
|
|
await setup(owner, OWNER_SECRET)
|
|
expect(mails).toHaveLength(2)
|
|
expect((await confirm(attackerLink, `${attacker}; ${attackerCookie}`)).status).toBe(400)
|
|
expect(await storedSecret(victim.id)).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('confirming', () => {
|
|
test('the link in the same browser turns it on, ends every session, signs nobody in; then password + code open the panel', async () => {
|
|
const person = await newAccount()
|
|
const session = await signIn(person.email)
|
|
const res = await setup(session, OWNER_SECRET)
|
|
const enrolCookie = cookiesOf(res).find((c) => c.startsWith('payload-iapl-enrol='))!
|
|
const link = linkIn(mails[0])!
|
|
mails.length = 0
|
|
const done = await confirm(link, `${session}; ${enrolCookie}`)
|
|
expect(done.status).toBe(200)
|
|
expect(await done.text()).toContain('/admin/login')
|
|
expect(done.headers.getSetCookie().join('\n')).not.toMatch(/payload-token=[^;]|payload-totp=[^;]/)
|
|
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
|
// the old password-only session is gone
|
|
const me = (await (await fetch(`${base}/api/users/me`, { headers: { cookie: session } })).json()) as { user: unknown }
|
|
expect(me.user).toBeNull()
|
|
// the notice "turned on"
|
|
expect(mails.map((m) => [m.to, m.subject])).toEqual([[person.email, expect.stringMatching(/two-step|dwuetapow/i)]])
|
|
expect(`${mails[0].html}${mails[0].text}`).not.toContain(OWNER_SECRET)
|
|
// sign in again: password, then the code
|
|
const again = await signIn(person.email)
|
|
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(OWNER_SECRET) }), headers: headers(again), method: 'POST' })
|
|
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
|
|
const full = [again, ...cookiesOf(verify)].join('; ')
|
|
expect((await fetch(`${base}/api/globals/site-settings`, { headers: { cookie: full } })).status).toBe(200)
|
|
// single use
|
|
expect((await confirm(link, `${session}; ${enrolCookie}`)).status).toBe(400)
|
|
})
|
|
|
|
test('a wrong code sends nothing; an expired link and a POST from another origin are refused', async () => {
|
|
const person = await newAccount()
|
|
const session = await signIn(person.email)
|
|
const wrong = await setup(session, OWNER_SECRET, '000000')
|
|
expect(wrong.status).toBe(400)
|
|
expect(mails).toHaveLength(0)
|
|
|
|
const res = await setup(session, OWNER_SECRET)
|
|
const enrolCookie = cookiesOf(res).find((c) => c.startsWith('payload-iapl-enrol='))!
|
|
const link = linkIn(mails[0])!
|
|
expect((await confirm(link, `${session}; ${enrolCookie}`, 'https://evil.example')).status).toBe(403)
|
|
const key = pendingEnrolmentKey('users', person.id)
|
|
const kv = (payload as unknown as { kv: { get: (k: string) => Promise<Record<string, unknown>>; set: (k: string, v: object) => Promise<void> } }).kv
|
|
await kv.set(key, { ...(await kv.get(key)), expiresAt: Date.now() - 1 })
|
|
expect((await confirm(link, `${session}; ${enrolCookie}`)).status).toBe(400)
|
|
expect(await storedSecret(person.id)).toBeNull()
|
|
})
|
|
|
|
test('at most five confirmation mails per account and hour', async () => {
|
|
const person = await newAccount()
|
|
const session = await signIn(person.email)
|
|
for (let i = 0; i < 5; i++) {expect((await setup(session, OWNER_SECRET)).status).toBe(202)}
|
|
expect((await setup(session, OWNER_SECRET)).status).toBe(429)
|
|
expect(mails).toHaveLength(5)
|
|
})
|
|
})
|
|
|
|
describe('mail that does not work', () => {
|
|
test('the link goes to the server log; the person is told to ask an administrator; the admin confirms it', async () => {
|
|
const person = await newAccount()
|
|
const session = await signIn(person.email)
|
|
mailBroken = true
|
|
const warn = vi.spyOn(payload.logger, 'warn')
|
|
const res = await setup(session, OWNER_SECRET)
|
|
const body = (await res.json()) as { mailed?: boolean; message?: string }
|
|
expect(body.mailed).toBe(false)
|
|
expect(body.message).toMatch(/administrator/i)
|
|
const logged = warn.mock.calls.map(([line]) => String(line)).find((line) => line.includes('/two-factor/confirm?u='))
|
|
warn.mockRestore()
|
|
expect(logged).toContain(base)
|
|
expect(await storedSecret(person.id)).toBeNull()
|
|
|
|
// the person themselves cannot use the admin action; an admin with the code can
|
|
expect((await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(session), method: 'POST' })).status).toBe(403)
|
|
const adminSession = await signIn('[email protected]')
|
|
const passwordOnly = await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(adminSession), method: 'POST' })
|
|
expect(passwordOnly.status).toBe(403)
|
|
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(ADMIN_SECRET) }), headers: headers(adminSession), method: 'POST' })
|
|
const admin = [adminSession, ...cookiesOf(verify)].join('; ')
|
|
mailBroken = false
|
|
const ok = await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })
|
|
expect(ok.status).toBe(200)
|
|
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
|
// nothing waits any more
|
|
expect((await fetch(`${base}/api/iapl/two-factor/confirm-pending`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })).status).toBe(404)
|
|
// the notice names who confirmed it
|
|
expect(mails.at(-1)?.text).toContain('[email protected]')
|
|
})
|
|
})
|
|
|
|
describe('notices and the other ways to set or remove a factor', () => {
|
|
test('an administrator\'s reset sends the account a notice; REST and GraphQL cannot write a secret', async () => {
|
|
const person = await newAccount()
|
|
await payload.update({ id: person.id, collection: 'users' as never, data: { totpSecret: OWNER_SECRET } as never, overrideAccess: true })
|
|
mails.length = 0
|
|
const adminSession = await signIn('[email protected]')
|
|
const verify = await fetch(`${base}/api/verify-totp`, { body: JSON.stringify({ token: totp(ADMIN_SECRET) }), headers: headers(adminSession), method: 'POST' })
|
|
const admin = [adminSession, ...cookiesOf(verify)].join('; ')
|
|
|
|
// REST and GraphQL: the field cannot be written, not even by an admin
|
|
await fetch(`${base}/api/users/${person.id}`, { body: JSON.stringify({ totpSecret: ATTACKER_SECRET }), headers: headers(admin), method: 'PATCH' })
|
|
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
|
const gql = await fetch(`${base}/api/graphql`, { body: JSON.stringify({ query: `mutation { updateUser(id: ${JSON.stringify(person.id)}, data: { totpSecret: "${ATTACKER_SECRET}" }) { id } }` }), headers: headers(admin), method: 'POST' })
|
|
expect(gql.status).toBeLessThan(500)
|
|
expect(await storedSecret(person.id)).toBe(OWNER_SECRET)
|
|
|
|
const reset = await fetch(`${base}/api/ipal/two-factor/reset`, { body: JSON.stringify({ userId: person.id }), headers: headers(admin), method: 'POST' })
|
|
expect(reset.status).toBe(200)
|
|
expect(await storedSecret(person.id)).toBeNull()
|
|
const notice = mails.find((m) => m.to === person.email)
|
|
expect(notice?.subject).toMatch(/removed|usunięta/i)
|
|
expect(notice?.text).toContain('[email protected]')
|
|
})
|
|
})
|