Files
ipal-kit/test/accountRulesNobodyManagesSuite.ts
T
Radosław SmolińskiandClaude Fable 5.2 c3d95988e1 K-1, K-2: only a roles field that holds a LIST counts; the start-up check asks each collection its own way
K-1 the plugin counts roles only from an array (getRoles). A single-valued roles field — a select, text or
    relationship without hasMany, a radio — never makes a plugin admin, yet canHoldStaffRole said true: on a
    project's own login collection with a single role select nobody could create, change, delete or unlock accounts,
    the account holding admin included. rolesAreAList(collection) is now a precondition of the admin rules. The same
    for hasPluginRoles: a single select whose values are all the plugin's had the admin rules already in 1.16.7 and
    gets 'an account of this collection' now — its accounts manage each other again; the value still grants nothing.
    A relationship with hasMany counts (ids that are text).
K-2 staffCollectionsNobodyManages returns { stuck, unchecked } and checks collection by collection: no query where
    the field cannot hold admin; a count for a select with hasMany; for text / json / relationship the accounts are
    read and the plugin's own test is applied. Where it cannot check it says so and claims nothing.
Tests: the reviewer's shapes over HTTP and the warning's table against a running Payload, 2FA off and on.

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

97 lines
6.6 KiB
TypeScript

/**
* The start-up warning "no staff account holds admin" against a RUNNING Payload (review of branch A, K-2):
* `staffCollectionsNobodyManages` for each shape of `roles` field, in three states — the collection empty, with a
* lowest account, with its top account — and what it must say. It was silent or wrong where a query answers
* differently per database (a value outside a Postgres enum, json on SQL, a relationship). Now each collection is
* checked in the way that is right for its field. SQLite, Postgres, MongoDB.
*/
import type { CollectionConfig, Field, Payload } 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 { staffCollectionsNobodyManages } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
const PASSWORD = 'a-long-test-password-1'
const select = (options: string[], hasMany = true): Field => ({ name: 'roles', type: 'select', hasMany, options }) as Field
/** `adminTop`: its top account IS a plugin admin; `ruled`: the collection runs on the admin rules. */
const SHAPES: { adminTop: boolean; fields: Field[]; low: unknown; ruled: boolean; slug: string; top: unknown }[] = [
{ slug: 'crew', adminTop: true, fields: [select(['user', 'editor', 'admin', 'boss'])], low: ['user'], ruled: true, top: ['admin'] },
{ slug: 'in-tabs', adminTop: true, fields: [{ type: 'tabs', tabs: [{ fields: [select(['user', 'editor', 'admin'])], label: 'Account' }] }], low: ['user'], ruled: true, top: ['admin'] },
{ slug: 'text-many', adminTop: true, fields: [{ name: 'roles', type: 'text', hasMany: true }], low: ['user'], ruled: true, top: ['admin'] },
// no `admin` among the values: nobody in it can be one — the editor is not
{ slug: 'viewers', adminTop: false, fields: [select(['viewer', 'editor'])], low: ['viewer'], ruled: true, top: ['editor'] },
{ slug: 'json-roles', adminTop: true, fields: [{ name: 'roles', type: 'json' }], low: ['user'], ruled: true, top: ['admin'] },
{ slug: 'rel-roles', adminTop: true, fields: [{ name: 'roles', type: 'relationship', hasMany: true, relationTo: 'role-names' }], low: ['user'], ruled: true, top: ['admin'] },
// single-valued: the value never counts, the collection is not on the admin rules, its 'admin' is not an admin
{ slug: 'single', adminTop: false, fields: [select(['user', 'editor', 'admin'], false)], low: 'user', ruled: false, top: 'admin' },
// roles of its own, and a collection with rules of its own: not on the admin rules
{ slug: 'team', adminTop: false, fields: [select(['lead', 'member'])], low: ['member'], ruled: false, top: ['lead'] },
]
/** One Payload instance per test file: run from a file of its own for 2FA off and on. */
export function nobodyManagesSuite(twoFactor: boolean): void {
test(`the start-up check says who has no admin — per collection, on this database (2FA on: ${twoFactor})`, async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
...SHAPES.map(({ slug, fields }): CollectionConfig => ({ slug, auth: true, fields })),
{ slug: 'own-rules', access: { create: () => false, delete: () => false, update: () => false }, auth: true, fields: [select(['user', 'editor', 'admin', 'boss'])] },
{ slug: 'role-names', fields: [{ name: 'id', type: 'text' }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'nobody_2fa' : 'nobody'),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users', staffCollections: [...SHAPES.map((shape) => shape.slug), 'own-rules'] },
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false,
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
const payload: Payload = await getPayload({ config })
const ask = (staff: string[]) => staffCollectionsNobodyManages(payload as never, staff, 'users')
const make = (collection: string, email: string, roles?: unknown) => payload.create({ collection: collection as never, data: { email, password: PASSWORD, ...(roles === undefined ? {} : { roles }) } as never })
try {
for (const id of ['user', 'admin', 'editor']) {await payload.create({ collection: 'role-names' as never, data: { id } as never })}
const said: Record<string, unknown[]> = {}
const should: Record<string, unknown[]> = {}
for (const { slug, adminTop, low, ruled, top } of SHAPES) {
const nobody = { stuck: ruled ? [slug] : [], unchecked: [] }
const states: unknown[] = [await ask(['users', slug])] // empty
await make(slug, `low@${slug}.example.com`, low)
states.push(await ask(['users', slug])) // a lowest account
await make(slug, `top@${slug}.example.com`, top)
states.push(await ask(['users', slug])) // its top account
said[slug] = states
// with the top account: silent where that account is a plugin admin; still "nobody" where it is not
should[slug] = [nobody, nobody, adminTop ? { stuck: [], unchecked: [] } : nobody]
}
expect(said).toEqual(should)
// several collections in one start: each is checked on its own — one that the database cannot be asked about
// does not silence the others, and an admin anywhere answers for all
await payload.delete({ collection: 'crew' as never, where: { email: { equals: '[email protected]' } } })
for (const slug of ['in-tabs', 'text-many', 'json-roles', 'rel-roles']) {await payload.delete({ collection: slug as never, where: { email: { equals: `top@${slug}.example.com` } } })}
const all = ['users', ...SHAPES.map((shape) => shape.slug), 'own-rules']
expect(await ask(all)).toEqual({ stuck: SHAPES.filter((shape) => shape.ruled).map((shape) => shape.slug).sort(), unchecked: [] })
// a collection with rules of its own is not on the admin rules: it is never named
expect((await ask(['users', 'own-rules'])).stuck).toEqual([])
// an admin of the panel's collection: silent everywhere
await make('users', '[email protected]', ['admin'])
expect(await ask(all)).toEqual({ stuck: [], unchecked: [] })
} finally {
await payload.destroy?.()
}
}, 120_000)
}