From be2e6d52d9876a843c6d1956a97e050e0847a4f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 02:59:44 +0100 Subject: [PATCH] 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 --- reference/e2e/late-staff-fixture.ts | 14 +++ reference/e2e/late-staff.spec.ts | 31 +++++- reference/src/payload.config.ts | 7 +- src/index.ts | 2 + src/modules/access/selfRegistration.ts | 62 ++++++++++- src/plugin.ts | 13 ++- test/accountRulesAdminValue.test.ts | 9 ++ test/accountRulesAdminValue2fa.test.ts | 9 ++ test/accountRulesAdminValueSuite.ts | 141 +++++++++++++++++++++++++ test/accountRulesSuite.ts | 40 ++++++- 10 files changed, 318 insertions(+), 10 deletions(-) create mode 100644 test/accountRulesAdminValue.test.ts create mode 100644 test/accountRulesAdminValue2fa.test.ts create mode 100644 test/accountRulesAdminValueSuite.ts diff --git a/reference/e2e/late-staff-fixture.ts b/reference/e2e/late-staff-fixture.ts index 5d59ff5..e32d7c8 100644 --- a/reference/e2e/late-staff-fixture.ts +++ b/reference/e2e/late-staff-fixture.ts @@ -9,6 +9,18 @@ import type { Config, Plugin } from 'payload' */ export const E2E_LATE_STAFF = process.env.E2E_LATE_STAFF === '1' +/** Slugs the fixture names as staff (payload.config.ts → `access.staffCollections`). */ +export const E2E_STAFF_SLUGS = ['late-staff', 'e2e-crew', 'e2e-late-text'] + +/** + * Listed BEFORE ipalKit: a staff collection of the project's own, without rules, whose roles are the plugin's values + * PLUS one more. `admin` on an account of it makes a plugin admin, so its accounts must not hand that value out. + */ +export const e2eEarlyStaff: Plugin = (config: Config) => + E2E_LATE_STAFF + ? { ...config, collections: [...(config.collections ?? []), { slug: 'e2e-crew', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin', 'boss'], saveToJWT: true }] }] } + : config + export const e2eLateStaff: Plugin = (config: Config) => E2E_LATE_STAFF ? { @@ -17,6 +29,8 @@ export const e2eLateStaff: Plugin = (config: Config) => ...(config.collections ?? []), // no access rules at all: Payload's defaults ("any logged-in user") are what ipalKit must replace { slug: 'late-staff', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], versions: true }, + // a late staff collection whose `roles` is a text field: any value can be written there, `admin` included + { slug: 'e2e-late-text', auth: true, fields: [{ name: 'roles', type: 'text', hasMany: true }] }, { slug: 'e2e-visitors', access: { create: () => true }, auth: true, fields: [] }, ], } diff --git a/reference/e2e/late-staff.spec.ts b/reference/e2e/late-staff.spec.ts index 165f611..fe2e48b 100644 --- a/reference/e2e/late-staff.spec.ts +++ b/reference/e2e/late-staff.spec.ts @@ -1,7 +1,7 @@ import { type APIRequestContext, expect, test } from '@playwright/test' import { randomUUID } from 'node:crypto' -import { totp } from './totp' +import { secondTestAdmin, totp } from './totp' /** * The account rules on a BUILT site, for a staff collection that a plugin listed after ipalKit adds @@ -25,7 +25,8 @@ test.describe('a late staff collection on a built site', () => { const tag = randomUUID().slice(0, 8) // a fully signed-in admin of the panel's collection const admin = await context(playwright, baseURL!) - expect((await admin.post('/api/users/login', { data: { email, password } })).status()).toBe(200) + // (the second test admin: the smoke and back-link specs spend the first one's 2FA attempts) + expect((await admin.post('/api/users/login', { data: { email: secondTestAdmin(email!), password } })).status()).toBe(200) expect((await (await admin.post('/api/verify-totp', { data: { token: totp(secret!) } })).json()).ok).toBe(true) // anonymous: the first-user route of the (possibly empty) late collection, in two spellings @@ -69,6 +70,32 @@ test.describe('a late staff collection on a built site', () => { // a short password is refused there too (the password rule) expect((await admin.post('/api/late-staff', { data: { email: `s-${tag}@example.com`, password: 'tooshort', roles: ['user'] } })).status()).toBe(400) + // Staff collections whose accounts can hold `admin` although the roles are not just the plugin's — a select with + // one more value (in the config), a text field (added by a later plugin): the lowest account does not make an + // admin, take the collection's admin over, or delete it, and reaches nothing an admin reaches. + for (const slug of ['e2e-crew', 'e2e-late-text']) { + const itsAdmin = await admin.post(`/api/${slug}`, { data: { email: `a-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['admin'] } }) + const itsUser = await admin.post(`/api/${slug}`, { data: { email: `u-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['user'] } }) + expect([slug, itsAdmin.status(), itsUser.status()]).toEqual([slug, 201, 201]) + const itsAdminId = (await itsAdmin.json()).doc.id as string + const itsUserId = (await itsUser.json()).doc.id as string + const api = await context(playwright, baseURL!) + expect((await api.post(`/api/${slug}/login`, { data: { email: `u-${tag}@${slug}.example.com`, password: PASSWORD } })).status()).toBe(200) + expect([slug, { + create: (await api.post(`/api/${slug}`, { data: { email: `made-${tag}@${slug}.example.com`, password: PASSWORD, roles: ['admin'] } })).status(), + integrations: (await api.get('/api/globals/site-integrations')).status(), + patch: (await api.patch(`/api/${slug}/${itsAdminId}`, { data: { password: `taken-${PASSWORD}` } })).status(), + users: (await api.get('/api/users')).status(), + // last: it would remove the account the other calls are about + zDelete: (await api.delete(`/api/${slug}/${itsAdminId}`)).status(), + }]).toEqual([slug, { create: 403, integrations: 403, patch: 403, users: 403, zDelete: 403 }]) + await api.patch(`/api/${slug}/${itsUserId}`, { data: { roles: ['admin'] } }) + expect((await (await admin.get(`/api/${slug}/${itsUserId}`)).json()).roles, `${slug}: its own roles`).toEqual(['user']) + expect((await api.patch(`/api/${slug}/${itsUserId}`, { data: { password: `own-${PASSWORD}` } })).status(), `${slug}: its own password`).toBe(200) + for (const id of [itsAdminId, itsUserId]) {expect((await admin.delete(`/api/${slug}/${id}`)).status()).toBe(200)} + await api.dispose() + } + // an admin: everything, and it cleans up expect((await admin.get('/api/late-staff/versions')).status()).toBe(200) expect((await admin.post('/api/late-staff/unlock', { data: { email: `low-${tag}@example.com` } })).status()).toBe(200) diff --git a/reference/src/payload.config.ts b/reference/src/payload.config.ts index 1e4c019..8b05dd3 100644 --- a/reference/src/payload.config.ts +++ b/reference/src/payload.config.ts @@ -19,7 +19,7 @@ import { Pages } from './collections/Pages' import { Posts } from './collections/Posts' // @starter:endif // @starter:if demo -import { E2E_LATE_STAFF, e2eLateStaff } from '../e2e/late-staff-fixture' +import { E2E_LATE_STAFF, E2E_STAFF_SLUGS, e2eEarlyStaff, e2eLateStaff } from '../e2e/late-staff-fixture' // @starter:endif import { contentConfig } from './content.config' import { db } from './db' @@ -56,11 +56,14 @@ export default buildConfig({ sharp, typescript: { outputFile: path.resolve(dirname, 'payload-types.ts') }, plugins: [ + // @starter:if demo + e2eEarlyStaff, // a test fixture, a no-op without E2E_LATE_STAFF=1 (e2e/late-staff-fixture.ts) + // @starter:endif ipalKit({ i18n: i18nConfig, // @starter:if demo // (the staffCollections entry exists only for e2e/late-staff.spec.ts, with E2E_LATE_STAFF=1) - access: { authCollection: 'users', ...(E2E_LATE_STAFF ? { staffCollections: ['late-staff'] } : {}) }, + access: { authCollection: 'users', ...(E2E_LATE_STAFF ? { staffCollections: E2E_STAFF_SLUGS } : {}) }, // @starter:else //: access: { authCollection: 'users' }, // @starter:endif diff --git a/src/index.ts b/src/index.ts index bfb6cc4..e81001b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,11 +30,13 @@ export { applyStaffAccountAccess, bothAllow, buildFirstUserEndpoint, + canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesByAdminOnly, rolesNotOwn, sameStaffCollectionAccess, + staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, diff --git a/src/modules/access/selfRegistration.ts b/src/modules/access/selfRegistration.ts index 0ee6662..b19672a 100644 --- a/src/modules/access/selfRegistration.ts +++ b/src/modules/access/selfRegistration.ts @@ -96,11 +96,35 @@ function findRolesField(fields: FieldLike[] | undefined): FieldLike | undefined return undefined } +/** The values of the collection's `roles` select (at the top level of the data, also inside a row or an unnamed tab), or null when it has none. */ +const roleValues = (collection: Staffish): null | unknown[] => { + const field = findRolesField(collection.fields as FieldLike[]) as { options?: unknown[]; type?: string } | undefined + if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return null} + 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. */ export function hasPluginRoles(collection: Staffish): boolean { - const field = findRolesField(collection.fields as FieldLike[]) as { options?: unknown[]; type?: string } | undefined - if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return false} - return field.options.every((option) => ROLE_HIERARCHY.includes((typeof option === 'string' ? option : (option as { value?: unknown })?.value) as never)) + return roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false +} + +/** + * True when an account of the collection can hold one of the plugin's roles that carry rights — `editor` or + * `admin` — whatever else its `roles` field offers. + * + * 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: + * - 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`). + */ +export function canHoldStaffRole(collection: Staffish): boolean { + if (!findRolesField(collection.fields as FieldLike[])) {return false} + const values = roleValues(collection) + return values === null || values.some((value) => value === 'editor' || value === 'admin') } /** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */ @@ -147,7 +171,8 @@ export type StaffAccountAccessOptions = { */ function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, late = false): StaffAccountRules { const slug = collection.slug - const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) + // the admin rules: where the roles are the plugin's, and wherever an account can hold `editor` or `admin` (canHoldStaffRole) + const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) || canHoldStaffRole(collection) const other = sameStaffCollectionAccess(slug) const access = (collection.access ?? {}) as Record const applied: string[] = [] @@ -322,6 +347,35 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption type LivePayload = { collections: Record; config?: unknown } +/** + * 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). + */ +export async function staffCollectionsNobodyManages( + payload: { collections: Record; count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }> }, + staffSlugs: string[], + except?: string, +): Promise { + 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[])) + }) + 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 + } + return ruled.map((c) => c.slug).sort() +} + /** * Auth collections whose `create` rule lets an anonymous request through — open sign-up. * For the doctor (slugs only). A rule that throws, or needs more than `{ req }`, counts as closed. diff --git a/src/plugin.ts b/src/plugin.ts index 9ac799e..b386bf6 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -15,7 +15,7 @@ import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js' import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js' import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js' -import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, unknownStaffCollections } from './modules/access/selfRegistration.js' +import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js' import { ROLE_HIERARCHY } from './modules/access/types.js' import { applyAdminI18n } from './modules/admin-i18n/apply.js' import { buildAdminImageEndpoints } from './modules/branding/adminImages.js' @@ -935,6 +935,17 @@ export const ipalKit = (options: IpalOptions): Plugin => { 'Every account of the login collection can open the panel. To keep the lowest role out, set access.defaultRole to \'editor\' or drop access.firstUserAdmin: false (docs/access.md "Account rules").', ) } + // 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) + 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").', + ) + } + } // The panel role: tell a site how many of its accounts the rule keeps out of the panel. if (panelRoleFor) { try { diff --git a/test/accountRulesAdminValue.test.ts b/test/accountRulesAdminValue.test.ts new file mode 100644 index 0000000..92db11f --- /dev/null +++ b/test/accountRulesAdminValue.test.ts @@ -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) diff --git a/test/accountRulesAdminValue2fa.test.ts b/test/accountRulesAdminValue2fa.test.ts new file mode 100644 index 0000000..03e825f --- /dev/null +++ b/test/accountRulesAdminValue2fa.test.ts @@ -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) diff --git a/test/accountRulesAdminValueSuite.ts b/test/accountRulesAdminValueSuite.ts new file mode 100644 index 0000000..d0a241e --- /dev/null +++ b/test/accountRulesAdminValueSuite.ts @@ -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 + 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 => { + 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 make('agents', 'admin@agents.example.com', ['admin']) + // 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' ? [(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', '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) +} diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index d913ecf..5812f08 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -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, 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 } },