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]>
This commit is contained in:
Radosław Smoliński
2026-11-25 03:44:25 +01:00
co-authored by Claude Fable 5.2
parent ccc6f85924
commit c3d95988e1
11 changed files with 406 additions and 47 deletions
+1
View File
@@ -33,6 +33,7 @@ export {
canHoldStaffRole,
hasPluginRoles,
openSignUpCollections,
rolesAreAList,
rolesByAdminOnly,
rolesNotOwn,
sameStaffCollectionAccess,
+84 -25
View File
@@ -103,9 +103,32 @@ const roleValues = (collection: Staffish): null | unknown[] => {
return field.options.map((option) => (typeof option === 'string' ? option : (option as { value?: unknown })?.value))
}
/** True when the collection carries the plugin's roles: a `roles` select at the top level of the data (also inside a row or an unnamed tab) whose values are all the plugin's. */
/** Field types that hold ONE value unless `hasMany` says otherwise, and those that never hold a list of role names. */
const SINGLE_UNLESS_MANY = ['select', 'text', 'relationship', 'upload']
const NEVER_A_ROLE_LIST = ['radio', 'number', 'date', 'checkbox', 'email', 'textarea', 'code', 'point']
/**
* True when the collection's `roles` field can put an ARRAY on the account. The plugin's predicates count roles
* only from an array (`getRoles` in predicates.ts): an account whose `roles` is the single value `'admin'` — a
* select or text without `hasMany`, a radio — is nobody to the plugin, so there is nothing of the plugin's to
* protect in such a collection, and its accounts keep managing each other as Payload's default lets them.
* An array: a select, text or relationship with `hasMany` (a relationship to documents with text ids holds those
* ids), json, and any type the plugin does not know.
*/
export function rolesAreAList(collection: Staffish): boolean {
const field = findRolesField(collection.fields as FieldLike[]) as { hasMany?: boolean; type?: string } | undefined
if (!field) {return false}
if (SINGLE_UNLESS_MANY.includes(field.type ?? '')) {return field.hasMany === true}
return !NEVER_A_ROLE_LIST.includes(field.type ?? '')
}
/**
* True when the collection carries the plugin's roles: a `roles` select (at the top level of the data, also inside
* a row or an unnamed tab) with `hasMany` whose values are all the plugin's. Without `hasMany` the value never
* counts as a role (`rolesAreAList`).
*/
export function hasPluginRoles(collection: Staffish): boolean {
return roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false
return rolesAreAList(collection) && (roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false)
}
/**
@@ -115,14 +138,16 @@ export function hasPluginRoles(collection: Staffish): boolean {
* The plugin's predicates go by the VALUE on the account (`isAdmin`, `isEditor`, `userMeetsRole`): an account of
* a staff collection whose roles hold `admin` is a plugin admin, also when the select offers `boss` next to it; one
* that holds `editor` edits the site's settings. So the accounts of such a collection must not be able to hand
* those values out to each other, and the admin rules apply:
* those values out to each other, and the admin rules apply. The field must be able to hold a LIST
* (`rolesAreAList`), and then:
* - a `roles` select with `editor` or `admin` among its options (`user, editor, admin, boss`; `viewer, editor`);
* - a `roles` field whose values cannot be listed — a text or json field, a select without options: anything
* can be written there, `admin` included.
* False without a `roles` field, and for a select whose options hold neither value (`lead, member`).
* - a `roles` field whose values cannot be listed — text, json, a relationship (to documents whose ids are text),
* a select without options: anything can be written there, `admin` included.
* False without a `roles` field, for a single-valued one, and for a select whose options hold neither value
* (`lead, member`).
*/
export function canHoldStaffRole(collection: Staffish): boolean {
if (!findRolesField(collection.fields as FieldLike[])) {return false}
if (!rolesAreAList(collection)) {return false}
const values = roleValues(collection)
return values === null || values.some((value) => value === 'editor' || value === 'admin')
}
@@ -347,33 +372,67 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; read?: Access; readVersions?: Access; unlock?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
type CountingPayload = {
collections: Record<string, { config: CollectionConfig }>
count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }>
find: (args: { collection: string; depth: number; limit: number; overrideAccess: boolean; pagination: boolean }) => Promise<{ docs: unknown[]; hasNextPage?: boolean; totalDocs?: number }>
}
/** How many accounts are read to look for an admin where the database cannot be asked. */
const ADMIN_SCAN_LIMIT = 1000
/**
* Whether a staff collection has an account that is a plugin admin: `true`, `false`, or `null` — could not check.
* Asked the way that is right for the field, never guessed:
* - no `roles` field: every account is an admin → is there an account;
* - a `roles` field that cannot hold a list, or a select whose options do not offer `admin`: none, without a query;
* - a select with `hasMany`: a count in the database;
* - anything else (text, json, a relationship): the accounts are READ and the plugin's own test is applied to the
* value (an array that holds `'admin'`) — a query on such a field answers differently on every database.
*/
async function collectionHasAdmin(payload: CountingPayload, collection: CollectionConfig): Promise<boolean | null> {
const field = findRolesField(collection.fields as FieldLike[]) as { type?: string } | undefined
try {
if (!field) {return (await payload.count({ collection: collection.slug, overrideAccess: true })).totalDocs > 0}
if (!rolesAreAList(collection)) {return false}
const values = roleValues(collection)
if (values && !values.includes('admin')) {return false}
if (values) {
try {
return (await payload.count({ collection: collection.slug, overrideAccess: true, where: { roles: { in: ['admin'] } } })).totalDocs > 0
} catch {
// asked in a way this database does not take: read instead
}
}
const { docs, hasNextPage } = await payload.find({ collection: collection.slug, depth: 0, limit: ADMIN_SCAN_LIMIT, overrideAccess: true, pagination: true })
if (docs.some((doc) => Array.isArray((doc as { roles?: unknown }).roles) && ((doc as { roles: unknown[] }).roles).includes('admin'))) {return true}
return hasNextPage ? null : false // more accounts than were read: not known
} catch {
return null
}
}
/**
* For the start-up line: staff collections that run on the plugin's ADMIN rules (other than `except`, the collection
* with the plugin's own roles) while NO account of any staff collection is a plugin admin — then nobody can create,
* delete or unlock accounts there. Returns their slugs; `[]` when an admin exists, when there is no such
* collection, or when the accounts cannot be counted (a `roles` field that cannot be queried).
* delete or unlock accounts there. Counted collection by collection:
* - `stuck`: those collections, when every staff collection could be checked and none has an admin;
* - `unchecked`: staff collections whose accounts could not be checked — then nothing is claimed (`stuck` is empty)
* unless an admin was found elsewhere, in which case both are empty.
*/
export async function staffCollectionsNobodyManages(
payload: { collections: Record<string, { config: CollectionConfig }>; count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }> },
staffSlugs: string[],
except?: string,
): Promise<string[]> {
export async function staffCollectionsNobodyManages(payload: CountingPayload, staffSlugs: string[], except?: string): Promise<{ stuck: string[]; unchecked: string[] }> {
const staff = staffSlugs.map((slug) => payload.collections?.[slug]?.config).filter((c): c is CollectionConfig => Boolean(c?.auth))
const ruled = staff.filter((c) => {
const rules = (c.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules
return c.slug !== except && rules && !rules.ownRoles && rules.applied.includes('create') && Boolean(findRolesField(c.fields as FieldLike[]))
return c.slug !== except && rules && !rules.ownRoles && rules.applied.includes('create') && rolesAreAList(c)
})
if (!ruled.length) {return []}
try {
for (const c of staff) {
// without a `roles` field every account of a staff collection is an admin to the plugin
const where = findRolesField(c.fields as FieldLike[]) ? { roles: { in: ['admin'] } } : undefined
if ((await payload.count({ collection: c.slug, overrideAccess: true, where })).totalDocs > 0) {return []}
}
} catch {
return [] // cannot tell: say nothing
if (!ruled.length) {return { stuck: [], unchecked: [] }}
const unchecked: string[] = []
for (const c of staff) {
const has = await collectionHasAdmin(payload, c)
if (has) {return { stuck: [], unchecked: [] }}
if (has === null) {unchecked.push(c.slug)}
}
return ruled.map((c) => c.slug).sort()
return unchecked.length ? { stuck: [], unchecked: unchecked.sort() } : { stuck: ruled.map((c) => c.slug).sort(), unchecked: [] }
}
/**
+6 -1
View File
@@ -937,13 +937,18 @@ export const ipalKit = (options: IpalOptions): Plugin => {
}
// Staff collections on the admin rules while no staff account is an admin: nobody can manage their accounts.
if (accounts) {
const stuck = await staffCollectionsNobodyManages(payload as never, staffCollectionSlugs(payload), options.access?.authCollection)
const { stuck, unchecked } = await staffCollectionsNobodyManages(payload as never, staffCollectionSlugs(payload), options.access?.authCollection)
if (stuck.length) {
payload.logger.warn(
`[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in ${stuck.map((s) => `"${s}"`).join(', ')} ` +
"(only an admin does there: the collection's roles can hold \"editor\" or \"admin\"). Give one account the role with a script " +
'(payload.update, Local API), or write the collection\'s own access.create / update / delete rules (docs/access.md "Account rules").',
)
} else if (unchecked.length) {
payload.logger.warn(
`[ipal] Could not check whether an account of ${unchecked.map((s) => `"${s}"`).join(', ')} holds the role "admin" (no other staff account does). ` +
'If none does, nobody can create, delete or unlock accounts in the staff collections that are managed by admins only (docs/access.md "Account rules").',
)
}
}
// The panel role: tell a site how many of its accounts the rule keeps out of the panel.
+49 -7
View File
@@ -26,10 +26,6 @@ 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' },
@@ -38,8 +34,29 @@ const SHAPES: { low: string[]; other?: string[]; slug: string; top: 'admin' | 'e
{ 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 () => {
@@ -51,6 +68,9 @@ export function adminValueSuite(twoFactor: boolean): void {
{ 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: [] },
@@ -60,7 +80,7 @@ export function adminValueSuite(twoFactor: boolean): void {
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text'] },
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,
}),
@@ -74,7 +94,7 @@ export function adminValueSuite(twoFactor: boolean): void {
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 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<null | Session> => {
const body = (await (await call('POST', `/${collection}/login`, {}, { email, password })).json()) as { token?: string }
return body.token ? { authorization: `JWT ${body.token}` } : null
@@ -82,7 +102,9 @@ export function adminValueSuite(twoFactor: boolean): void {
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 call('POST', '/customers', {}, { email: '[email protected]', password: PASSWORD })
await make('agents', '[email protected]', ['admin'])
for (const id of ['user', 'admin', 'boss', 'editor']) {await payload.create({ collection: 'role-names' as never, data: { id } as never })}
// 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)
@@ -119,7 +141,7 @@ export function adminValueSuite(twoFactor: boolean): void {
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`))!] : [])]
const managers = [(await login('agents', '[email protected]'))!, ...(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])
}
@@ -129,6 +151,26 @@ export function adminValueSuite(twoFactor: boolean): void {
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', '[email protected]'))!
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', '[email protected]', ['member'])
const member = (await login('team', '[email protected]'))!
+9
View File
@@ -0,0 +1,9 @@
/** The start-up check for staff collections without an admin, 2FA off — see accountRulesNobodyManagesSuite.ts. */
import { vi } from 'vitest'
import { nobodyManagesSuite } from './accountRulesNobodyManagesSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
nobodyManagesSuite(false)
@@ -0,0 +1,9 @@
/** The start-up check for staff collections without an admin, 2FA ON — see accountRulesNobodyManagesSuite.ts. */
import { vi } from 'vitest'
import { nobodyManagesSuite } from './accountRulesNobodyManagesSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
nobodyManagesSuite(true)
+96
View File
@@ -0,0 +1,96 @@
/**
* 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)
}
+9
View File
@@ -0,0 +1,9 @@
/** A login collection with a single-valued role select, 2FA off — see accountRulesSingleLoginSuite.ts. */
import { vi } from 'vitest'
import { singleLoginSuite } from './accountRulesSingleLoginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
singleLoginSuite(false)
+9
View File
@@ -0,0 +1,9 @@
/** A login collection with a single-valued role select, 2FA ON — see accountRulesSingleLoginSuite.ts. */
import { vi } from 'vitest'
import { singleLoginSuite } from './accountRulesSingleLoginSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
singleLoginSuite(true)
+89
View File
@@ -0,0 +1,89 @@
/**
* The project's own LOGIN collection with a single-valued role select and no rules (review of branch A, K-1):
* `admin.user: 'people'`, no `access` option, `roles` = select `user, editor, admin, boss` WITHOUT hasMany.
* The plugin counts roles only from an array, so nobody there is a plugin admin whatever the field says; on such a
* collection the admin rules would mean that NOBODY can create, change, delete or unlock accounts — the account
* holding `admin` included. It keeps "an account of this collection", as on 1.16.7.
* Real HTTP; SQLite by default, Postgres / MongoDB with the usual variables; 2FA off and on (one file each).
*/
import type { 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 { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer } from './http/server.js'
import { totp } from './http/totp.js'
const PASSWORD = 'a-long-test-password-1'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
/** One Payload instance per test file: run from a file of its own for 2FA off and on. */
export function singleLoginSuite(twoFactor: boolean): void {
test(`a login collection with a single role select: its accounts keep managing each other (2FA on: ${twoFactor})`, async () => {
const config = buildTestConfig({
admin: { user: 'people' },
collections: [
{ slug: 'people', auth: true, fields: [{ name: 'roles', type: 'select', options: ['user', 'editor', 'admin', 'boss'] }] },
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase(twoFactor ? 'single_login_2fa' : 'single_login'),
editor: lexicalEditor(),
plugins: [ipalKit({ 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 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 = (email: string, role: string) => payload.create({ collection: 'people' as never, data: { email, password: PASSWORD, roles: role, ...(twoFactor ? { totpSecret: TOTP_SECRET } : {}) } as never })
/** A full login: with 2FA on, the code too. */
const login = async (collection: string, email: string): Promise<Session> => {
const res = await call('POST', `/${collection}/login`, {}, { email, password: PASSWORD })
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}`)}
if (!twoFactor || collection !== 'people') {return { authorization: `JWT ${body.token}` }}
const cookies = cookiesOf(res)
const verify = await fetch(`${server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), headers: { 'content-type': 'application/json', cookie: cookies.join('; ') }, method: 'POST' })
expect(((await verify.json()) as { ok?: boolean }).ok).toBe(true)
return { cookie: [...cookies, ...cookiesOf(verify)].join('; ') }
}
try {
const victim = await make('[email protected]', 'user')
await make('[email protected]', 'user')
await make('[email protected]', 'boss')
await make('[email protected]', 'admin')
const got: Record<string, unknown> = {}
for (const who of ['low', 'boss', 'admin']) {
const session = await login('people', `${who}@example.com`)
got[who] = {
create: (await call('POST', '/people', session, { email: `by-${who}@example.com`, password: PASSWORD, roles: 'user' })).status,
patch: (await call('PATCH', `/people/${victim.id}`, session, { password: `changed-by-${who}-123456` })).status,
unlock: (await call('POST', '/people/unlock', session, { email: '[email protected]' })).status,
}
}
// as on 1.16.7: every account of the login collection, the one holding `admin` included
const yes = { create: 201, patch: 200, unlock: 200 }
expect(got).toEqual({ admin: yes, boss: yes, low: yes })
expect((await call('DELETE', `/people/${victim.id}`, await login('people', '[email protected]'))).status).toBe(200)
// what is still closed: an account of another collection, and nobody
expect((await call('POST', '/customers', {}, { email: '[email protected]', password: PASSWORD })).status).toBe(201)
const visitor = await login('customers', '[email protected]')
for (const [name, session] of [['a visitor account', visitor], ['nobody', {}]] as [string, Session][]) {
expect([name, (await call('POST', '/people', session, { email: `x-${name.length}@example.com`, password: PASSWORD, roles: 'admin' })).status, (await call('GET', '/people', session)).status]).toEqual([name, 403, 403])
}
} finally {
await server.close()
await payload.destroy?.()
}
}, 120_000)
}
+45 -14
View File
@@ -19,7 +19,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js'
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig, withTotpParts } from './helpers.js'
import { testDatabase } from './http/db.js'
@@ -574,10 +574,19 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(canHoldStaffRole(roles(['Admin', 'administrator', 'user']))).toBe(false) // the values themselves, nothing like them
expect(canHoldStaffRole({ slug: 'x', fields: [] })).toBe(false) // no roles field: nothing to hand out (every account is an admin)
// a field whose values cannot be listed can hold anything
expect(canHoldStaffRole({ slug: 'x', fields: [{ name: 'roles', type: 'text' }] } as never)).toBe(true)
expect(canHoldStaffRole({ slug: 'x', fields: [{ name: 'roles', type: 'json' }] } as never)).toBe(true)
const field = (f: Record<string, unknown>) => ({ slug: 'x', fields: [{ name: 'roles', ...f }] }) as never
expect(canHoldStaffRole(field({ type: 'text', hasMany: true }))).toBe(true)
expect(canHoldStaffRole(field({ type: 'json' }))).toBe(true)
expect(canHoldStaffRole(field({ type: 'relationship', hasMany: true, relationTo: 'role-names' }))).toBe(true) // ids that are text
expect(canHoldStaffRole(field({ type: 'some-type-of-a-plugin' }))).toBe(true) // unknown: assume it can
expect(canHoldStaffRole(roles([]))).toBe(true)
expect(canHoldStaffRole({ slug: 'x', fields: [{ type: 'row', fields: [{ name: 'roles', type: 'text' }] }] } as never)).toBe(true)
expect(canHoldStaffRole({ slug: 'x', fields: [{ type: 'row', fields: [{ name: 'roles', type: 'text', hasMany: true }] }] } as never)).toBe(true)
// Review of branch A (K-1): the plugin counts roles only from an ARRAY. A single-valued field never makes a
// plugin admin, so there is nothing to protect — and the collection's accounts keep managing each other.
for (const single of [{ type: 'select', options: ['user', 'editor', 'admin', 'boss'] }, { type: 'select', hasMany: false, options: ['user', 'editor', 'admin'] }, { type: 'text' }, { type: 'radio', options: ['user', 'admin'] }, { type: 'number' }, { type: 'date' }, { type: 'checkbox' }, { type: 'relationship', relationTo: 'role-names' }, { type: 'upload', relationTo: 'media' }]) {
expect([JSON.stringify(single), rolesAreAList(field(single)), canHoldStaffRole(field(single)), hasPluginRoles(field(single))]).toEqual([JSON.stringify(single), false, false, false])
}
expect([rolesAreAList(field({ type: 'select', hasMany: true, options: ['lead'] })), rolesAreAList(field({ type: 'json' })), rolesAreAList({ slug: 'x', fields: [] })]).toEqual([true, true, false])
expect(hasPluginRoles(roles([]))).toBe(false)
expect(hasPluginRoles({ slug: 'x', fields: [] })).toBe(false)
expect(hasPluginRoles({ slug: 'x', fields: [{ name: 'roles', type: 'text' }] } as never)).toBe(false)
@@ -668,7 +677,7 @@ export function accountRulesSuite(twoFactor: boolean): void {
const narrow = () => false
const where = () => ({ team: { equals: 'a' } })
const hook = () => undefined
const late = { slug: 'late', access: { create: g, delete: narrow, read: g, readVersions: g, unlock: bw, update: where }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', access: {}, options: ['user', 'admin'] }] }
const late = { slug: 'late', access: { create: g, delete: narrow, read: g, readVersions: g, unlock: bw, update: where }, auth: true, endpoints: [{ handler: () => undefined, method: 'post', path: '/first-register' }], fields: [{ name: 'roles', type: 'select', access: {}, hasMany: true, options: ['user', 'admin'] }] }
const seen = { slug: 'users', access: { create: g }, auth: true, custom: { ipalAccounts: true }, endpoints: [], fields: [] }
const visitors = { slug: 'visitors', access: { create: g }, auth: true, endpoints: [], fields: [] }
const asIs = { slug: 'as-is', access: { create: g }, auth: true, custom: { ipal: { accountRules: false } }, endpoints: [], fields: [] }
@@ -745,28 +754,50 @@ export function accountRulesSuite(twoFactor: boolean): void {
})
test('staffCollectionsNobodyManages: the admin rules without any admin — for the start-up warning', async () => {
const roles = (options: string[]) => [{ name: 'roles', type: 'select', options }]
const roles = (options: string[]) => [{ name: 'roles', type: 'select', hasMany: true, options }]
const ruled = { applied: ['create', 'update', 'delete'], ownRoles: false }
const collections = {
crew: { config: { slug: 'crew', auth: true, custom: { ipalAccountRules: ruled }, fields: roles(['user', 'admin', 'boss']) } },
notes: { config: { slug: 'notes', auth: true, custom: { ipalAccountRules: ruled }, fields: [{ name: 'roles', type: 'json' }] } },
team: { config: { slug: 'team', auth: true, custom: { ipalAccountRules: { applied: ['create'], ownRoles: true } }, fields: roles(['lead', 'member']) } },
users: { config: { slug: 'users', auth: true, custom: { ipalAccountRules: ruled }, fields: roles(['user', 'editor', 'admin']) } },
viewers: { config: { slug: 'viewers', auth: true, custom: { ipalAccountRules: ruled }, fields: roles(['viewer', 'editor']) } },
}
const withAdmins = (admins: Record<string, number>, fail = false) => ({
const asked: string[] = []
const site = ({ admins = {}, docs = {}, failCount = [], failFind = [], many = [] }: { admins?: Record<string, number>; docs?: Record<string, unknown[]>; failCount?: string[]; failFind?: string[]; many?: string[] }) => ({
collections,
count: async ({ collection }: { collection: string }) => {
if (fail) {throw new Error('cannot query')}
asked.push(`count ${collection}`)
if (failCount.includes(collection)) {throw new Error('the database does not take this query')}
return { totalDocs: admins[collection] ?? 0 }
},
find: async ({ collection }: { collection: string }) => {
asked.push(`find ${collection}`)
if (failFind.includes(collection)) {throw new Error('cannot read')}
return { docs: docs[collection] ?? [], hasNextPage: many.includes(collection) }
},
})
const ask = (state: Parameters<typeof site>[0], staff: string[]) => staffCollectionsNobodyManages(site(state) as never, staff, 'users')
// nobody is an admin anywhere: the collections on the admin rules, without the plugin's own (it has its own warning)
expect(await staffCollectionsNobodyManages(withAdmins({}) as never, ['users', 'crew', 'team'], 'users')).toEqual(['crew'])
expect(await ask({}, ['users', 'crew', 'team'])).toEqual({ stuck: ['crew'], unchecked: [] })
// an admin in the collection, or in another staff collection, manages it
expect(await staffCollectionsNobodyManages(withAdmins({ crew: 1 }) as never, ['users', 'crew', 'team'], 'users')).toEqual([])
expect(await staffCollectionsNobodyManages(withAdmins({ users: 2 }) as never, ['users', 'crew', 'team'], 'users')).toEqual([])
// nothing on the admin rules; or the accounts cannot be counted: nothing is said
expect(await staffCollectionsNobodyManages(withAdmins({}) as never, ['users', 'team'], 'users')).toEqual([])
expect(await staffCollectionsNobodyManages(withAdmins({}, true) as never, ['users', 'crew'], 'users')).toEqual([])
expect(await ask({ admins: { crew: 1 } }, ['users', 'crew', 'team'])).toEqual({ stuck: [], unchecked: [] })
expect(await ask({ admins: { users: 2 } }, ['users', 'crew', 'team'])).toEqual({ stuck: [], unchecked: [] })
// nothing on the admin rules: nothing is said
expect(await ask({}, ['users', 'team'])).toEqual({ stuck: [], unchecked: [] })
// a select that does not offer `admin` has none — without a query (on Postgres the query for a value outside the enum throws)
asked.length = 0
expect(await ask({ failCount: ['viewers'] }, ['users', 'viewers'])).toEqual({ stuck: ['viewers'], unchecked: [] })
expect(asked).toEqual(['count users'])
// a field the database cannot be asked about (json): the accounts are read and the plugin's own test is applied
expect(await ask({ docs: { notes: [{ roles: ['user'] }, { roles: 'admin' }, { roles: null }] } }, ['users', 'notes'])).toEqual({ stuck: ['notes'], unchecked: [] })
expect(await ask({ docs: { notes: [{ roles: ['user'] }, { roles: ['boss', 'admin'] }] } }, ['users', 'notes'])).toEqual({ stuck: [], unchecked: [] })
// a count that fails falls back to reading; what cannot be checked at all is named, and NOBODY is not claimed
expect(await ask({ docs: { crew: [{ roles: ['admin'] }] }, failCount: ['crew'] }, ['users', 'crew'])).toEqual({ stuck: [], unchecked: [] })
expect(await ask({ failFind: ['notes'] }, ['users', 'crew', 'notes'])).toEqual({ stuck: [], unchecked: ['notes'] })
expect(await ask({ many: ['notes'] }, ['users', 'crew', 'notes'])).toEqual({ stuck: [], unchecked: ['notes'] }) // more accounts than were read
// …but one collection that cannot be checked does not hide an admin found elsewhere
expect(await ask({ admins: { crew: 1 }, failFind: ['notes'] }, ['users', 'notes', 'crew'])).toEqual({ stuck: [], unchecked: [] })
})
test('openSignUpCollections: slugs of auth collections an anonymous request may create in', async () => {