/** * A project's own staff collection, without access rules of its own, whose accounts CAN hold one of the plugin's * roles that carry rights — although its `roles` field is not the plugin's (in the released 1.16.7: H-2, J-3): * - the plugin's values plus one more (`user, editor, admin, boss`); * - `editor` among values of its own, no `admin` (`viewer, editor`); * - a `roles` field whose values cannot be listed: text, json. * The plugin's checks go by the value on the account, so such an account is a plugin admin / editor. Before, these * collections counted as "roles of the project's own" and got "an account of this collection" for create / update / * delete: an account with the lowest role created an `admin` there and was in everything. Now: the admin rules. * Config-time and added by a later plugin. Real HTTP; SQLite, Postgres, MongoDB. */ import type { Config, Field, 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' const ROLES: Field = { name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true } const TEXT_ROLES: Field = { name: 'roles', type: 'text', hasMany: true } /** The shapes: the lowest role of the collection, and the plugin role an account of it must not be able to hand out. */ const SHAPES: { low: string[]; other?: string[]; slug: string; top: 'admin' | 'editor' }[] = [ { slug: 'crew', low: ['user'], other: ['boss'], top: 'admin' }, { slug: 'late-crew', low: ['user'], other: ['boss'], top: 'admin' }, { slug: 'viewers', low: ['viewer'], top: 'editor' }, { slug: 'text-roles', low: ['user'], other: ['anything'], top: 'admin' }, { slug: 'late-text', low: ['user'], top: 'admin' }, { slug: 'json-roles', low: ['user'], top: 'admin' }, // a relationship with hasMany to documents whose ids are text: at depth 0 the account's `roles` is ['admin'] { slug: 'rel-roles', low: ['user'], other: ['boss'], top: 'admin' }, ] /** * Review of branch A (K-1): `roles` fields that hold ONE value. The plugin counts roles only from an array, so * an account whose `roles` is `'admin'` there is nobody to the plugin: nothing to protect, and the collection's * accounts keep managing each other exactly as on 1.16.7 (Payload's default for its own accounts). */ const SINGLE: { field: Field; low: unknown; slug: string; top: unknown }[] = [ { slug: 'single', field: { name: 'roles', type: 'select', options: ['user', 'editor', 'admin', 'boss'] }, low: 'user', top: 'admin' }, { slug: 'single-plugin', field: { name: 'roles', type: 'select', options: ['user', 'editor', 'admin'] }, low: 'user', top: 'admin' }, // all the plugin's values: admin rules on 1.16.7 { slug: 'single-late', field: { name: 'roles', type: 'select', options: ['user', 'editor', 'admin', 'boss'] }, low: 'user', top: 'admin' }, { slug: 'radio', field: { name: 'roles', type: 'radio', options: ['user', 'admin'] }, low: 'user', top: 'admin' }, { slug: 'text-one', field: { name: 'roles', type: 'text' }, low: 'user', top: 'admin' }, { slug: 'rel-one', field: { name: 'roles', type: 'relationship', relationTo: 'role-names' }, low: 'user', top: 'admin' }, ] const late: Plugin = (config: Config) => ({ ...config, collections: [...(config.collections ?? []), { slug: 'late-crew', auth: true, fields: [ROLES] }, { slug: 'late-text', auth: true, fields: [TEXT_ROLES] }, { slug: 'single-late', auth: true, fields: [SINGLE.find((x) => x.slug === 'single-late')!.field] }], }) /** One Payload instance per test file: run from a file of its own for 2FA off and on. */ export function adminValueSuite(twoFactor: boolean): void { test(`a staff collection whose accounts can hold editor or admin: the admin rules (2FA on: ${twoFactor})`, async () => { const config = buildTestConfig({ admin: { user: 'users' }, collections: [ { slug: 'crew', auth: true, fields: [ROLES] }, { slug: 'agents', auth: true, fields: [{ ...ROLES, options: ['user', 'editor', 'admin'] } as Field] }, { slug: 'viewers', auth: true, fields: [{ ...ROLES, options: ['viewer', 'editor'] } as Field] }, { slug: 'text-roles', auth: true, fields: [TEXT_ROLES] }, { slug: 'json-roles', auth: true, fields: [{ name: 'roles', type: 'json' }] }, { slug: 'role-names', fields: [{ name: 'id', type: 'text' }] }, // role documents with text ids { slug: 'rel-roles', auth: true, fields: [{ name: 'roles', type: 'relationship', hasMany: true, relationTo: 'role-names' }] }, ...SINGLE.filter((x) => x.slug !== 'single-late').map((x) => ({ slug: x.slug, auth: true as const, fields: [x.field] })), // its own values with neither `editor` nor `admin`: the plugin cannot tell who its admins are — unchanged { slug: 'team', auth: true, fields: [{ ...ROLES, options: ['lead', 'member'] } as Field] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, ], db: testDatabase(twoFactor ? 'admin_value_2fa' : 'admin_value'), editor: lexicalEditor(), plugins: [ iapl({ access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text', 'rel-roles', ...SINGLE.map((x) => x.slug)] }, 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, }) 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 make = (collection: string, email: string, roles: unknown) => payload.create({ collection: collection as never, data: { email, password: PASSWORD, roles } as never }) const login = async (collection: string, email: string, password = PASSWORD): Promise => { const body = (await (await call('POST', `/${collection}/login`, {}, { email, password })).json()) as { token?: string } return body.token ? { authorization: `JWT ${body.token}` } : null } const rolesOf = async (collection: string, id: unknown) => ((await payload.findByID({ id: id as never, collection: collection as never })) as { roles?: string[] }).roles try { const agent = await make('agents', 'one@agents.example.com', ['user']) await call('POST', '/customers', {}, { email: 'visitor@example.com', password: PASSWORD }) await make('agents', 'admin@agents.example.com', ['admin']) for (const id of ['user', 'admin', 'boss', 'editor']) {await payload.create({ collection: 'role-names' as never, data: { id } as never })} // IPAL_TEST_SHAPE=: one shape only — for measuring an older tree, where the first open shape stops the run for (const { slug, low, other, top } of SHAPES.filter((shape) => !process.env.IPAL_TEST_SHAPE || shape.slug === process.env.IPAL_TEST_SHAPE)) { // the account the others must not take over: the collection's highest (an admin, or — `viewers` — an editor) const target = await make(slug, `top@${slug}.example.com`, [top]) const mine = await make(slug, `low@${slug}.example.com`, low) if (other) {await make(slug, `other@${slug}.example.com`, other)} for (const email of [`low@${slug}.example.com`, ...(other ? [`other@${slug}.example.com`] : [])]) { const me = (await login(slug, email))! const id = (await payload.find({ collection: slug as never, where: { email: { equals: email } } })).docs[0].id const role = await rolesOf(slug, id) // one object, so a failure shows everything that was open const got = { createTop: (await call('POST', `/${slug}`, me, { email: `made-by-${email}`, password: PASSWORD, roles: [top] })).status, // …and as that account: the secrets global, another staff collection's roles, the panel's accounts, a settings global madeReaches: await (async () => { const made = await login(slug, `made-by-${email}`) if (!made) {return 'no such account'} return [(await call('GET', '/globals/site-integrations', made)).status, (await call('PATCH', `/agents/${agent.id}`, made, { roles: ['admin'] })).status, (await call('GET', '/users', made)).status, (await call('POST', '/globals/site-settings', made, {})).status] })(), ownRoles: await (async () => { await call('PATCH', `/${slug}/${id}`, me, { roles: [top] }) const after = await rolesOf(slug, id) await payload.update({ id: id as never, collection: slug as never, data: { roles: role } as never }) return after })(), takeOverTop: (await call('PATCH', `/${slug}/${target.id}`, me, { password: 'taken-over-password-1' })).status, unlockTop: (await call('POST', `/${slug}/unlock`, me, { email: `top@${slug}.example.com` })).status, // last: it removes the account the other calls are about zDeleteTop: (await call('DELETE', `/${slug}/${target.id}`, me)).status, } expect([slug, email, got]).toEqual([slug, email, { createTop: 403, madeReaches: 'no such account', ownRoles: role, takeOverTop: 403, unlockTop: 403, zDeleteTop: 403 }]) } // what stays: its own password const me = (await login(slug, `low@${slug}.example.com`))! expect([slug, (await call('PATCH', `/${slug}/${mine.id}`, me, { password: 'my-own-new-password-1' })).status]).toEqual([slug, 200]) // who manages the accounts: an admin of the collection where it has one, and an admin of another staff collection const managers = [(await login('agents', 'admin@agents.example.com'))!, ...(top === 'admin' && slug !== 'rel-roles' ? [(await login(slug, `top@${slug}.example.com`))!] : [])] // (over REST a related role arrives as a document, not as 'admin': that account is no admin there) for (const [index, manager] of managers.entries()) { expect([slug, index, (await call('POST', `/${slug}`, manager, { email: `by-manager-${index}@${slug}.example.com`, password: PASSWORD, roles: low })).status, (await call('PATCH', `/${slug}/${mine.id}`, manager, { roles: low })).status]).toEqual([slug, index, 201, 200]) } // an editor of such a collection is not an admin: it creates nobody (the `viewers` shape) if (top === 'editor') { const editor = (await login(slug, `top@${slug}.example.com`))! expect([slug, (await call('POST', `/${slug}`, editor, { email: `by-editor@${slug}.example.com`, password: PASSWORD, roles: ['editor'] })).status]).toEqual([slug, 403]) } } // ── K-1: single-valued `roles` — as on 1.16.7. The value grants nothing, so nothing is closed. ── for (const { slug, low, top } of SINGLE.filter((shape) => !process.env.IPAL_TEST_SHAPE || shape.slug === process.env.IPAL_TEST_SHAPE)) { const boss = await make(slug, `top@${slug}.example.com`, top) const mine = await make(slug, `low@${slug}.example.com`, low) const victim = await make(slug, `victim@${slug}.example.com`, low) const me = (await login(slug, `low@${slug}.example.com`))! const holder = (await login(slug, `top@${slug}.example.com`))! expect([slug, { // an account that holds 'admin' in a single-valued field is not a plugin admin: it opens nothing adminValueReaches: [(await call('GET', '/globals/site-integrations', holder)).status, (await call('PATCH', `/agents/${agent.id}`, holder, { roles: ['admin'] })).status, (await call('GET', '/users', holder)).status], // the collection's accounts manage each other, the lowest and the one holding 'admin' alike create: [(await call('POST', `/${slug}`, me, { email: `by-low@${slug}.example.com`, password: PASSWORD, roles: top })).status, (await call('POST', `/${slug}`, holder, { email: `by-top@${slug}.example.com`, password: PASSWORD, roles: low })).status], patchOther: [(await call('PATCH', `/${slug}/${victim.id}`, me, { password: 'another-long-password-1' })).status, (await call('PATCH', `/${slug}/${victim.id}`, holder, { password: 'another-long-password-2' })).status], zDelete: (await call('DELETE', `/${slug}/${victim.id}`, holder)).status, }]).toEqual([slug, { adminValueReaches: [403, 403, 403], create: [201, 201], patchOther: [200, 200], zDelete: 200 }]) // an account of ANOTHER collection still gets nothing there const outsider = (await login('customers', 'visitor@example.com'))! expect([slug, (await call('POST', `/${slug}`, outsider, { email: `by-visitor@${slug}.example.com`, password: PASSWORD, roles: top })).status, (await call('PATCH', `/${slug}/${boss.id}`, outsider, { password: 'taken-over-password-1' })).status, (await call('GET', `/${slug}`, outsider)).status]).toEqual([slug, 403, 403, 403]) expect(mine.id).toBeDefined() } // role values with neither `editor` nor `admin`: as before — accounts of the collection manage it, never their own roles await make('team', 'member@team.example.com', ['member']) const member = (await login('team', 'member@team.example.com'))! expect((await call('POST', '/team', member, { email: 'new@team.example.com', password: PASSWORD, roles: ['lead'] })).status).toBe(201) } finally { await server.close() await payload.destroy?.() } }, 120_000) }