/** * 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 { iapl } 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 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 => { 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: [iapl({ 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: 'boss@example.com', password: PASSWORD, roles: ['superadmin'] })).status).toBe(200) const boss = await login('users', 'boss@example.com') // the first M1 cut: 403 — the plugin looked for one of ITS roles and found none expect((await call('/users', boss, 'POST', { email: 'writer@example.com', password: PASSWORD, roles: ['writer'] })).status).toBe(201) const writer = await login('users', 'writer@example.com') // the project's roles are the project's to enforce: inside the collection nothing changed expect((await call('/users', writer, 'POST', { email: 'third@example.com', password: PASSWORD, roles: ['writer'] })).status).toBe(201) const third = await idOf('users', 'third@example.com') 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', 'writer@example.com') const id = await idOf('users', 'writer@example.com') 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]=writer@example.com', writer, 'PATCH', { roles: ['superadmin'] }) expect(await roles()).toEqual(['writer']) const boss = await login('users', 'boss@example.com') 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: 'visitor@example.com', password: PASSWORD })).status).toBe(201) const visitor = await login('customers', 'visitor@example.com') const halfRes = await call('/users/login', {}, 'POST', { email: 'writer@example.com', password: PASSWORD }) const half: Session = { authorization: `JWT ${((await halfRes.json()) as { token: string }).token}` } // the password only const victim = await idOf('users', 'boss@example.com') 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: 'boss@example.com', 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: [iapl({ 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/) })