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
+52 -12
View File
@@ -165,7 +165,16 @@ export type StaffAccountRules = { applied: string[]; ownRoles: boolean; slug?: s
* (`{ ...staff, slug: 'copy' }`) and the marker travels with it; and in `next dev` a collection object can
* outlive a reload in which it became staff.
*/
export type AccountsMarker = { slug: string; staff: boolean }
export type AccountsMarker = {
/**
* The operations that had a rule in the project's config when ipalKit ran (before Payload and the 2FA package
* filled the missing ones). A collection of the config that becomes staff LATER — a plugin listed after ipalKit
* sets `admin.user` to it — keeps exactly those rules; an operation that had none gets the plugin's.
*/
own?: string[]
slug: string
staff: boolean
}
const markerOf = (collection: { custom?: unknown }): AccountsMarker | undefined => {
const marker = (collection.custom as { ipalAccounts?: unknown } | undefined)?.ipalAccounts
return marker && typeof marker === 'object' && typeof (marker as AccountsMarker).slug === 'string' ? (marker as AccountsMarker) : undefined
@@ -223,7 +232,9 @@ const bothAllowField =
* `mode`:
* - `'config'` (ipalKit is running, nothing is sanitized): an operation without a rule gets the plugin's;
* - `'late'` (a staff collection a later plugin added; the config is sanitized, so Payload's default cannot be
* told from a written rule): the plugin's rule in front of every rule;
* told from a written rule): the plugin's rule in front of every rule — except the operations named in `kept`:
* the collection was in the config when ipalKit ran and had a rule of the project's for them then (the marker's
* `own`), so they are left as a rule the project wrote, exactly as at config time;
* - `'copied'` (a late collection that is not staff, or that keeps its own rules — `custom.ipal.accountRules:
* false`): the plugin's rule goes in front ONLY of a rule the plugin wrote for another collection (its mark,
* ruleMark.ts). Such a rule says "an account of the original", "the account itself" = one of the original's;
@@ -231,7 +242,7 @@ const bothAllowField =
* Accepted cost: where a copied rule says "itself" for the ORIGINAL's accounts, the copy's own account cannot
* edit itself (as before this change) — the copying plugin writes the copy's `access.update`.
*/
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, mode: 'config' | 'copied' | 'late' = 'config'): StaffAccountRules {
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, mode: 'config' | 'copied' | 'late' = 'config', kept: string[] = []): StaffAccountRules {
const slug = collection.slug
// the admin rules: where the roles are the plugin's, and wherever an account can hold `editor` or `admin` (canHoldStaffRole)
const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) || canHoldStaffRole(collection)
@@ -263,7 +274,7 @@ function ruleStaffCollection(collection: CollectionConfig, { create = true, plug
if (mode === 'config') {
if (there || !enabled) {continue} // a rule the project wrote
access[operation] = rule // marked when ipalKit finishes (markStaffRules): the 2FA package wraps it first
} else if ((mode === 'late' && enabled) || mark) {
} else if ((mode === 'late' && enabled && !kept.includes(operation)) || mark) {
access[operation] = markedStaffRule(bothAllow(rule, there), slug)
} else {continue}
if (!applied.includes(operation)) {applied.push(operation)}
@@ -272,7 +283,8 @@ function ruleStaffCollection(collection: CollectionConfig, { create = true, plug
// The `roles` field. An account that may update itself would raise itself through a `roles` field without access of
// its own. The guard (the plugin's roles: only an admin changes them; others: never one's own) is put:
// - config: where the plugin's `update` rule is the one in force (it says "the account itself");
// - late: on every staff collection the plugin rules;
// - late: on every staff collection the plugin rules (as at config time, not where the project's own `update`
// rule was kept);
// - on every COPY, whatever the mode — also one that keeps its own rules and one that is not staff: its field came
// without a rule of its own, and its accounts must not write their own roles because the original's could not.
// A rule the field has is kept: the guard goes in front of it only when it is the plugin's rule for another collection.
@@ -282,7 +294,7 @@ function ruleStaffCollection(collection: CollectionConfig, { create = true, plug
const there = roles.access?.update
const fieldMark = staffRuleOf(there)
const foreign = Boolean(fieldMark) && mode !== 'config'
const wanted = mode === 'config' ? write && applied.includes('update') : (mode === 'late' && write) || copied
const wanted = mode === 'config' ? write && applied.includes('update') : (mode === 'late' && write && !kept.includes('update')) || copied
if (foreign || (!there && wanted)) {
// the field object may be shared with the collection this one was copied from — give this one its own
if (mode !== 'config') {roles = ownCopyOfField(collection, roles)}
@@ -316,6 +328,9 @@ function ownCopyOfField(collection: CollectionConfig, field: FieldLike): FieldLi
return copy
}
/** The operations the plugin has a rule for. */
const OPERATIONS = ['create', 'update', 'delete', 'unlock', 'read', 'readVersions']
/** A copy of the field tree down to the `roles` field, so the project's own objects are not changed. */
const copyToRoles = (fields: FieldLike[] | undefined): FieldLike[] | undefined =>
fields?.map((field) => {
@@ -335,7 +350,13 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op
return {
...config,
collections: (config.collections ?? []).map((collection) => {
if (!collection.auth || !staffSlugs.includes(collection.slug)) {return collection}
if (!collection.auth) {return collection}
// Which operations have a rule of the project's NOW — later nobody can tell (Payload and the 2FA package fill
// the missing ones). Kept in the marker for a collection that becomes staff after ipalKit ran.
const own = OPERATIONS.filter((operation) => Boolean((collection.access as Record<string, unknown> | undefined)?.[operation]))
if (!staffSlugs.includes(collection.slug)) {
return { ...collection, custom: { ...collection.custom, ipalAccounts: { slug: collection.slug, own, staff: false } satisfies AccountsMarker } }
}
const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] }
ruleStaffCollection(copy, options, 'config')
return copy
@@ -344,7 +365,16 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op
}
/** What was put on one late auth collection: for the log, which says only what was really done. */
export type LateAdoption = { applied: string[]; firstUser: boolean; password: boolean; slug: string }
export type LateAdoption = {
applied: string[]
firstUser: boolean
/** The operations whose rule from the project's config was left as it is (a config collection that became staff later). */
kept: string[]
/** True when the collection was in the config when ipalKit ran (and became staff afterwards); false when a later plugin added it. */
known: boolean
password: boolean
slug: string
}
/**
* Collections that were not in the config when ipalKit ran — a plugin listed after it added them.
@@ -368,12 +398,16 @@ export function adoptLateAuthCollections(
// a copy; a marker that says "not staff" on a collection that is staff now was made before it was named as one.
const marker = markerOf(collection)
if (marker?.slug === collection.slug && (marker.staff || !staff)) {continue}
const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, password: false }
// In the config when ipalKit ran, not staff then (a later plugin made it the panel's): the rules it had then stay.
const known = marker?.slug === collection.slug
const kept = known && Array.isArray(marker.own) ? marker.own : []
const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, kept: [], known, password: false }
// A staff collection gets the plugin's rules in front of its own. Any other late collection — not staff, or one
// that keeps its own rules — only where it carries a rule the plugin wrote for another collection (a copy).
const ruled = staff && access !== false && custom?.ipal?.accountRules !== false
done.applied = ruleStaffCollection(collection, access === false || !access ? {} : access, ruled ? 'late' : 'copied').applied
collection.custom = { ...collection.custom, ipalAccounts: { slug: collection.slug, staff } satisfies AccountsMarker }
done.kept = ruled ? kept : []
done.applied = ruleStaffCollection(collection, access === false || !access ? {} : access, ruled ? 'late' : 'copied', kept).applied
collection.custom = { ...collection.custom, ipalAccounts: { slug: collection.slug, ...(kept.length ? { own: kept } : {}), staff } satisfies AccountsMarker }
if (staff) {
const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] }
// (a copied collection brings the original's hooks along: the password rule is put once)
@@ -422,7 +456,13 @@ export function markSeenAuthCollections(config: Config, staffSlugs: string[] = [
const marked = markStaffRules(config) // (a no-op where the plugin marked them before its 2FA guard)
return {
...marked,
collections: (marked.collections ?? []).map((c) => (c.auth ? { ...c, custom: { ...c.custom, ipalAccounts: { slug: c.slug, staff: staffSlugs.includes(c.slug) } satisfies AccountsMarker } } : c)),
collections: (marked.collections ?? []).map((c) => {
if (!c.auth) {return c}
// (the rules the project wrote, noted before the 2FA package ran — applyStaffAccountAccess)
const before = markerOf(c)
const own = before?.slug === c.slug && Array.isArray(before.own) ? { own: before.own } : {}
return { ...c, custom: { ...c.custom, ipalAccounts: { slug: c.slug, ...own, staff: staffSlugs.includes(c.slug) } satisfies AccountsMarker } }
}),
}
}
+2 -1
View File
@@ -212,7 +212,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// said exactly: what was put, on which collection
for (const late of lateAccounts) {
const parts = [late.applied.length ? `access rules for ${late.applied.join(', ')}` : '', late.password ? 'the password rule' : '', late.firstUser ? 'the first-user endpoint' : ''].filter(Boolean)
payload.logger.info(`[ipal] "${late.slug}" was added after ipalKit: put on it — ${parts.join('; ')}.`)
const kept = late.kept.length ? ` Its own rules for ${late.kept.join(', ')} are kept as written.` : ''
payload.logger.info(`[ipal] "${late.slug}" ${late.known ? 'became a staff collection after ipalKit ran' : 'was added after ipalKit'}: put on it — ${parts.join('; ')}.${kept}`)
}
}
if (!secondFactorGuard) {return}
+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'] }