Files
ipal-kit/test/accessControl.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 0c61ac231b Security: staff checks only for staff collections; 2FA covers what the plugin adds
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]>
2026-11-24 00:31:55 +01:00

243 lines
10 KiB
TypeScript

import type { Access, CollectionConfig, Config, Field, GlobalConfig } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const empty = (extra: Partial<Config> = {}): Config =>
({ collections: [], secret: 'x', ...extra }) as unknown as Config
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const user = { id: 3, collection: 'users', roles: ['user'] }
/** Runs a collection/global access function the way Payload does. */
const run = (fn: Access | undefined, u: unknown) =>
fn ? fn({ req: { user: u } } as never) : 'payload-default'
describe('injected auth collection', () => {
test('with roles: a plain user can only see and edit itself, never create or delete', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {}
expect(run(access.update, user)).toEqual({ id: { equals: 3 } })
expect(run(access.read, user)).toEqual({ id: { equals: 3 } })
expect(run(access.delete, user)).toBe(false)
expect(run(access.create, user)).toBe(false)
expect(run(access.delete, editor)).toBe(false)
expect(run(access.update, null)).toBe(false)
expect(run(access.update, admin)).toBe(true)
expect(run(access.delete, admin)).toBe(true)
expect(run(access.create, admin)).toBe(true)
})
test("the project's own auth collection keeps its own access", async () => {
const own = { slug: 'users', access: { read: () => true }, auth: true, fields: [] }
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(
empty({ collections: [own] as CollectionConfig[] }),
)
expect(config.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access)
})
})
describe('2FA wraps the auth collection people log in with', () => {
const totp = () => vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
test('defaults to access.authCollection, not a literal "users"', async () => {
const plugin = totp()
await ipalKit({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
empty(),
)
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' }))
})
test('defaults to admin.user when access is not configured', async () => {
const plugin = totp()
await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
empty({ admin: { user: 'staff' } } as Partial<Config>),
)
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' }))
})
const twoAuth = () =>
empty({
admin: { user: 'admins' },
collections: [
{ slug: 'admins', auth: true, fields: [] },
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [] },
],
} as Partial<Config>)
test('admin.user wins over access.authCollection as the default target', async () => {
const plugin = totp()
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth())
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' }))
})
test('a target other than the panel login collection fails at init…', async () => {
const plugin = totp()
await expect(
ipalKit({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()),
).rejects.toThrow(/admin panel logs in with "admins"/)
})
test('…unless allowCollectionMismatch says it is deliberate', async () => {
const plugin = totp()
await ipalKit({
i18n,
twoFactor: { allowCollectionMismatch: true, collectionSlug: 'users', issuer: 'A', plugin: plugin as never },
})(twoAuth())
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'users' }))
})
test('a target that is not an auth collection always fails', async () => {
const plugin = totp()
await expect(
ipalKit({
i18n,
twoFactor: { allowCollectionMismatch: true, collectionSlug: 'pages', issuer: 'A', plugin: plugin as never },
})(twoAuth()),
).rejects.toThrow(/"pages" is not an auth collection/)
})
})
describe('globals: public read, editor+ write', () => {
test.each(['site-settings', 'cookie-settings', 'notifications'])('%s', async (slug) => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const access = (config.globals?.find((g) => g.slug === slug) as GlobalConfig).access ?? {}
expect(run(access.read, null)).toBe(true)
expect(run(access.update, user)).toBe(false)
expect(run(access.update, null)).toBe(false)
expect(run(access.update, editor)).toBe(true)
expect(run(access.update, admin)).toBe(true)
})
})
describe('forms collection: public read, editor+ write, Emails hidden from plain users', () => {
const build = async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty())
return config.collections?.find((c) => c.slug === 'forms') as CollectionConfig
}
test('create / update / delete need editor', async () => {
const { access = {} } = await build()
expect(run(access.read, null)).toBe(true)
for (const op of ['create', 'update', 'delete'] as const) {
expect(run(access[op], user)).toBe(false)
expect(run(access[op], editor)).toBe(true)
}
})
test('the Emails field (recipients, BCC) is unreadable for a plain user', async () => {
const forms = await build()
const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as {
access?: { read?: (a: unknown) => boolean }
}
expect(emails.access?.read?.({ req: { user } })).toBe(false)
expect(emails.access?.read?.({ req: { user: editor } })).toBe(true)
})
})
describe('roles field: the first-register account becomes admin', () => {
const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig
const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: { beforeChange?: ((a: unknown) => unknown)[] } }
const count = vi.fn(async () => ({ totalDocs }))
return roles.hooks?.beforeChange?.[0]?.({
collection: { slug: 'users' },
operation: 'create',
req: { pathname, payload: { count } },
value,
})
}
test('empty collection → admin, whatever was sent', async () => {
expect(await hook(0, ['user'])).toEqual(['admin'])
})
test('later accounts keep what access allowed', async () => {
expect(await hook(1, ['user'])).toEqual(['user'])
})
test('an open sign-up on an empty collection is not promoted', async () => {
expect(await hook(0, ['user'], '/api/users')).toEqual(['user'])
})
})
describe('every access default can be overridden by the project', () => {
test('injected users: unlock is admin-only by default; access.authAccess keys win', async () => {
const base = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
const def = base.collections?.find((c) => c.slug === 'users')?.access ?? {}
expect(run(def.unlock, user)).toBe(false)
expect(run(def.unlock, admin)).toBe(true)
const config = await ipalKit({
access: { authAccess: { read: () => true }, authCollection: 'users' },
i18n,
twoFactor: false,
})(empty())
const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {}
expect(run(access.read, user)).toBe(true)
expect(run(access.delete, user)).toBe(false) // the rest keeps the plugin default
})
test('access.firstUserAdmin: false keeps what the first-register form sent', async () => {
const config = await ipalKit({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty())
const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig
const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: unknown }
expect(roles.hooks).toBeUndefined()
})
test('globalOverrides: an object merges access (project wins), a function takes over', async () => {
const config = await ipalKit({
access: { authCollection: 'users' },
globalOverrides: {
'cookie-settings': (g) => ({ ...g, label: 'Cookies' }),
notifications: { access: { update: ({ req }) => Boolean(req.user) } },
},
i18n,
twoFactor: false,
})(empty())
const notifications = config.globals?.find((g) => g.slug === 'notifications') as GlobalConfig
expect(run(notifications.access?.update, user)).toBe(true)
expect(run(notifications.access?.read, null)).toBe(true)
expect(config.globals?.find((g) => g.slug === 'cookie-settings')?.label).toBe('Cookies')
// untouched globals keep the secure default
expect(run((config.globals?.find((g) => g.slug === 'site-settings') as GlobalConfig).access?.update, user)).toBe(false)
})
test('forms: formOverrides.access wins; a read rule on the Emails field wins', async () => {
const config = await ipalKit({
access: { authCollection: 'users' },
forms: {
formOverrides: {
access: { update: () => true },
fields: ({ defaultFields }) =>
defaultFields.map((f) => ('name' in f && f.name === 'emails' ? ({ ...f, access: { read: () => true } } as Field) : f)),
},
},
i18n,
twoFactor: false,
})(empty())
const forms = config.collections?.find((c) => c.slug === 'forms') as CollectionConfig
expect(run(forms.access?.update, user)).toBe(true)
expect(run(forms.access?.delete, user)).toBe(false)
const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as { access?: { read?: (a: unknown) => boolean } }
expect(emails.access?.read?.({ req: { user } })).toBe(true)
})
})