L-2: a config collection that becomes staff later keeps the rules it had at config time

A collection of the config that is not named as staff and that a plugin listed after
ipalKit makes the panel's (admin.user) was adopted as a late collection: the plugin's
rule went in front of every rule, also the ones the project wrote. The marker now
holds the operations that had a rule at config time (own); those are left as written
when the collection is handled again, and an operation without one gets the plugin's.
The start log tells this case from a collection a later plugin added.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 10:03:31 +01:00
co-authored by Claude Fable 5.2
parent a743479276
commit 20809ba933
6 changed files with 230 additions and 16 deletions
+9
View File
@@ -0,0 +1,9 @@
/** A config collection that a later plugin makes the panel's, 2FA off — see accountRulesLateStaffSuite.ts. */
import { vi } from 'vitest'
import { lateStaffSuite } from './accountRulesLateStaffSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
lateStaffSuite(false)
+9
View File
@@ -0,0 +1,9 @@
/** A config collection that a later plugin makes the panel's, 2FA ON — see accountRulesLateStaffSuite.ts. */
import { vi } from 'vitest'
import { lateStaffSuite } from './accountRulesLateStaffSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
lateStaffSuite(true)
+103
View File
@@ -0,0 +1,103 @@
/**
* A collection of the config that becomes staff LATER (review of the copy rules, L-2): `people` is in the config and
* is not named as staff; a plugin listed after ipalKit sets `admin.user` to it. At config time the plugin saw which
* operations had a rule of the project's (the marker's `own`); when the collection is handled again at start:
* - an operation that HAD a rule keeps it, exactly as written (here `create`: any signed-in account);
* - an operation that had none gets the plugin's rule (on 1.16.7 a visitor account changed and deleted panel
* accounts there: Payload's default).
* Real HTTP; SQLite by default, Postgres / MongoDB with the usual variables; 2FA off and on (one file each).
*/
import type { Config, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer } from './http/server.js'
const PASSWORD = 'a-long-test-password-1'
/** The later plugin: the panel logs in with `people` from now on. */
const panelIsPeople: Plugin = (config: Config) => ({ ...config, admin: { ...config.admin, user: 'people' } })
/** One Payload instance per test file: run from a file of its own for 2FA off and on. */
export function lateStaffSuite(twoFactor: boolean): void {
test(`a config collection a later plugin makes the panel's: its own rules stay, the missing ones are the plugin's (2FA on: ${twoFactor})`, async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'people', access: { create: ({ req }) => Boolean(req.user) }, auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'late_staff_2fa' : 'late_staff'),
editor: lexicalEditor(),
plugins: [
ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
panelIsPeople,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
const payload: Payload = await getPayload({ config })
const server = await startPayloadServer(config)
type Session = Record<string, string>
const call = (method: string, pathname: string, session: Session = {}, body?: unknown) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...session }, method })
const login = async (collection: string, email: string): Promise<Session> => {
const body = (await (await call('POST', `/${collection}/login`, {}, { email, password: PASSWORD })).json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}`)}
return { authorization: `JWT ${body.token}` }
}
const make = (email: string, role: string) => payload.create({ collection: 'people' as never, data: { email, password: PASSWORD, roles: [role] } as never })
const rolesOf = async (id: number | string) => ((await payload.findByID({ id, collection: 'people' as never, overrideAccess: true })) as { roles?: string[] }).roles
try {
// what the plugin wrote down, and what it put
const custom = payload.collections['people' as never].config.custom as { ipalAccountRules?: { applied: string[] }; ipalAccounts?: unknown }
expect(custom.ipalAccounts).toEqual({ slug: 'people', own: ['create'], staff: true })
expect([...custom.ipalAccountRules!.applied].sort()).toEqual(['delete', 'read', 'readVersions', 'roles', 'unlock', 'update'])
const victim = await make('[email protected]', 'user')
const low = await make('[email protected]', 'user')
await make('[email protected]', 'admin')
expect((await call('POST', '/customers', {}, { email: '[email protected]', password: PASSWORD })).status).toBe(201)
const visitor = await login('customers', '[email protected]')
const lowSession = await login('people', '[email protected]')
const adminSession = await login('people', '[email protected]')
const got: Record<string, unknown> = {}
for (const [who, session] of [['nobody', {}], ['visitor', visitor], ['low', lowSession]] as [string, Session][]) {
got[who] = {
create: (await call('POST', '/people', session, { email: `by-${who}@example.com`, password: PASSWORD })).status,
delete: (await call('DELETE', `/people/${victim.id}`, session)).status,
patch: (await call('PATCH', `/people/${victim.id}`, session, { password: `changed-by-${who}-123456` })).status,
read: (await call('GET', '/people', session)).status,
unlock: (await call('POST', '/people/unlock', session, { email: '[email protected]' })).status,
}
}
const no = { create: 403, delete: 403, patch: 403, read: 403, unlock: 403 }
expect(got).toEqual({
low: { ...no, create: 201, read: 200 }, // the plugin's rules: an admin, or the account itself
nobody: no,
// `create` is the project's own rule ("any signed-in account"): kept as written. The rest had no rule: the plugin's.
visitor: { ...no, create: 201 },
})
// the account itself: may edit itself, never its own roles
expect((await call('PATCH', `/people/${low.id}`, lowSession, { roles: ['admin'] })).status).toBe(200)
expect(await rolesOf(low.id)).toEqual(['user'])
// an admin of the collection manages it
expect((await call('PATCH', `/people/${victim.id}`, adminSession, { roles: ['editor'] })).status).toBe(200)
expect(await rolesOf(victim.id)).toEqual(['editor'])
expect((await call('POST', '/people/unlock', adminSession, { email: '[email protected]' })).status).toBe(200)
expect((await call('DELETE', `/people/${victim.id}`, adminSession)).status).toBe(200)
} finally {
await server.close()
await payload.destroy?.()
}
}, 120_000)
}
+55 -3
View File
@@ -680,6 +680,58 @@ export function accountRulesSuite(twoFactor: boolean): void {
// Review round 3 (R3-1): nothing may depend on recognising Payload's default — a production build minifies
// its name away. The functions below have the names a bundler gives them: none that means anything.
// Review of the copy rules (L-2): a collection that WAS in the config and becomes staff later (a later plugin sets
// `admin.user`). The plugin noted at config time which operations had a rule; those stay as written.
test('a config collection that becomes staff later keeps the rules it had at config time', async () => {
const own = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
const rolesField = () => ({ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] })
const { ipalKit } = await import('../src/plugin.js')
const built = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({
admin: { user: 'users' },
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'none', auth: true, fields: [rolesField()] },
{ slug: 'some', access: { create: own, update: own }, auth: true, fields: [rolesField()] },
{ slug: 'pages', fields: [] },
],
secret: 'x',
} as unknown as Config)
const of = (slug: string) => built.collections!.find((c) => c.slug === slug)!
expect(of('none').custom?.ipalAccounts).toEqual({ slug: 'none', own: [], staff: false })
expect(of('some').custom?.ipalAccounts).toEqual({ slug: 'some', own: ['create', 'update'], staff: false })
expect(of('users').custom?.ipalAccounts).toEqual({ slug: 'users', staff: true })
expect(of('pages').custom?.ipalAccounts).toBeUndefined()
// Payload sanitizes: every missing rule is a function now, none with a telling name
const filled = (slug: string) => {
const c = of(slug)
const access = Object.fromEntries(['create', 'update', 'delete', 'unlock', 'read', 'readVersions'].map((operation) => [operation, (c.access as Record<string, unknown>)?.[operation] ?? (({ req }: { req: { user: unknown } }) => Boolean(req.user))]))
return { ...c, access, endpoints: [] }
}
const none = filled('none')
const some = filled('some')
// a copy of it under a new slug brings the marker along: its `own` says nothing about the copy
const copy = { ...filled('some'), slug: 'copy' }
const config = { collections: [none, some, copy] } as never
expect(adoptLateAuthCollections(config, ['none', 'some', 'copy'], { access: {}, firstUserRoute: 'all' })).toEqual([
{ slug: 'none', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: false, kept: [], known: true, password: false },
{ slug: 'some', applied: ['delete', 'unlock', 'read', 'readVersions'], firstUser: false, kept: ['create', 'update'], known: true, password: false },
{ slug: 'copy', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: false, kept: [], known: false, password: false },
])
// the kept rules are the very functions the project wrote; the roles field is not guarded where its own `update` rule stays (as at config time)
expect([(some.access as Record<string, unknown>).create, (some.access as Record<string, unknown>).update]).toEqual([own, own])
expect((some.fields as { access?: unknown }[])[0].access).toBeUndefined()
expect(some.custom?.ipalAccounts).toEqual({ slug: 'some', own: ['create', 'update'], staff: true })
const visitor = { req: { payload: { config: { admin: { user: 'some' }, custom: { ipal: { staffCollections: ['none', 'some', 'copy'] } } } }, user: { id: 1, collection: 'customers' } } } as never
const answers = async (c: { access: Record<string, unknown> }) => Object.fromEntries(await Promise.all(Object.entries(c.access).map(async ([operation, rule]) => [operation, Boolean(await (rule as (a: never) => unknown)(visitor))])))
expect(await answers(none as never)).toEqual({ create: false, delete: false, read: false, readVersions: false, unlock: false, update: false })
expect(await answers(some as never)).toEqual({ create: true, delete: false, read: false, readVersions: false, unlock: false, update: true })
// handled: a second pass changes nothing
expect(adoptLateAuthCollections(config, ['none', 'some', 'copy'], { access: {}, firstUserRoute: 'all' })).toEqual([])
// the opt-out keeps everything; and a collection that never became staff is left alone
const asIs = { ...filled('some'), custom: { ...of('some').custom, ipal: { accountRules: false } } }
expect(adoptLateAuthCollections({ collections: [asIs, filled('none')] } as never, ['some'], { access: {}, firstUserRoute: 'all' })).toEqual([])
})
test('late collections: the plugin\'s rule goes in FRONT of whatever is there, whatever it is called', async () => {
const g = ({ req }: { req: { user: unknown } }) => Boolean(req.user) // Payload's default as a built site holds it: no telling name
const bw = ({ req }: { req: { user: unknown } }) => Boolean(req.user)
@@ -694,9 +746,9 @@ export function accountRulesSuite(twoFactor: boolean): void {
const config = { collections: [late, pages, seen, visitors, asIs] } as never
const staff = { staffCollections: ['users', 'late', 'as-is'] }
expect(adoptLateAuthCollections(config, ['users', 'late', 'as-is'], { beforeOperation: hook })).toEqual([
{ slug: 'late', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: true, password: true },
{ slug: 'visitors', applied: [], firstUser: true, password: false },
{ slug: 'as-is', applied: [], firstUser: true, password: true }, // its own rules as they are: it said so
{ slug: 'late', applied: ['create', 'update', 'delete', 'unlock', 'read', 'readVersions', 'roles'], firstUser: true, kept: [], known: false, password: true },
{ slug: 'visitors', applied: [], firstUser: true, kept: [], known: false, password: false },
{ slug: 'as-is', applied: [], firstUser: true, kept: [], known: false, password: true }, // its own rules as they are: it said so
])
const ask = (operation: keyof typeof late.access, user: unknown) => (late.access[operation] as (a: unknown) => unknown)({ req: { payload: staff, user } })
const admin = { id: 1, collection: 'users', roles: ['admin'] }