Files
ipal-kit/test/accountRulesOwnRoles.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 7002ebbfa6 M1 review round 2: the transport is no way round, nobody raises its own role, late staff collections
R2-1 the SMTP password is bound to server, port and user whatever the transport says; the transport alone is not bound.
R2-2 where the plugin's update rule is in force the roles field is closed for the account itself
     (the plugin's roles: only an admin; roles of the project's own: never one's own).
R2-3 auth collections a later plugin adds get the account rules, the password rule and the first-user endpoint when
     the config goes live; a staff slug that is not an auth collection stops the start.
R2-4 smtpRequireTls is taken out: the branch adds no field, column or collection.
Also: read (a staff account) and unlock (an admin) defaults on staff collections (accounts.staffOnlyRead);
doctor staff-own-roles and read / unlock in staff-accounts-open; r1 NULL against the default, also inside a row;
r2 bound values compared exactly.

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

126 lines
7.8 KiB
TypeScript

/**
* A project with role values of its OWN and no `access` option (review of M1, M1-6): the account rules must not
* lock it out of its own accounts after an upgrade — and must still keep accounts of other collections away.
* 2FA on, as on a real site. Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI /
* IPAL_TEST_MONGO_URI.
*/
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 { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { staffCollectionsOpenToOthers } from '../src/modules/access/selfRegistration.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
import { totp } from './http/totp.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const PASSWORD = 'a-long-test-password-1'
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
let server: TestServer
let payload: Payload
type Session = Record<string, string>
const call = (pathname: string, session: Session, method: string, body?: unknown) =>
fetch(`${server.url}/api${pathname}`, { body: body === undefined ? undefined : JSON.stringify(body), headers: { 'content-type': 'application/json', ...session }, method })
const idOf = async (collection: string, email: string) => (await payload.find({ collection: collection as never, where: { email: { equals: email } } })).docs[0]?.id
/** A full login: password, and for the 2FA collection the code. */
const login = async (collection: string, email: string): Promise<Session> => {
const res = await call(`/${collection}/login`, {}, 'POST', { email, password: PASSWORD })
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
if (collection !== 'users') {return { authorization: `JWT ${body.token}` }}
await payload.update({ collection: 'users' as never, data: { totpSecret: TOTP_SECRET } as never, where: { email: { equals: email } } })
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('; ') }
}
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
// the project's own staff collection: its own role values, no access rules, no `access` option below
{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['superadmin', 'writer'] }] },
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase('accounts_own_roles'),
editor: lexicalEditor(),
plugins: [ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
test('the first account registers; accounts of the collection create, change and delete accounts as before the upgrade', async () => {
expect((await call('/users/first-register', {}, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['superadmin'] })).status).toBe(200)
const boss = await login('users', '[email protected]')
// the first M1 cut: 403 — the plugin looked for one of ITS roles and found none
expect((await call('/users', boss, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
const writer = await login('users', '[email protected]')
// the project's roles are the project's to enforce: inside the collection nothing changed
expect((await call('/users', writer, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
const third = await idOf('users', '[email protected]')
expect((await call(`/users/${third}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200)
expect((await call(`/users/${third}`, boss, 'DELETE')).status).toBe(200)
})
// Review round 2 (R2-2): the plugin cannot rank the project's roles, but one thing it can hold: nobody changes its OWN.
test('an account does not change its own roles; another account of the collection does (the project\'s rules narrow that)', async () => {
const writer = await login('users', '[email protected]')
const id = await idOf('users', '[email protected]')
const roles = async () => ((await payload.findByID({ id: id as never, collection: 'users' as never })) as { roles?: string[] }).roles
await call(`/users/${id}`, writer, 'PATCH', { roles: ['superadmin'] })
await call('/users?where[email][equals][email protected]', writer, 'PATCH', { roles: ['superadmin'] })
expect(await roles()).toEqual(['writer'])
const boss = await login('users', '[email protected]')
expect((await call(`/users/${id}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200)
expect(await roles()).toEqual(['superadmin'])
await payload.update({ id: id as never, collection: 'users' as never, data: { roles: ['writer'] } as never })
})
test('an account of another collection, a half-signed-in one and nobody stay out', async () => {
expect((await call('/customers', {}, 'POST', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
const visitor = await login('customers', '[email protected]')
const halfRes = await call('/users/login', {}, 'POST', { email: '[email protected]', password: PASSWORD })
const half: Session = { authorization: `JWT ${((await halfRes.json()) as { token: string }).token}` } // the password only
const victim = await idOf('users', '[email protected]')
for (const [who, session] of [['visitor', visitor], ['password only', half], ['anonymous', {}]] as [string, Session][]) {
expect([who, (await call('/users', session, 'POST', { email: `by-${who.replace(' ', '-')}@example.com`, password: PASSWORD, roles: ['superadmin'] })).status]).toEqual([who, 403])
expect([who, (await call(`/users/${victim}`, session, 'PATCH', { password: 'taken-over-password-1' })).status]).toEqual([who, 403])
expect([who, (await call(`/users/${victim}`, session, 'DELETE')).status]).toEqual([who, 403])
}
expect((await call('/users/login', {}, 'POST', { email: '[email protected]', password: 'taken-over-password-1' })).status).not.toBe(200)
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
})
test('a staff collection that does not exist stops the start, with the slug and the fix', async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('accounts_ghost'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
await expect(getPayload({ config, key: 'ghost' })).rejects.toThrow(/"ghost-staff"[\s\S]*no auth collection with that slug[\s\S]*staffCollections/)
})