Security review round 2: no exception by name, staff list fails closed, verify limit

R2-1: the sweep skipped every collection whose slug starts with payload-,
so a plugin's payload-... collection added after ipalKit was never guarded.
There is no exception by name or prefix now: every collection and global
is guarded, Payload's own included, and the job queue's run / queue /
cancel rules too.

R2-2: role predicates called without a source fail closed where the staff
collections are not known (browser bundle, middleware, edge): nobody is
staff. They accept req.payload, a config (also the client config) or
{ staffCollections } as the source.

R2-3: the staff list is filed per config / Payload instance; a call without
a source gets only what every config in the process calls staff.

R2-4: payload.config is watched on the instance, so a config swapped in by
a dev reload is guarded before any request or Local API call.

R2-5: verify attempts are limited per account (default 5 in 10 minutes,
twoFactor.verifyLimit), counted in memory, never skipped.

R2-6: a user object without collection owes the second factor; endpoints
the 2FA package may add on collections or globals are guarded too; a
warning names staff collections that 2FA does not cover; docs state what
is not covered, fix the one-argument examples and the doctor example.

HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and
MongoDB (test adapter added).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 01:46:25 +01:00
co-authored by Claude Fable 5.2
parent 32faaa5e30
commit c56f0d41b8
34 changed files with 871 additions and 108 deletions
+84 -4
View File
@@ -15,7 +15,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { numericIds, testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
@@ -28,7 +28,13 @@ const PASSWORD = 'a-long-test-password-1'
/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */
const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [...(config.collections ?? []), { slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] }],
collections: [
...(config.collections ?? []),
{ slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] },
// A plugin may well call its collection `payload-…` (@payloadcms/plugin-mcp: `payload-mcp-api-keys`).
{ slug: 'payload-vault', access: { read: ({ req }) => Boolean(req.user) }, fields: [{ name: 'secret', type: 'text' }] },
],
globals: [...(config.globals ?? []), { slug: 'late-settings', fields: [{ name: 'note', type: 'text' }] }],
})
const projectCollections: CollectionConfig[] = [
@@ -114,10 +120,14 @@ beforeAll(async () => {
payload = await getPayload({ config })
server = await startPayloadServer(config)
// The plugin's own and `late-notes`. Payload's built-in collections and the late plugin's `payload-vault` /
// `late-settings` have a describe of their own below (their rule is "any logged-in account", so the comparisons
// with an anonymous visitor do not apply to them).
pluginCollections = payload.config.collections.map((c) => c.slug).filter((s) => !PROJECT_SLUGS.has(s) && !s.startsWith('payload-'))
pluginGlobals = payload.config.globals.map((g) => g.slug)
pluginGlobals = payload.config.globals.map((g) => g.slug).filter((slug) => slug !== 'late-settings')
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
await payload.create({ collection: 'payload-vault' as never, data: { secret: 'VAULT' } as never })
const user = (email: string, extra: object) =>
payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['admin'], ...extra } as never })
await user('[email protected]', { totpSecret: TOTP_SECRET })
@@ -346,7 +356,7 @@ describe("the 2FA package's endpoints accept accounts of the 2FA collection only
const after = await secretOf('[email protected]')
expect(after.totpSecret).toBe(TOTP_SECRET)
// the case this test is about: the two accounts really share an id (SQL adapters; on MongoDB ids never repeat)
expect(String(customer.user.id)).toBe(String(admin.id))
if (numericIds()) {expect(String(customer.user.id)).toBe(String(admin.id))}
// an account of yet another auth collection is refused the same way
const member = await api('/setup-totp', sessions.member, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
expect(member.status).toBe(403)
@@ -382,16 +392,86 @@ describe('per-entity opt-out from the second factor', () => {
})
})
describe('no exception by name: a later plugin\'s `payload-…` collection is guarded like any other', () => {
test('REST (list, count, by id) and GraphQL refuse a password-only session; a verified one reads it', async () => {
for (const p of ['/payload-vault', '/payload-vault/count', '/globals/late-settings']) {
const res = await api(p, sessions.passwordOnly)
expect([p, res.status]).toEqual([p, 403])
expect(await res.text()).not.toContain('VAULT')
}
const out = await gql(sessions.passwordOnly, '{ PayloadVaults { docs { secret } } }')
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
expect(JSON.stringify(out)).not.toContain('VAULT')
const ok = await api('/payload-vault', sessions.verified)
expect(ok.status).toBe(200)
expect(await ok.text()).toContain('VAULT')
})
test("Payload's own collections answer a password-only session nothing either", async () => {
const own = payload.config.collections.map((c) => c.slug).filter((slug) => slug.startsWith('payload-') && slug !== 'payload-vault')
expect(own).toEqual(expect.arrayContaining(['payload-preferences', 'payload-locked-documents', 'payload-migrations']))
const open: string[] = []
for (const slug of own) {
const status = (await api(`/${slug}`, sessions.passwordOnly)).status
if (status === 200) {open.push(`${slug}: ${status}`)}
}
expect(open).toEqual([])
})
})
describe('the code cannot be guessed: verify attempts are limited per account', () => {
const GUESS_SECRET = 'ONSWG4TFORRW6ZDF'
let cookie: string
beforeAll(async () => {
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: GUESS_SECRET } as never })
cookie = (await login('users', '[email protected]')).cookies.join('; ')
})
const verify = (token: string, headers: Record<string, string> = { cookie }) =>
fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token }), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
test('five wrong codes are answered, the sixth attempt is refused — also with the right code', async () => {
for (let i = 0; i < 5; i++) {
const res = await verify('000000')
expect(res.status).toBe(200)
expect(((await res.json()) as { ok: boolean }).ok).toBe(false)
}
const sixth = await verify('000000')
expect(sixth.status).toBe(429)
expect(Number(sixth.headers.get('retry-after'))).toBeGreaterThan(0)
const right = await verify(totp(GUESS_SECRET))
expect(right.status).toBe(429)
expect(right.headers.getSetCookie().join(';')).not.toContain('payload-totp')
expect((await fetch(`${server.url}/api/pages`, { headers: { cookie } })).status).toBe(403)
})
test('the limit is the account\'s alone: nobody without its password can use it, other accounts are not affected', async () => {
// someone without the password cannot count against the account: no session, or a session of another collection
for (let i = 0; i < 8; i++) {
await verify('000000', {})
await verify('000000', sessions.customer.headers)
}
// another staff account still verifies
const other = await login('users', '[email protected]')
const ok = await verify(totp(TOTP_SECRET), { cookie: other.cookies.join('; ') })
expect(((await ok.json()) as { ok: boolean }).ok).toBe(true)
})
})
// Last: it replaces the running config.
describe('dev hot reload', () => {
test('a freshly built config is guarded again, also what a later plugin added', async () => {
// What Payload's reload() does to the instance: a newly built and sanitized config, no onInit.
const fresh = await makeConfig()
payload.config = fresh
// Before any HTTP request: the Local API meets the new config guarded already.
const passwordOnlyUser = { ...(await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0], _strategy: 'local-jwt', collection: 'users' }
payload.collections = Object.fromEntries(
fresh.collections.map((c) => [c.slug, { config: c, customIDType: payload.collections[c.slug as never]?.customIDType }]),
) as never
payload.globals = { config: fresh.globals }
await expect(payload.find({ collection: 'late-notes' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
await expect(payload.find({ collection: 'payload-vault' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
await expect(payload.findGlobal({ slug: 'late-settings' as never, overrideAccess: false, user: passwordOnlyUser })).rejects.toThrow()
expect((await api('/late-notes', sessions.passwordOnly)).status).toBe(403)
expect((await api('/late-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)