Files
ipal-kit/test/accountCopyTableSuite.ts
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

286 lines
20 KiB
TypeScript

/**
* The copy rules as ONE table (review round 4 of the follow-ups: "a rule that cannot widen").
*
* A plugin listed after iapl copies staff collections, reuses their access objects, wraps their rules, writes
* rules of its own next to them — every shape the reviews of 1.16.7's follow-ups tried (zzcopy3's table, R4-1, F-1,
* F-2, G-1, G-2, H-1, J-1, J-2). For every shape, every kind of account and every operation two things must hold:
*
* 1. NOT WIDER THAN 1.16.7. What an account may do is measured as a number (0 / 1, or how many documents it
* reads) and compared with the same measurement taken on the released 1.16.7
* (test/fixtures/copyRulesBaseline.json, written by this suite with IPAL_COPY_BASELINE=write on that tree).
* 2. NOT WIDER THAN THE PLUGIN'S RULE for that collection: nobody from outside, no account of another staff
* collection that is not an admin, nobody raises its own role, and — on every shape — the account with the
* same id in the ORIGINAL collection is not "the account itself" (the one thing 1.16.7 itself had open).
*
* The plugin never replaces a rule on these collections; it puts its own in front (bothAllow). So both hold by
* construction, and this table is the proof on real HTTP. SQLite by default; Postgres / MongoDB with the usual
* variables; 2FA off and on (one file each).
*/
import type { CollectionConfig, Config, Field, Payload, Plugin } from 'payload'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { expect, test } from 'vitest'
import { iapl } 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 BASELINE = path.resolve(import.meta.dirname, 'fixtures/copyRulesBaseline.json')
const MARK = Symbol.for('ipal.staffRule')
const roles = (options: string[], extra: Record<string, unknown> = {}): Field => ({ name: 'roles', type: 'select', hasMany: true, options, saveToJWT: true, ...extra }) as Field
const PLUGIN = ['user', 'editor', 'admin']
const MORE = ['user', 'editor', 'admin', 'boss']
const note: Field = { name: 'note', type: 'text' }
const nobody = () => false
/** A function with a hand-made mark, as deliberate code could write one. */
const forged = <T extends (...args: never[]) => unknown>(fn: T, mark: Record<string, unknown>): T => {
Object.defineProperty(fn, MARK, { configurable: true, value: { self: fn, ...mark } })
return fn
}
/** Shapes that are NOT named in `access.staffCollections`. */
const NOT_STAFF = ['nonstaff', 'crewnon', 'crossopt', 'ownvalsnon', 'teamnon']
const late: Plugin = (config: Config) => {
const of = (slug: string) => (config.collections ?? []).find((c) => c.slug === slug)!
const a = of('agents')
const acc = a.access!
const optOut = { ...a.custom, ipal: { accountRules: false } }
const shapes: CollectionConfig[] = [
{ ...a, slug: 'plain' },
{ ...a, slug: 'ownrules', access: { ...acc, create: nobody, delete: nobody, read: ({ req }) => ((req.user as { roles?: string[] } | null)?.roles?.includes('admin') ? { email: { equals: '[email protected]' } } : false), update: nobody } },
{ ...a, slug: 'ownfield', fields: [roles(PLUGIN, { access: { update: nobody } }), note] },
{ ...a, slug: 'optout', custom: optOut },
{ ...a, slug: 'nonstaff' },
{ ...of('users'), slug: 'userscopy' },
{ ...of('proj'), slug: 'projcopy' },
{ ...a, slug: 'lesscopy', access: { create: acc.create } },
// one rule of the original used for other operations
{ ...a, slug: 'crossop', access: { ...acc, read: acc.create, update: acc.create } },
{ ...a, slug: 'crossopt', access: { ...acc, read: acc.create, update: acc.create } },
// wrappers that are not the plugin's
{ ...a, slug: 'proxied', access: { ...acc, create: new Proxy(acc.create!, { apply: nobody }), read: new Proxy(acc.read!, { apply: nobody }), update: new Proxy(acc.update!, { apply: nobody }) } },
{ ...a, slug: 'protod', access: { ...acc, update: Object.setPrototypeOf(() => false, acc.update!) as never } },
{ ...a, slug: 'mimic', access: { ...acc, update: Object.defineProperties(() => false, Object.getOwnPropertyDescriptors(acc.update!)) as never } },
{ ...a, slug: 'bound', access: { ...acc, update: acc.update!.bind(null) } },
{ ...a, slug: 'wrapnarrow', access: { ...acc, read: async (x) => Boolean(await acc.read!(x)) && Boolean((x.req.user as { roles?: string[] } | null)?.roles?.includes('admin')), update: async (x) => Boolean(await acc.update!(x)) && Boolean((x.req.user as { roles?: string[] } | null)?.roles?.includes('admin')) } },
{ ...a, slug: 'whererule', access: { ...acc, read: () => ({ email: { equals: '[email protected]' } }), update: () => ({ email: { equals: '[email protected]' } }) } },
{ ...a, slug: 'frozen', access: Object.freeze({ ...acc, update: Object.freeze(() => false) }) },
{ ...a, slug: 'shared1' },
{ ...a, slug: 'shared2', access: { ...acc, delete: acc.update } },
{ ...a, slug: 'hookproxy', hooks: { ...a.hooks, beforeOperation: (a.hooks?.beforeOperation ?? []).map((hook) => new Proxy(hook, {})) } },
// the opt-out with rules of its own
{ ...a, slug: 'optopen', access: { ...acc, create: () => true, read: () => true }, custom: optOut },
{ ...a, slug: 'optsame', custom: optOut, fields: [roles(PLUGIN), note] }, // J-2: its own roles field, no field access
{ ...a, slug: 'optvals', custom: optOut, fields: [roles(MORE), note] },
{ ...a, slug: 'optplain', custom: optOut },
// other role values than the original's
{ ...a, slug: 'ownvals', fields: [roles(MORE)] }, // H-1
{ ...a, slug: 'ownvalsnon', fields: [roles(MORE)] },
{ slug: 'freshown', access: { ...acc }, auth: true, fields: [roles(MORE)] },
{ ...a, slug: 'renamed', fields: [roles(['lead', 'member']), note] },
{ ...a, slug: 'noroles', fields: [note] },
{ ...of('crew'), slug: 'crewcopy' },
{ ...of('crew'), slug: 'crewnon' },
{ ...of('crew'), slug: 'crewadmin', fields: [roles(PLUGIN)] },
{ ...of('team'), slug: 'teamcopy' },
{ ...of('team'), slug: 'teamnon' },
{ ...of('team'), slug: 'teamadmin', fields: [roles(PLUGIN)] }, // J-1: "an account of the collection" on a collection with `admin`
{ slug: 'teamfresh', access: { ...of('team').access }, auth: true, fields: [roles(PLUGIN)] },
// hand-made marks
{ slug: 'forged', access: { create: forged(() => true, { slug: 'forged' }), update: forged(() => false, { slug: 'elsewhere' }) }, auth: true, fields: [roles(PLUGIN)] },
{ ...a, slug: 'handmark', access: { ...acc, update: Object.defineProperty(() => false, MARK, { configurable: true, value: (acc.update as unknown as Record<symbol, unknown>)[MARK] }) as never } },
{ slug: 'liar', access: { create: forged(() => true, { slug: 'agents', kind: 'bogus', operation: 'bogus' }), update: forged(() => false, { slug: 'agents', kind: 'admin', operation: 'update' }) }, auth: true, fields: [roles(PLUGIN)] },
{ slug: 'protoop', access: { create: forged(() => false, { slug: 'agents', kind: 'toString', operation: 'toString' }), read: forged(() => false, { slug: 'agents', kind: 'toString', operation: 'toString' }) }, auth: true, fields: [roles(PLUGIN)] },
]
return { ...config, collections: [...(config.collections ?? []), ...shapes] }
}
type Session = Record<string, string>
type Table = Record<string, number>
/** One Payload instance per test file: run from a file of its own for 2FA off and on. */
export function copyTableSuite(twoFactor: boolean): void {
test(`copies of staff collections: never wider than 1.16.7, never wider than the plugin's rule (2FA on: ${twoFactor})`, async () => {
let shapeSlugs: string[] = []
const capture: Plugin = (config) => {
shapeSlugs = (config.collections ?? []).filter((c) => c.auth).map((c) => c.slug).filter((slug) => !['agents', 'crew', 'customers', 'proj', 'team', 'users'].includes(slug))
return config
}
const staffShapes = (all: string[]) => all.filter((slug) => !NOT_STAFF.includes(slug))
// the slugs are needed for `access.staffCollections` before the late plugin runs: build them once from a dry call
const names = ((late({ collections: [{ slug: 'agents', access: { create: nobody, read: nobody, update: nobody }, auth: true, fields: [] }, { slug: 'users', auth: true, fields: [] }, { slug: 'proj', auth: true, fields: [] }, { slug: 'crew', auth: true, fields: [] }, { slug: 'team', auth: true, fields: [] }] } as never) as Config).collections ?? []).map((c) => c.slug).filter((slug) => !['agents', 'crew', 'proj', 'team', 'users'].includes(slug))
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'agents', auth: true, fields: [roles(PLUGIN), note] },
{ slug: 'crew', auth: true, fields: [roles(['user', 'boss', 'admin'])] },
{ slug: 'team', auth: true, fields: [roles(['lead', 'member'])] },
{ slug: 'proj', access: { update: ({ req }) => (req.user as { email?: string } | null)?.email === '[email protected]' }, auth: true, fields: [roles(PLUGIN)] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'copy_table_2fa' : 'copy_table'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users', staffCollections: ['agents', 'crew', 'team', 'proj', ...staffShapes(names)] },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false,
}),
late,
capture,
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
const payload: Payload = await getPayload({ config })
const server = await startPayloadServer(config)
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 make = async (collection: string, email: string, value: string[] | undefined) => {
try {
return await payload.create({ collection: collection as never, data: { email, password: PASSWORD, ...(value ? { roles: value } : {}) } as never })
} catch {
return null
}
}
const login = async (collection: string, email: string): Promise<null | Session> => {
const body = (await (await call('POST', `/${collection}/login`, {}, { email, password: PASSWORD })).json()) as { token?: string }
return body.token ? { authorization: `JWT ${body.token}` } : null
}
const rolesOf = async (collection: string, id: unknown) => JSON.stringify(((await payload.findByID({ id: id as never, collection: collection as never }).catch(() => null)) as { roles?: unknown } | null)?.roles ?? null)
const reset = (collection: string, id: unknown, data: Record<string, unknown>) => payload.update({ id: id as never, collection: collection as never, data: data as never }).catch(() => null)
try {
// the original's first account: on the SQL adapters it has the same id as the first account of every copy
await make('agents', '[email protected]', ['user'])
await make('agents', '[email protected]', ['admin'])
await call('POST', '/customers', {}, { email: '[email protected]', password: PASSWORD })
const outside: [string, Session][] = [
['anonymous', {}],
['customer', (await login('customers', '[email protected]'))!],
['namesake', (await login('agents', '[email protected]'))!], // an `agents` account with the role user
['agentsAdmin', (await login('agents', '[email protected]'))!],
]
const table: Table = {}
const shapes: Record<string, { adminRules: boolean; hasRoles: boolean; optOut: boolean; staff: boolean }> = {}
for (const slug of shapeSlugs) {
const collection = payload.collections[slug as never].config as CollectionConfig
const field = (collection.fields as { name?: string; options?: unknown[]; type?: string }[]).find((f) => f.name === 'roles')
const options = field?.type === 'select' && Array.isArray(field.options) ? field.options.map((o) => (typeof o === 'string' ? o : (o as { value: string }).value)) : null
const low = field ? [options?.includes('user') ? 'user' : (options?.at(-1) ?? 'user')] : undefined
const top = field ? [options?.includes('admin') ? 'admin' : (options?.[0] ?? 'admin')] : undefined
shapes[slug] = {
adminRules: Boolean(field) && (!options || options.some((o) => o === 'editor' || o === 'admin') || options.every((o) => PLUGIN.includes(o))),
hasRoles: Boolean(field),
optOut: (collection.custom as { ipal?: { accountRules?: unknown } } | undefined)?.ipal?.accountRules === false,
staff: !NOT_STAFF.includes(slug),
}
const mine = await make(slug, `low@${slug}.example.com`, low) // FIRST: the namesake's twin
let victim = await make(slug, `victim@${slug}.example.com`, low)
const boss = await make(slug, `top@${slug}.example.com`, top)
if (!mine || !victim || !boss) {continue} // the shape cannot hold accounts on this tree: nothing to compare
// The shape's own accounts log in at the START of their turn: a password that was put back after another
// actor's turn ends the sessions an account had (and an account that cannot log in has no rows).
const actors: [string, (() => Promise<null | Session>) | Session][] = [...outside, ['ownLow', () => login(slug, `low@${slug}.example.com`)], ['ownTop', () => login(slug, `top@${slug}.example.com`)]]
for (const [actor, who] of actors) {
const session = typeof who === 'function' ? await who() : who
if (!session) {continue}
if (actor === 'ownLow' || actor === 'ownTop') {
// a session that works at all: `me` answers with the account
const me = (await (await call('GET', `/${slug}/me`, session)).json()) as { user?: { email?: string } | null }
table[`${slug} | ${actor} | signedIn`] = me.user?.email ? 1 : 0
}
const set = (action: string, value: number) => {
table[`${slug} | ${actor} | ${action}`] = value
}
const list = await call('GET', `/${slug}?limit=100`, session)
set('read', list.status === 200 ? (((await list.json()) as { totalDocs?: number }).totalDocs ?? 0) : 0)
const made = `made-${actor}@${slug}.example.com`
set('create', (await call('POST', `/${slug}`, session, { email: made, password: PASSWORD, ...(top ? { roles: top } : {}) })).status === 201 ? 1 : 0)
await payload.delete({ collection: slug as never, where: { email: { equals: made } } }).catch(() => null)
set('patchVictim', (await call('PATCH', `/${slug}/${victim.id}`, session, { password: 'taken-over-password-1' })).status === 200 ? 1 : 0)
if (actor !== 'ownTop') {set('patchTop', (await call('PATCH', `/${slug}/${boss.id}`, session, { password: 'taken-over-password-1' })).status === 200 ? 1 : 0)}
// the account with the SAME id as the namesake's own (R4-1)
if (actor !== 'ownLow') {set('patchTwin', (await call('PATCH', `/${slug}/${mine.id}`, session, { password: 'taken-over-password-1' })).status === 200 ? 1 : 0)}
if (actor === 'ownLow') {
if (top) {
const before = await rolesOf(slug, mine.id)
await call('PATCH', `/${slug}/${mine.id}`, session, { roles: top })
await call('PATCH', `/${slug}?where[email][equals]=low@${slug}.example.com`, session, { roles: top })
set('raiseSelf', (await rolesOf(slug, mine.id)) === before ? 0 : 1)
await reset(slug, mine.id, { roles: low })
}
}
if (top) {
const before = await rolesOf(slug, victim.id)
await call('PATCH', `/${slug}/${victim.id}`, session, { roles: top })
set('rolesVictim', (await rolesOf(slug, victim.id)) === before ? 0 : 1)
await reset(slug, victim.id, { roles: low })
}
set('unlock', (await call('POST', `/${slug}/unlock`, session, { email: `victim@${slug}.example.com` })).status === 200 ? 1 : 0)
const gone = (await call('DELETE', `/${slug}/${victim.id}`, session)).status === 200
set('delete', gone ? 1 : 0)
if (gone) {victim = (await make(slug, `victim@${slug}.example.com`, low))!}
// last in its turn: a new password ends the account's own session
if (actor === 'ownLow') {set('ownPassword', (await call('PATCH', `/${slug}/${mine.id}`, session, { password: 'my-own-new-password-1' })).status === 200 ? 1 : 0)}
for (const [id, email] of [[victim.id, `victim@${slug}.example.com`], [boss.id, `top@${slug}.example.com`], [mine.id, `low@${slug}.example.com`]] as [unknown, string][]) {
await reset(slug, id, { email, password: PASSWORD })
}
}
}
expect(Object.keys(table).length).toBeGreaterThan(1000)
// the table measures something: the shapes' own accounts were signed in, and on a plain staff copy staff reads staff
expect(Object.keys(table).filter((key) => key.endsWith('| signedIn') && table[key] === 1).length).toBeGreaterThan(40)
expect(table['plain | ownTop | read']).toBeGreaterThan(0)
if (process.env.IPAL_COPY_BASELINE === 'write') {
writeFileSync(BASELINE, `${JSON.stringify(table, null, 1)}\n`)
return
}
// ── 1. not wider than 1.16.7 ──
expect(existsSync(BASELINE), 'test/fixtures/copyRulesBaseline.json (IPAL_COPY_BASELINE=write on the 1.16.7 tree)').toBe(true)
const baseline = JSON.parse(readFileSync(BASELINE, 'utf8')) as Table
const compared = Object.keys(table).filter((key) => key in baseline)
expect(compared.length).toBeGreaterThan(1000)
expect(Object.keys(shapes).filter((slug) => !compared.some((key) => key.startsWith(`${slug} | `)))).toEqual([]) // every shape is in the baseline
const wider = compared.filter((key) => table[key] > baseline[key]).map((key) => `${key}: ${baseline[key]} → ${table[key]}`)
expect(wider, 'wider than 1.16.7').toEqual([])
// ── 2. not wider than the plugin's rule ──
const over: string[] = []
const must = (key: string, most: number) => {
if (key in table && table[key] > most) {over.push(`${key}: ${table[key]} (at most ${most})`)}
}
const WRITES = ['create', 'patchVictim', 'patchTop', 'patchTwin', 'rolesVictim', 'unlock', 'delete']
for (const [slug, shape] of Object.entries(shapes)) {
// on EVERY shape: the original's account with the same id is not "the account itself", and nobody raises its own role
must(`${slug} | namesake | patchTwin`, 0)
if (shape.hasRoles) {must(`${slug} | ownLow | raiseSelf`, 0)}
if (!shape.staff || shape.optOut) {continue} // its own rules decide the rest (part 1 holds them to 1.16.7)
for (const actor of ['anonymous', 'customer']) {
for (const action of ['read', ...WRITES]) {must(`${slug} | ${actor} | ${action}`, 0)}
}
// a staff account of ANOTHER collection that is not an admin writes nothing
for (const action of WRITES) {must(`${slug} | namesake | ${action}`, 0)}
// where the admin rules apply, the collection's own lowest account writes nothing but itself
if (shape.adminRules) {
for (const action of WRITES.filter((a) => a !== 'patchTwin')) {must(`${slug} | ownLow | ${action}`, 0)}
}
}
expect(over, "wider than the plugin's rule").toEqual([])
} finally {
await server.close()
await payload.destroy?.()
}
}, 600_000)
}