Staff check (userMeetsRole): the 'no roles field = every account passes' rule applied to the account's own collection, so an account of a second auth collection (customers) passed every staff check. It now applies only to staff collections: the panel's login collection plus the new access.staffCollections. The injected auth collection uses the new adminOrSelfIn(slug), so an account of another collection with the same numeric id is not 'self'. 2FA: @clocklimited/payload-2fa wraps the collections and globals present when it runs; ipalKit's own globals and collections were added later and stayed unwrapped, so a password without the TOTP code opened them over REST and GraphQL. ipal-kit now has its own second-factor check (secondFactorPassed / requireSecondFactor): applied to every collection and global at the end of ipalKit, again in onInit for entities added by plugins listed after it, and inside userMeetsRole and the endpoints that take a project access function. It fails closed: an unrecognised user shape is refused, and startup stops when the injected 2FA plugin lacks the parts the check reads (twoFactor.guard: false opts out). Tests through real HTTP requests (REST and GraphQL) against Payload's route handlers, plus the reference smoke test. Docs, agent guide, skills and the reference skills copy updated; changelog entry without a version. Co-Authored-By: Claude Fable 5.2 <[email protected]>
164 lines
9.6 KiB
TypeScript
164 lines
9.6 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 { staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
|
|
import { guardPayloadAccess, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.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)
|
|
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' } }, 'admin')).toBe(false)
|
|
})
|
|
|
|
test('without a payload only a held role counts', () => {
|
|
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
|
|
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('adminOrSelfIn', () => {
|
|
const run = (fn: Access, user: unknown) => fn({ req: { 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],
|
|
]
|
|
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('onInit guards what a later plugin added; Payload\'s own collections are left alone', () => {
|
|
const late = { slug: 'late', access: {} as Record<string, unknown> }
|
|
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()
|
|
expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time
|
|
})
|
|
|
|
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('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)
|
|
})
|
|
})
|