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

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

90 lines
5.5 KiB
TypeScript

/**
* 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)
}