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:
co-authored by
Claude Fable 5.2
parent
32faaa5e30
commit
c56f0d41b8
@@ -10,7 +10,8 @@ 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 { guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.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'
|
||||
|
||||
@@ -76,7 +77,7 @@ describe('userMeetsRole: who is staff', () => {
|
||||
})
|
||||
|
||||
describe('adminOrSelfIn', () => {
|
||||
const run = (fn: Access, user: unknown) => fn({ req: { user } } as never)
|
||||
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 } })
|
||||
@@ -97,6 +98,7 @@ describe('secondFactorPassed', () => {
|
||||
['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],
|
||||
]
|
||||
test.each(cases)('%s', (_, user, expected) => {
|
||||
expect(secondFactorPassed({ payload, user })).toBe(expected)
|
||||
@@ -142,14 +144,35 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
|
||||
})
|
||||
|
||||
test('onInit guards what a later plugin added; Payload\'s own collections are left alone', () => {
|
||||
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 payload = { config: { collections: [late, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [] } } as never
|
||||
expect(guardPayloadAccess(payload)).toEqual(['late'])
|
||||
expect((late.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
|
||||
expect(internal.access.read).toBeUndefined()
|
||||
const jobs = { access: {} 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 own rules (run / queue / cancel)
|
||||
for (const op of ['run', 'queue', 'cancel']) {
|
||||
expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
|
||||
expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
|
||||
}
|
||||
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 () => {
|
||||
@@ -210,6 +233,55 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user