In the released 1.16.7. The plugin's checks go by the value on the account, but a project's own staff collection
without rules got the admin rules only when ALL its role values were the plugin's; otherwise 'an account of this
collection' could create, change and delete accounts. Measured on bc0fa65 (SQLite; the first shape also on Postgres
and MongoDB, 2FA off and on): with roles user/editor/admin/boss, with a text and with a json roles field, config-time
and added by a later plugin, an account with the role user creates an admin (201) who reads Site integrations, changes
another staff collection's roles and lists the panel's accounts (200 / 200 / 200), takes the admin over and deletes it;
with viewer/editor a viewer creates an editor who gets past the access rule of Site settings.
canHoldStaffRole(collection): a roles select with editor or admin among its values, or a roles field whose values
cannot be listed. Then: create / delete / unlock an admin, update an admin or the account itself, roles only by an
admin. A project's own rules win. A warning at start when no staff account is an admin and such a collection exists.
The built-site fixture gets a config-time and a late collection of that kind; nothing here touches copied collections.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
142 lines
9.7 KiB
TypeScript
142 lines
9.7 KiB
TypeScript
/**
|
|
* 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 { 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 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 }
|
|
const late: Plugin = (config: Config) => ({
|
|
...config,
|
|
collections: [...(config.collections ?? []), { slug: 'late-crew', auth: true, fields: [ROLES] }, { slug: 'late-text', auth: true, fields: [TEXT_ROLES] }],
|
|
})
|
|
/** 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' },
|
|
]
|
|
|
|
/** 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' }] },
|
|
// 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: [
|
|
ipalKit({
|
|
access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text'] },
|
|
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<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 make = (collection: string, email: string, roles: string[]) => payload.create({ collection: collection as never, data: { email, password: PASSWORD, roles } as never })
|
|
const login = async (collection: string, email: string, password = PASSWORD): Promise<null | Session> => {
|
|
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', '[email protected]', ['user'])
|
|
await make('agents', '[email protected]', ['admin'])
|
|
// IPAL_TEST_SHAPE=<slug>: 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', '[email protected]'))!, ...(top === 'admin' ? [(await login(slug, `top@${slug}.example.com`))!] : [])]
|
|
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])
|
|
}
|
|
}
|
|
// role values with neither `editor` nor `admin`: as before — accounts of the collection manage it, never their own roles
|
|
await make('team', '[email protected]', ['member'])
|
|
const member = (await login('team', '[email protected]'))!
|
|
expect((await call('POST', '/team', member, { email: '[email protected]', password: PASSWORD, roles: ['lead'] })).status).toBe(201)
|
|
} finally {
|
|
await server.close()
|
|
await payload.destroy?.()
|
|
}
|
|
}, 120_000)
|
|
}
|