/** * 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 iapl 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 { 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' /** 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: [ iapl({ 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 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 => { 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('victim@example.com', 'user') const low = await make('low@example.com', 'user') await make('admin@example.com', 'admin') expect((await call('POST', '/customers', {}, { email: 'visitor@example.com', password: PASSWORD })).status).toBe(201) const visitor = await login('customers', 'visitor@example.com') const lowSession = await login('people', 'low@example.com') const adminSession = await login('people', 'admin@example.com') const got: Record = {} 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: 'victim@example.com' })).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: 'victim@example.com' })).status).toBe(200) expect((await call('DELETE', `/people/${victim.id}`, adminSession)).status).toBe(200) } finally { await server.close() await payload.destroy?.() } }, 120_000) }