A staff collection whose accounts can hold editor or admin gets the admin rules (H-2, J-3)

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]>
This commit is contained in:
Radosław Smoliński
2026-11-25 02:59:44 +01:00
co-authored by Claude Fable 5.2
parent 01219b69d3
commit be2e6d52d9
10 changed files with 318 additions and 10 deletions
+9
View File
@@ -0,0 +1,9 @@
/** The plugin's role values plus one more on a staff collection, 2FA off — see accountRulesAdminValueSuite.ts. */
import { vi } from 'vitest'
import { adminValueSuite } from './accountRulesAdminValueSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
adminValueSuite(false)
+9
View File
@@ -0,0 +1,9 @@
/** The plugin's role values plus one more on a staff collection, 2FA ON — see accountRulesAdminValueSuite.ts. */
import { vi } from 'vitest'
import { adminValueSuite } from './accountRulesAdminValueSuite.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
adminValueSuite(true)
+141
View File
@@ -0,0 +1,141 @@
/**
* 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)
}
+39 -1
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, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js'
import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, 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'
@@ -565,6 +565,19 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(hasPluginRoles(roles([{ label: 'Admin', value: 'admin' }, { label: 'Editor', value: 'editor' }]))).toBe(true)
expect(hasPluginRoles(roles(['superadmin', 'writer']))).toBe(false)
expect(hasPluginRoles(roles(['admin', 'writer']))).toBe(false) // one foreign value: the project's own roles
// …but an account that CAN hold `editor` or `admin` is the plugin's business: the admin rules apply (review H-2, J-3)
expect(canHoldStaffRole(roles(['admin', 'writer']))).toBe(true)
expect(canHoldStaffRole(roles(['user', 'editor', 'admin', 'boss']))).toBe(true)
expect(canHoldStaffRole(roles(['viewer', 'editor']))).toBe(true)
expect(canHoldStaffRole(roles([{ label: 'Admin', value: 'admin' }, { label: 'Boss', value: 'boss' }]))).toBe(true)
expect(canHoldStaffRole(roles(['superadmin', 'writer']))).toBe(false)
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)
expect(canHoldStaffRole(roles([]))).toBe(true)
expect(canHoldStaffRole({ slug: 'x', fields: [{ type: 'row', fields: [{ name: 'roles', type: 'text' }] }] } as never)).toBe(true)
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)
@@ -731,6 +744,31 @@ export function accountRulesSuite(twoFactor: boolean): void {
expect(adminRule(await build({ access: { authCollection: 'users', firstUserAdmin: false }, accounts: { panelRole: false } }))).toBeUndefined()
})
test('staffCollectionsNobodyManages: the admin rules without any admin — for the start-up warning', async () => {
const roles = (options: string[]) => [{ name: 'roles', type: 'select', 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']) } },
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']) } },
}
const withAdmins = (admins: Record<string, number>, fail = false) => ({
collections,
count: async ({ collection }: { collection: string }) => {
if (fail) {throw new Error('cannot query')}
return { totalDocs: admins[collection] ?? 0 }
},
})
// 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'])
// 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([])
})
test('openSignUpCollections: slugs of auth collections an anonymous request may create in', async () => {
const collections = {
customers: { config: { slug: 'customers', access: { create: () => true }, auth: true } },