Files
ipal-kit/test/secondFactorGuard.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 dc5326ea1c Review round 3: job-queue rules keep Payload's own defaults; a failed 2FA lookup fails closed
Job queue (R3-1): only a rule that exists is wrapped. At config time that
is what the project wrote; Payload fills in the rest when it builds the
config (3.94.1: run, queue and cancel are all defaultAccess, a logged-in
user) and the sweep of the running config wraps those. No default is
invented, so a request without a user gets what Payload itself answers.

hasTotp false while the account's record carries a TOTP secret (the 2FA
package's own lookup failed, R3-4): the account owes its code, not
'not set up yet'.

Docs: the two-configs-in-one-process case for calls without a source, and
that a half-logged-in editor's browser is refused media files.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 02:22:04 +01:00

302 lines
19 KiB
TypeScript

/**
* The rules behind test/securityHttp.test.ts, one by one: who is staff (userMeetsRole), when the second
* factor counts as passed, and what ipalKit does with a 2FA plugin it does not recognise.
*/
import type { Access, Config } from 'payload'
import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/access.js'
import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { ensurePayloadGuarded, guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed, watchPayloadConfig } from '../src/modules/security/totp/secondFactor.js'
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
const fakeTotp = (o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)
/** A payload as the access functions see it: sanitized `admin.user`, the collections by slug, `custom`. */
const payloadOf = (config: Config, adminUser = 'users') =>
({
collections: Object.fromEntries((config.collections ?? []).map((c) => [c.slug, { config: c }])),
config: { admin: { user: adminUser }, collections: config.collections, custom: config.custom, globals: config.globals },
}) as never
const twoAuth = (): Config =>
({
collections: [
{ slug: 'customers', auth: true, fields: [] },
{ slug: 'partners', auth: true, fields: [] },
],
secret: 'x',
}) as unknown as Config
describe('userMeetsRole: who is staff', () => {
test('with roles: the role decides; an account of another auth collection never passes', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['user'] } }, 'editor')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'no-such-collection' } }, 'user')).toBe(false)
// a role value on an account of a non-staff collection counts for nothing
expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { roles: ['admin'] } }, 'user')).toBe(false) // no collection at all
expect(userMeetsRole({ payload, user: null }, 'user')).toBe(false)
})
test('without `access`: every account of the panel collection passes, other auth collections do not', async () => {
const config = await ipalKit({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users'])
expect(userMeetsRole({ payload, user: { collection: 'users' } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('access.staffCollections names more staff collections, on purpose', async () => {
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners'])
expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal
expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('without a payload: the staff collections of the config ipalKit built last; only a held role counts', async () => {
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // isAdmin(req.user) in a hook
expect(isAdmin({ collection: 'users', roles: ['admin'] })).toBe(true)
})
})
describe('adminOrSelfIn', () => {
const run = (fn: Access, user: unknown) => fn({ req: { payload: { config: { admin: { user: 'users' } } }, user } } as never)
test('"self" is an account of that collection only', () => {
const access = adminOrSelfIn('users')
expect(run(access, { id: 5, collection: 'users', roles: ['user'] })).toEqual({ id: { equals: 5 } })
expect(run(access, { id: 5, collection: 'customers' })).toBe(false) // same id, other collection
expect(run(access, { id: 1, collection: 'users', roles: ['admin'] })).toBe(true)
expect(run(access, null)).toBe(false)
})
})
describe('secondFactorPassed', () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } } as never
const cases: [string, unknown, boolean][] = [
['no user', null, true],
['password and code (the totp strategy)', { _strategy: 'totp', collection: 'users', hasTotp: true }, true],
['API key', { _strategy: 'api-key', collection: 'users', hasTotp: true }, true],
['TOTP not set up yet', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true],
['password only', { _strategy: 'local-jwt', collection: 'users', hasTotp: true }, false],
['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false],
['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false],
['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true],
['a user object that does not say its collection (fail closed)', { _strategy: 'totp', hasTotp: true }, false],
['`hasTotp` false although the record carries a secret (the package\'s lookup failed): refused', { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSecret: 'JBSWY3DPEHPK3PXP' }, false],
]
test.each(cases)('%s', (_, user, expected) => {
expect(secondFactorPassed({ payload, user })).toBe(expected)
})
test('2FA off: everyone passes', () => {
expect(secondFactorPassed({ payload: { config: {} } as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } })).toBe(true)
})
test('requireSecondFactor wraps once and keeps the inner rule', () => {
const inner: Access = ({ req }) => Boolean((req.user as { ok?: boolean } | null)?.ok)
const wrapped = requireSecondFactor(inner)
expect(requireSecondFactor(wrapped)).toBe(wrapped)
const call = (user: unknown) => wrapped({ req: { payload, user } } as never)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true, ok: true })).toBe(true)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe(false)
expect(call({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, ok: true })).toBe(false)
})
})
describe('ipalKit and the 2FA plugin', () => {
const passwordOnly = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] }
const verified = { ...passwordOnly, _strategy: 'totp' }
test('every collection and global in the config is guarded, whenever it was added', async () => {
const config = await ipalKit({
access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, forms: {}, i18n, stats: true,
twoFactor: { issuer: 'A', plugin: fakeTotp as never },
})({ collections: [{ slug: 'pages', fields: [] }], globals: [{ slug: 'own', fields: [] }], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
const open: string[] = []
const check = (kind: string, slug: string, access: Record<string, unknown> | undefined, ops: string[]) => {
for (const op of ops) {
const fn = access?.[op] as ((a: unknown) => unknown) | undefined
if (!fn || fn({ req: { payload, user: passwordOnly } }) !== false) {open.push(`${kind} ${slug}.${op}`)}
}
}
for (const c of config.collections ?? []) {check('collection', c.slug, c.access as never, ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])}
for (const g of config.globals ?? []) {check('global', g.slug, g.access as never, ['read', 'readDrafts', 'readVersions', 'update'])}
expect(open).toEqual([])
// and a verified admin still gets in
const integrations = config.globals!.find((g) => g.slug === 'site-integrations')!
expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
})
test('the sweep guards everything a later plugin or Payload itself added — no exception by name or prefix', () => {
const late = { slug: 'late', access: {} as Record<string, unknown> }
const prefixed = { slug: 'payload-vault', access: {} as Record<string, unknown> } // a plugin's collection, e.g. payload-mcp-api-keys
const internal = { slug: 'payload-preferences', access: {} as Record<string, unknown> }
const loggedIn = ({ req }: { req: { user?: unknown } }) => Boolean(req.user) // Payload's defaultAccess
const jobs = { access: { cancel: loggedIn, queue: loggedIn, run: loggedIn } as Record<string, unknown> }
const payload = { config: { collections: [late, prefixed, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [{ slug: 'payload-jobs-stats' }], jobs } } as never
expect(guardPayloadAccess(payload)).toEqual(['late', 'payload-vault', 'payload-preferences', 'payload-jobs-stats', 'jobs'])
for (const entity of [late, prefixed, internal]) {
expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
}
// the job queue's rules as Payload filled them in (3.94.1: all three "a logged-in user"): kept, plus
// "not while the second factor is owed"
const job = (op: string, user: unknown) => (jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user } })
for (const op of ['run', 'queue', 'cancel']) {
expect([op, job(op, null), job(op, passwordOnly), job(op, verified)]).toEqual([op, false, false, true])
}
// a rule the project set is kept as it is; a rule nobody set is not invented (Payload fills it in)
const own = { access: { queue: () => true } as Record<string, unknown> }
guardPayloadAccess({ config: { collections: [], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [], jobs: own } } as never)
const ownQueue = (user: unknown) => (own.access.queue as (a: unknown) => unknown)({ req: { payload, user } })
expect([ownQueue(null), ownQueue(passwordOnly), ownQueue(verified)]).toEqual([true, false, true])
expect(own.access.run).toBeUndefined()
expect(own.access.cancel).toBeUndefined()
expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time
expect(ensurePayloadGuarded(payload)).toEqual([])
expect(ensurePayloadGuarded(payload)).toBeNull() // this config object was done
})
test('a config swapped onto the instance (dev reload) is adopted at once, before any request', () => {
const adopted: unknown[] = []
const instance = { config: { name: 'first' } } as never as { config: { name: string } }
watchPayloadConfig(instance as never, (p) => adopted.push((p as never as { config: { name: string } }).config.name))
instance.config = { name: 'second' }
expect(adopted).toEqual(['second'])
expect(instance.config.name).toBe('second')
expect({ ...instance }.config.name).toBe('second') // still an ordinary enumerable property to readers
})
test('a 2FA plugin without the parts the guard relies on stops the start', async () => {
const unknown = () => (c: Config) => c
const run = (guard?: false) =>
ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config)
await expect(run()).rejects.toThrow(/did not add the `totpSecret` field, the `hasTotp` field, the `totp` auth strategy/)
// twoFactor.guard: false = the package alone, as before
const config = await run(false)
expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined()
})
test('per-entity opt-out: the package key and ipal-kit\'s key, operation by operation', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
collections: [
{ slug: 'a', custom: { totp: { disableAccessWrapper: { read: true } } }, fields: [] },
{ slug: 'b', custom: { ipal: { secondFactor: false } }, fields: [] },
],
globals: [{ slug: 'g', custom: { ipal: { secondFactor: { read: false } } }, fields: [] }],
secret: 'x',
} as unknown as Config)
const payload = payloadOf(config)
// an operation without a function = Payload's default: any logged-in account
const call = (access: unknown, op: string) => {
const fn = (access as Record<string, ((a: unknown) => unknown) | undefined> | undefined)?.[op]
return fn ? fn({ req: { payload, user: passwordOnly } }) : true
}
const col = (slug: string) => config.collections!.find((c) => c.slug === slug)!.access
expect(call(col('a'), 'read')).toBe(true)
expect(call(col('a'), 'update')).toBe(false)
// opted out of everything and no rule of its own: left exactly as the project wrote it (Payload's default applies)
expect(col('b')).toBeUndefined()
const g = config.globals!.find((x) => x.slug === 'g')!.access
expect(call(g, 'read')).toBe(true)
expect(call(g, 'update')).toBe(false)
// ipal-kit's key reaches the package in its own key, so the package leaves the operation alone too
expect((config.globals!.find((x) => x.slug === 'g')!.custom as { totp: unknown }).totp).toEqual({ disableAccessWrapper: { read: true } })
})
test("the 2FA package's endpoints: accounts of the 2FA collection only; management needs the second factor", async () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } }
const inner = () => Promise.resolve(Response.json({ ok: true }))
const call = async (path: string, user: unknown) => {
const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise<Response>, path }, 'users')
return (await endpoint.handler({ payload, user } as never)).status
}
const customer = { id: 1, collection: 'customers' }
const newcomer = { id: 2, _strategy: 'local-jwt', collection: 'users', hasTotp: false }
for (const path of ['/setup-totp', '/verify-totp', '/remove-totp', '/admin/reset-user-totp', '/some-future-endpoint']) {
expect([path, await call(path, customer)]).toEqual([path, 403])
expect([path, await call(path, null)]).toEqual([path, 200]) // no user: the package answers itself
}
expect(await call('/setup-totp', newcomer)).toBe(200)
expect(await call('/verify-totp', passwordOnly)).toBe(200)
expect(await call('/remove-totp', passwordOnly)).toBe(403)
expect(await call('/admin/reset-user-totp', passwordOnly)).toBe(403)
expect(await call('/some-future-endpoint', passwordOnly)).toBe(403)
expect(await call('/admin/reset-user-totp', verified)).toBe(200)
})
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(limit(req(1))).toBeNull()}
const refused = limit(req(1))!
expect(refused.status).toBe(429)
expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(0)
expect(((await refused.json()) as { message: string }).message).toMatch(/Too many codes/)
expect(limit(req(2))).toBeNull() // another account is not affected
expect(limit({ ...(req(1) as object), user: null } as never)).toBeNull() // no session: the package refuses by itself
const two = buildVerifyLimit('admins', { max: 2, windowMinutes: 1 })
expect([two(req(1)), two(req(1))]).toEqual([null, null])
expect(two(req(1))!.status).toBe(429)
// wired by default; twoFactor.verifyLimit: false leaves the package's endpoint as it is
const base = () => ({ collections: [], endpoints: [], secret: 'x' }) as unknown as Config
const withEndpoint = (o: { collection: string }) => (c: Config) => ({ ...withTotpParts(c, o.collection), endpoints: [...(c.endpoints ?? []), { handler: () => Response.json({ ok: false }), method: 'post' as const, path: '/verify-totp' }] })
const call = async (config: Config, n: number) => {
const endpoint = config.endpoints!.find((e) => e.path === '/verify-totp')!
let last = 0
for (let i = 0; i < n; i++) {last = (await endpoint.handler(req(77))).status}
return last
}
clearVerifyLimits()
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429)
clearVerifyLimits()
expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200)
})
test('staff collections outside the 2FA collection are named in a warning at start', async () => {
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
...twoAuth(),
admin: { user: 'users' },
} as Config)
const warnings: string[] = []
const payload = {
collections: {},
config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] },
count: () => ({ totalDocs: 0 }),
find: () => ({ docs: [] }),
findGlobal: () => ({}),
logger: { info: () => {}, warn: (m: string) => warnings.push(m) },
updateGlobal: () => ({}),
}
await Promise.resolve(config.onInit!(payload as never)).catch(() => {}) // later onInit steps need a real database
expect(warnings.join('\n')).toMatch(/2FA covers "users" only\. Staff accounts of "partners"/)
})
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)
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: unknown) => unknown
expect(read({ req: { payload, user: { collection: 'users', roles: ['admin'] } } })).toBe(true)
})
})