M1 review round 3: late staff collections without guessing Payload's default; rules survive a dev reload

R3-1 nothing is decided by a function's name any more (a production build renames it): on a collection that
     arrives after ipalKit the plugin's rule is put in FRONT of the rule that is there and both must allow
     (bothAllow). unlock follows the same table. The log says exactly what was put.
R3-2 the adoption walks the live config (payload.config), which Payload swaps first on a dev reload.
R3-3 readVersions gets the read rule on staff collections.
R3-5 a secret that is not text is refused.
Also: the async check of requireSetup.exempt compares the constructor, not its name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:24 +01:00
co-authored by Claude Fable 5.2
parent 3e44863c98
commit 6e0ad26b2c
13 changed files with 288 additions and 72 deletions
+9
View File
@@ -0,0 +1,9 @@
/** A dev reload and a late staff collection, 2FA off — see accountRulesReloadSuite.ts. */
import { vi } from 'vitest'
import { reloadSuite } from './accountRulesReloadSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
reloadSuite(false)
+9
View File
@@ -0,0 +1,9 @@
/** A dev reload and a late staff collection, 2FA ON — see accountRulesReloadSuite.ts. */
import { vi } from 'vitest'
import { reloadSuite } from './accountRulesReloadSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
reloadSuite(true)
+96
View File
@@ -0,0 +1,96 @@
/**
* A dev reload (review round 3, R3-2): Payload swaps `payload.config` and runs no onInit. A staff collection that a
* plugin listed after ipalKit adds must keep the account rules on the new config — with 2FA off and on.
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Config, Payload, Plugin, SanitizedConfig } 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'
const late: Plugin = (config: Config) => ({
...config,
collections: [...(config.collections ?? []), { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }], versions: true }],
})
const makeConfig = (twoFactor: boolean) =>
buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'reload_2fa' : 'reload'),
editor: lexicalEditor(),
plugins: [
ipalKit({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }),
late,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
/** One Payload instance per test file (Payload caches it): run from a file of its own for 2FA off and on. */
export function reloadSuite(twoFactor: boolean): void {
test(`a late staff collection keeps its rules over a dev reload (2FA on: ${twoFactor})`, async () => {
const config = makeConfig(twoFactor)
const payload: Payload = await getPayload({ config })
const server = await startPayloadServer(config)
const call = (method: string, pathname: string, body?: unknown, headers: Record<string, string> = {}) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method })
const round = async (when: string) => {
const tag = `${when.replace(/\W+/g, "-")}-${Math.random().toString(36).slice(2)}`
// an EMPTY late staff collection: its first-user route, in two spellings
const before = (await payload.count({ collection: 'late-staff' as never })).totalDocs
for (const spelling of ['/first-register', '/First-Register']) {
expect([when, spelling, (await call('POST', `/late-staff${spelling}`, { email: `first-${tag}@example.com`, password: PASSWORD, roles: ['admin'] })).status]).toEqual([when, spelling, 403])
}
expect([when, (await payload.count({ collection: 'late-staff' as never })).totalDocs]).toEqual([when, before])
// a visitor account
expect((await call('POST', '/customers', { email: `c-${tag}@example.com`, password: PASSWORD })).status).toBe(201)
const token = ((await (await call('POST', '/customers/login', { email: `c-${tag}@example.com`, password: PASSWORD })).json()) as { token: string }).token
const visitor = { authorization: `JWT ${token}` }
const victim = await payload.create({ collection: 'late-staff' as never, data: { email: `v-${tag}@example.com`, password: PASSWORD, roles: ['user'] } as never })
const got = {
create: (await call('POST', '/late-staff', { email: `x-${tag}@example.com`, password: PASSWORD, roles: ['admin'] }, visitor)).status,
delete: (await call('DELETE', `/late-staff/${victim.id}`, undefined, visitor)).status,
patch: (await call('PATCH', `/late-staff/${victim.id}`, { password: 'taken-over-password-1' }, visitor)).status,
read: (await call('GET', '/late-staff', undefined, visitor)).status,
unlock: (await call('POST', '/late-staff/unlock', { email: `v-${tag}@example.com` }, visitor)).status,
versions: (await call('GET', '/late-staff/versions', undefined, visitor)).status,
}
expect([when, got]).toEqual([when, { create: 403, delete: 403, patch: 403, read: 403, unlock: 403, versions: 403 }])
// the password rule is on the collection too
await expect(payload.create({ collection: 'late-staff' as never, data: { email: `s-${tag}@example.com`, password: 'tooshort', roles: ['user'] } as never })).rejects.toThrow()
await payload.delete({ collection: 'late-staff' as never, where: { email: { contains: tag } } })
}
try {
await round('start')
// what Payload's dev `reload()` does: a NEW sanitized config is assigned first, the collections after it
const next = await makeConfig(twoFactor)
const live = payload as unknown as { collections: Record<string, { config: unknown; customIDType?: unknown }>; config: SanitizedConfig; globals: { config: unknown } }
live.config = next
live.collections = Object.fromEntries(next.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }]))
live.globals = { config: next.globals }
await round('after the reload')
// and once more: a second reload meets a fresh config again
const third = await makeConfig(twoFactor)
live.config = third
live.collections = Object.fromEntries(third.collections.map((c) => [c.slug, { config: c, customIDType: live.collections[c.slug]?.customIDType }]))
live.globals = { config: third.globals }
await round('after a second reload')
} finally {
await server.close()
await payload.destroy?.()
}
}, 120_000)
}
+67 -28
View File
@@ -19,7 +19,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { adoptLateAuthCollections, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { adoptLateAuthCollections, bothAllow, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig, withTotpParts } from './helpers.js'
import { testDatabase } from './http/db.js'
@@ -33,7 +33,7 @@ const latePlugin: Plugin = (config: Config) => ({
...config,
collections: [
...(config.collections ?? []),
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }] },
{ slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'late-members', auth: true, fields: [] },
],
})
@@ -90,7 +90,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
// a staff collection with the project's OWN role values and no rules: the plugin cannot tell who its admins are
{ slug: 'crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['boss', 'worker'] }] },
// a staff collection with the plugin's role values, written by the project, no rules
{ slug: 'agents', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }] },
{ slug: 'agents', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'),
@@ -318,15 +318,28 @@ export function accountRulesSuite(twoFactor: boolean): void {
}
expect([collection, (await call(`/${collection}`, editor)).status]).toEqual([collection, 200]) // staff reads staff
}
// versions hold what the accounts hold (review round 3, R3-3)
await payload.update({ collection: 'agents' as never, data: { roles: ['admin'] } as never, where: { email: { equals: '[email protected]' } } })
for (const collection of ['agents', 'late-staff']) {
for (const [who, session] of [['visitor', visitor], ['anonymous', {}]] as [string, Session][]) {
const res = await call(`/${collection}/versions`, session)
expect([collection, who, res.status]).toEqual([collection, who, 403])
expect(await res.text()).not.toContain('[email protected]')
}
expect([collection, (await call(`/${collection}/versions`, editor)).status]).toEqual([collection, 200])
}
const gql = (await (await post('/graphql', { query: '{ Agents { docs { email } } }' }, visitor)).json()) as { data?: unknown; errors?: unknown[] }
expect(JSON.stringify(gql)).not.toContain('[email protected]')
expect((await post('/agents/unlock', { email: '[email protected]' }, editor)).status).toBe(403)
expect((await post('/agents/unlock', { email: '[email protected]' }, admin)).status).toBe(200)
await make('late-staff', { email: '[email protected]', roles: ['user'] })
expect((await post('/late-staff/unlock', { email: '[email protected]' }, editor)).status).toBe(403) // a late collection: the same table
expect((await post('/late-staff/unlock', { email: '[email protected]' }, admin)).status).toBe(200)
})
// Review round 2 (R2-3): a staff collection a later plugin adds.
test('a staff collection added by a plugin listed after ipalKit has the same rules', async () => {
expect((await payload.count({ collection: 'late-staff' as never })).totalDocs).toBe(0) // the first-user spellings above created nothing
// (the first-user spellings above created nothing: counted there)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, visitor)).status).toBe(403)
expect((await post('/late-staff', { email: '[email protected]', password: PASSWORD, roles: ['admin'] }, editor)).status).toBe(403)
// the password rule is there too
@@ -587,7 +600,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 0, 0])
expect([firstUser(on, 'users'), firstUser(on, 'staff2'), firstUser(on, 'customers'), firstUser(on, 'pages')]).toEqual([1, 1, 1, 0])
const payloadWay = await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false } })
expect(of(payloadWay, 'staff2').access).toEqual({ read: staffReadAccess })
expect(of(payloadWay, 'staff2').access).toEqual({ read: staffReadAccess, readVersions: staffReadAccess })
expect(of(await build({ accounts: { adminOnlyCreate: false, adminOnlyWrite: false, firstUserRoute: 'all', password: false, staffOnlyRead: false } }), 'staff2').access).toBeUndefined()
expect([guards(payloadWay, 'staff2'), firstUser(payloadWay, 'staff2')]).toEqual([0, 0])
// each switch on its own
@@ -634,36 +647,62 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(rolesField(await build({}), 'users').access?.update).toBeTypeOf('function')
})
test('late collections: adopted once, with the same rules; a project\'s own rule and Payload\'s default told apart', () => {
function defaultAccess({ req }: { req: { user: unknown } }) {return Boolean(req.user)} // what a sanitized config holds where nothing was written
const mine = () => true
// 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.
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)
const narrow = () => false
const where = () => ({ team: { equals: 'a' } })
const hook = () => undefined
const late = { slug: 'late', access: { create: defaultAccess, delete: mine, read: defaultAccess, unlock: defaultAccess, update: defaultAccess }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', options: ['user', 'admin'] }] }
const seen = { slug: 'users', access: { create: defaultAccess }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] }
const visitors = { slug: 'visitors', access: { create: defaultAccess }, auth: true, endpoints: [], fields: [] }
const late = { slug: 'late', access: { create: g, delete: narrow, read: g, readVersions: g, unlock: bw, update: where }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', access: {}, options: ['user', 'admin'] }] }
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] }
const visitors = { slug: 'visitors', access: { create: g }, auth: true, endpoints: [], fields: [] }
const asIs = { slug: 'as-is', access: { create: g }, auth: true, custom: { ipal: { accountRules: false } }, endpoints: [], fields: [] }
const pages = { slug: 'pages', access: {}, endpoints: [], fields: [] }
const live = { collections: { late: { config: late }, pages: { config: pages }, users: { config: seen }, visitors: { config: visitors } } } as never
expect(adoptLateAuthCollections(live, ['users', 'late'], { beforeOperation: hook })).toEqual(['late', 'visitors'])
expect(late.access.create).toBe(staffCreateAccess)
expect(late.access.delete).toBe(mine)
expect(late.access.read).toBe(staffReadAccess)
expect(late.access.unlock).toBe(staffCreateAccess)
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
])
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'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const own = { id: 7, collection: 'late', roles: ['user'] }
const customer = { id: 9, collection: 'customers', roles: ['admin'] }
for (const operation of ['create', 'read', 'readVersions', 'update', 'delete', 'unlock'] as const) {
expect([operation, await ask(operation, customer)]).toEqual([operation, false])
expect([operation, await ask(operation, null)]).toEqual([operation, false])
}
expect(await ask('create', editor)).toBe(false)
expect(await ask('create', admin)).toBe(true)
expect(await ask('unlock', editor)).toBe(false) // an admin, as the table in the docs says
expect(await ask('unlock', admin)).toBe(true)
expect(await ask('read', editor)).toBe(true)
expect(await ask('readVersions', editor)).toBe(true)
// a rule of the collection's own is kept, and only ever narrows: both must allow
expect(await ask('delete', admin)).toBe(false)
expect(await ask('update', admin)).toEqual({ team: { equals: 'a' } })
expect(await ask('update', own)).toEqual({ and: [{ id: { equals: 7 } }, { team: { equals: 'a' } }] })
expect((late.fields[0] as { access?: { update?: unknown } }).access?.update).toBe(rolesByAdminOnly)
expect((late as { hooks?: { beforeOperation?: unknown[] } }).hooks?.beforeOperation).toEqual([hook])
expect((late.endpoints[0] as { custom?: { ipalFirstUser?: boolean } }).custom?.ipalFirstUser).toBe(true) // in FRONT of Payload's
expect(late.endpoints).toHaveLength(2)
// a late auth collection that is not staff: the first-user endpoint only
expect(visitors.access.create).toBe(defaultAccess)
expect(visitors.endpoints).toHaveLength(1)
expect(visitors.access.create).toBe(g)
expect(asIs.access.create).toBe(g)
// what ipalKit saw at config time, and what is not an auth collection: untouched
expect(seen.access.create).toBe(defaultAccess)
expect(seen.endpoints).toHaveLength(0)
expect(pages.endpoints).toHaveLength(0)
expect(seen.access.create).toBe(g)
expect([seen.endpoints.length, pages.endpoints.length]).toEqual([0, 0])
// a second call (a request after the start) changes nothing
expect(adoptLateAuthCollections(live, ['users', 'late'], { beforeOperation: hook })).toEqual([])
expect(adoptLateAuthCollections(config, ['users', 'late'], { beforeOperation: hook })).toEqual([])
expect(late.endpoints).toHaveLength(2)
// a staff slug without an auth collection
expect(unknownStaffCollections(live, ['users', 'late', 'pages', 'ghost'])).toEqual(['pages', 'ghost'])
expect(unknownStaffCollections(config, ['users', 'late', 'pages', 'ghost'])).toEqual(['pages', 'ghost'])
// the combiner
expect(await bothAllow(() => true, undefined)({} as never)).toBe(true)
expect(await bothAllow(() => false, () => { throw new Error('not asked') })({} as never)).toBe(false)
})
test('the rules are on the collections BEFORE the 2FA package wraps them', async () => {
@@ -674,7 +713,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
return withTotpParts({ ...c, collections: (c.collections ?? []).map((col) => ({ ...col, access: { create: () => true, delete: () => true, update: () => true, ...col.access } })) }, o.collection)
}
await build({ twoFactor: { issuer: 'A', plugin: factory as never } })
expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'read', 'unlock', 'update'])
expect(Object.keys(seen.staff2 as object).sort()).toEqual(['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])
expect(seen.customers).toEqual({ create: expect.any(Function) })
})
@@ -707,10 +746,10 @@ export function accountRulesSuite(twoFactor: boolean): void {
const collections = {
agents: { config: { slug: 'agents', access: { create: staffCreateAccess, delete: anyone, update: anyone }, auth: true } },
customers: { config: { slug: 'customers', access: { create: () => true, update: anyone }, auth: true } }, // not staff: not its business
users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, read: staffReadAccess, unlock: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } },
users: { config: { slug: 'users', access: { create: staffCreateAccess, delete: staffCreateAccess, read: staffReadAccess, readVersions: staffReadAccess, unlock: staffCreateAccess, update: staffUpdateAccess('users') }, auth: true } },
weird: { config: { slug: 'weird', access: { update: () => { throw new Error('x') } }, auth: true } },
}
expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:read', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:unlock']) // no rule = Payload's default, open; a rule that throws = closed
expect(await staffCollectionsOpenToOthers({ collections, config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['agents', 'weird'] } } } } as never)).toEqual(['agents:delete', 'agents:read', 'agents:readVersions', 'agents:unlock', 'agents:update', 'weird:create', 'weird:delete', 'weird:read', 'weird:readVersions', 'weird:unlock']) // no rule = Payload's default, open; a rule that throws = closed
})
})
}
+3 -3
View File
@@ -512,10 +512,10 @@ describe('ipalKit and the 2FA plugin', () => {
admin: { user: 'users' },
} as Config)
const warnings: string[] = []
const auth = (slug: string) => ({ config: { slug, auth: true, custom: { ipalAccounts: true }, fields: [] } })
const auth = (slug: string) => ({ slug, auth: true, custom: { ipalAccounts: true }, fields: [] })
const payload = {
collections: { partners: auth('partners'), users: auth('users') },
config: { admin: { user: 'users' }, collections: [], custom: config.custom, globals: [] },
collections: {},
config: { admin: { user: 'users' }, collections: [auth('partners'), auth('users')], custom: config.custom, globals: [] },
count: () => ({ totalDocs: 0 }),
find: () => ({ docs: [] }),
findGlobal: () => ({}),
+11
View File
@@ -131,6 +131,17 @@ describe('saving', () => {
expect((await stored()).smtpPassword ?? null).toBeNull()
})
test('a value that is not text is refused, and the stored one stays', async () => {
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP, turnstileSecretKey: TURNSTILE } as never })
for (const notText of [false, 0, 5, {}, { a: 1 }, [SECRET_MASK], ['x']]) {
const res = await save({ smtpPassword: notText })
expect([JSON.stringify(notText), res.status]).toEqual([JSON.stringify(notText), 400])
expect(await res.text()).not.toContain('S3CRET')
expect((await save({ turnstileSecretKey: notText })).status).toBe(400)
}
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
})
test('GraphQL mutation: the mask keeps, a value replaces', async () => {
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP } as never })
let out = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpFromName: "By GraphQL" }) { smtpPassword smtpFromName } }`)