2FA setup required: review fixes (SR-1 to SR-9)

SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy,
nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops
reading at the size limit.
SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a
windowHours that is not a number or false, stop the start.
SR-3: on Postgres / SQLite the missing column makes every login fail: the log
says so, the docs call the migration a required step of the same deploy, and
ipal-doctor reports a SQL project without it.
SR-4: an admin's reset also ends the account's sessions.
SR-5: the reset needs a session that entered its own TOTP code by default.
SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert.
SR-7: building blocks exported; dashboard notice, status field, setup notice and
the server-side image fetch can be switched off one by one.
SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on.
SR-9: both ways out of "every administrator is blocked" in security.md.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 19:32:34 +01:00
co-authored by Claude Fable 5.2
parent 9d2ab43438
commit 75a6f5209e
34 changed files with 780 additions and 103 deletions
+147 -3
View File
@@ -4,7 +4,7 @@
*/
import type { Access, Config } from 'payload'
import { describe, expect, test } from 'vitest'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
@@ -20,7 +20,7 @@ import {
twoFactorSetupState,
watchPayloadConfig,
} from '../src/modules/security/totp/secondFactor.js'
import { resolveRequireSetup } from '../src/modules/security/totp/setupRequired.js'
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
@@ -377,8 +377,28 @@ describe('ipalKit and the 2FA plugin', () => {
const off = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base())
expect(guard(off)).toMatchObject({ requireSetup: false })
expect(off.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
// the data field stays whenever 2FA is on: the schema must not depend on the switch (SQL would drop the column)
const offUsers = off.collections!.find((c) => c.slug === 'users')!
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus')).toBe(false)
expect(offUsers.hooks?.beforeChange?.length ?? 0).toBe(0) // no stamping while the mode is off
expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert')
const guardOff = await ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base())
expect(guardOff.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true)
// each part of the mode has its own switch
const has = (c: Config) => ({
dashboard: JSON.stringify(c.admin?.components?.beforeDashboard ?? []).includes('TwoFactorAlert'),
setupNotice: JSON.stringify(c.admin?.components?.providers ?? []).includes('"requireSetup":true'),
status: c.collections!.find((x) => x.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'),
})
// fakeTotp registers no provider, so the setup notice is checked with the real package in test/safeBack.test.ts
expect(has(on)).toMatchObject({ dashboard: true, status: true })
const noDash = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base())
expect(has(noDash)).toMatchObject({ dashboard: false, status: true })
const noStatus = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base())
expect(has(noStatus)).toMatchObject({ dashboard: true, status: false })
expect(guard(noStatus)).toMatchObject({ requireSetup: true }) // the lock itself is unchanged
expect(off.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) // an admin can still reset a lost phone
// 2FA off: nothing of this exists
@@ -387,6 +407,130 @@ describe('ipalKit and the 2FA plugin', () => {
expect(none.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false)
})
test.each([['24'], [-1], [Number.NaN], [Number.POSITIVE_INFINITY], [true], [null]])('requireSetup.windowHours %s stops the start (a typo must not mean "no limit")', async (windowHours) => {
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/)
// also when ipal-kit's own check is off: a wrong value is never silently accepted
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/)
expect(() => resolveRequireSetup({ windowHours: windowHours as never })).toThrow(/windowHours/)
})
test('windowHours: a number, 0 or false still work', () => {
expect(resolveRequireSetup({ windowHours: 1.5 }).setupWindowMs).toBe(1.5 * 3_600_000)
expect(resolveRequireSetup({ windowHours: 0 }).setupWindowMs).toBe(0)
expect(resolveRequireSetup({ windowHours: false }).setupWindowMs).toBe(0)
})
// exempt lets an account in on its password: anything but a plain `true` must never do that.
describe('requireSetup.exempt', () => {
const user = { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSetupFrom: new Date().toISOString() }
const payloadWith = (exempt: unknown) => ({ config: { custom: { ipal: { twoFactor: { collection: 'users', ...resolveRequireSetup({ exempt: exempt as never }) } } } } })
test('an async function stops the start', async () => {
expect(() => resolveRequireSetup({ exempt: (async () => false) as never })).toThrow(/must not be async/)
await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/)
expect(() => resolveRequireSetup({ exempt: 'yes' as never })).toThrow(/must be a function/)
})
test.each([
['a Promise from a plain function', () => Promise.resolve(false)],
['a rejecting Promise', () => Promise.reject(new Error('x'))],
['a string', () => 'yes'],
['a number', () => 1],
['an object', () => ({})],
['an error', () => { throw new Error('boom') }],
['false', () => false],
['undefined', () => undefined],
])('%s exempts nobody', (_name, exempt) => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const payload = payloadWith(exempt)
expect(secondFactorPassed({ payload: payload as never, user })).toBe(false)
expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open')
error.mockRestore()
})
test('only true exempts; a wrong answer is logged', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const yes = payloadWith(() => true)
expect(secondFactorPassed({ payload: yes as never, user })).toBe(true)
expect(twoFactorSetupState({ payload: yes as never, user })).toBe('exempt')
expect(error).not.toHaveBeenCalled()
const odd = strictExempt(() => Symbol('yes') as never)
expect(odd({ user })).toBe(false)
expect(odd({ user })).toBe(false)
expect(error).toHaveBeenCalledTimes(1) // each kind of wrong answer once, not on every request
expect(String(error.mock.calls[0]?.[0])).toMatch(/exempt returned a symbol.*NOT exempt/)
error.mockRestore()
})
test('a guard config built without resolveRequireSetup is strict too', () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users', exempt: () => Promise.resolve(true), requireSetup: true } } } } }
expect(secondFactorPassed({ payload: payload as never, user })).toBe(false)
expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open')
})
})
// Postgres / SQLite without the migration: the start-up step is the first to hit the missing column. It must not
// stop the site, and must say what the real consequence is (every login fails), not only "no window yet".
test('a missing column at start: no throw, and the log says nobody can log in', async () => {
const { backfillSetupFrom } = await import('../src/modules/security/totp/setupRequired.js')
const fake = (name: string, message: string) => {
const logger = { error: vi.fn(), warn: vi.fn() }
return { logger, payload: { count: async () => { throw new Error(message) }, db: { name }, logger } }
}
const pg = fake('postgres', 'column users.totp_setup_from does not exist')
expect(await backfillSetupFrom(pg.payload as never, 'users')).toBe(0)
expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN.*migrate/s)
const sqlite = fake('sqlite', 'no such column: totp_setup_from')
await backfillSetupFrom(sqlite.payload as never, 'users')
expect(sqlite.logger.error).toHaveBeenCalledTimes(1)
const mongo = fake('mongoose', 'connection lost')
await backfillSetupFrom(mongo.payload as never, 'users')
expect(mongo.logger.error).not.toHaveBeenCalled()
expect(mongo.logger.warn).toHaveBeenCalledTimes(1)
})
// The reset removes a second factor: by default only a session that entered its own TOTP code may do it.
describe('the reset endpoint: who may use it', () => {
const run = async (reqUser: Record<string, unknown>, options: Parameters<typeof buildTwoFactorResetEndpoint>[1] = {}, guardExtra: Record<string, unknown> = {}) => {
const update = vi.fn(async () => ({}))
const payload = {
collections: { users: { config: { auth: { useSessions: true } } } },
config: { collections: [{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select' }] }], custom: { ipal: { staffCollections: ['users'], twoFactor: { collection: 'users', requireSetup: true, ...guardExtra } } } },
logger: { error: () => undefined, info: () => undefined },
update,
}
const req = { i18n: { t: (k: string) => k }, json: async () => ({ userId: '7' }), payload, user: reqUser }
const res = await buildTwoFactorResetEndpoint('users', options).handler(req as never)
return { status: res.status, update }
}
const admin = { id: 1, collection: 'users', hasTotp: true, roles: ['admin'] }
test('a session that entered its code: allowed; the account loses its secret AND its sessions', async () => {
const { status, update } = await run({ ...admin, _strategy: 'totp' })
expect(status).toBe(200)
const data = (update.mock.calls[0] as unknown as [{ data: Record<string, unknown>; id: string }])[0]
expect(data.id).toBe('7')
expect(data.data).toMatchObject({ sessions: [], totpSecret: null })
expect(typeof data.data.totpSetupFrom).toBe('string')
})
test('an exempt admin on its password, and an API-key admin: refused by default', async () => {
const exempt = { exempt: () => true }
expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, {}, exempt)).status).toBe(403)
expect((await run({ ...admin, _strategy: 'api-key' })).status).toBe(403)
expect((await run({ ...admin, _strategy: 'local-jwt' })).status).toBe(403) // password only
})
test('resetAccess loosens it for those sessions — never for one that still owes its code', async () => {
const access = () => true
expect((await run({ ...admin, _strategy: 'api-key' }, { access })).status).toBe(200)
expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, { access }, { exempt: () => true })).status).toBe(200)
expect((await run({ ...admin, _strategy: 'local-jwt' }, { access })).status).toBe(403)
expect((await run({ ...admin, _strategy: 'totp' }, { access: () => 'yes' as never })).status).toBe(403) // only true
expect((await run({ ...admin, _strategy: 'totp' }, { access: async () => true })).status).toBe(200)
})
})
test('twoFactor: false — no guard, a password is enough (as documented)', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)