/** * M1 account rules over real HTTP (SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / * IPAL_TEST_MONGO_URI): who may open the panel, who may create an account, what a password must be. */ import type { Config, Payload } from 'payload' import { lexicalEditor } from '@payloadcms/richtext-lexical' import os from 'os' import path from 'path' import { getPayload } from 'payload' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js' import { ipalKit } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer, type TestServer } from './http/server.js' vi.mock('server-only', () => ({})) const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } const PASSWORD = 'a-long-test-password-1' let server: TestServer let payload: Payload type Session = Record const call = (pathname: string, session: Session = {}, init: RequestInit = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...session, ...(init.headers as Record | undefined) } }) const post = (pathname: string, body: unknown, session: Session = {}) => call(pathname, session, { body: JSON.stringify(body), method: 'POST' }) const login = async (collection: string, email: string, password = PASSWORD): Promise => { const body = (await (await post(`/${collection}/login`, { email, password })).json()) as { token?: string } if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)} return { authorization: `JWT ${body.token}` } } const make = (collection: string, data: Record) => payload.create({ collection: collection as never, data: { password: PASSWORD, ...data } as never }) beforeAll(async () => { const config = buildTestConfig({ admin: { user: 'users' }, collections: [ { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'members', auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, ], db: testDatabase('accounts'), editor: lexicalEditor(), plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: 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?.() }) describe('the lowest role stays out of the admin panel (accounts.panelRole)', () => { const canAccessAdmin = async (session: Session) => Boolean(((await (await call('/access', session)).json()) as { canAccessAdmin?: boolean }).canAccessAdmin) beforeAll(async () => { await make('users', { email: 'admin@example.com', roles: ['admin'] }) await make('users', { email: 'editor@example.com', roles: ['editor'] }) await make('users', { email: 'plain@example.com', roles: ['user'] }) await make('customers', { email: 'visitor@example.com' }) }) test('Payload reports panel access for an admin and an editor, not for a plain user or a visitor account', async () => { expect(await canAccessAdmin(await login('users', 'admin@example.com'))).toBe(true) expect(await canAccessAdmin(await login('users', 'editor@example.com'))).toBe(true) expect(await canAccessAdmin(await login('users', 'plain@example.com'))).toBe(false) expect(await canAccessAdmin(await login('customers', 'visitor@example.com'))).toBe(false) expect(await canAccessAdmin({})).toBe(false) }) test('the API is not touched: the plain user still logs in and reads its own account', async () => { const session = await login('users', 'plain@example.com') const me = (await (await call('/users/me', session)).json()) as { user?: { email?: string } } expect(me.user?.email).toBe('plain@example.com') }) test('the start-up count: how many accounts are below the panel role', async () => { expect(await countBelowPanelRole(payload, 'users', 'editor')).toEqual({ all: 3, below: 1 }) expect(await countBelowPanelRole(payload, 'users', 'admin')).toEqual({ all: 3, below: 2 }) }) }) describe('accounts.panelRole: the config', () => { const build = (options: Record, incoming: Partial = {}) => ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config) const adminRule = (config: Config) => config.collections!.find((c) => c.slug === 'users')!.access?.admin test('on by default at editor; a role, false and accounts: false change it', async () => { expect(resolvePanelRole(undefined)).toBe('editor') expect(resolvePanelRole('admin')).toBe('admin') expect(resolvePanelRole('user')).toBeNull() // the lowest role = everyone, as before expect(resolvePanelRole(false)).toBeNull() expect(() => resolvePanelRole('boss' as never)).toThrow(/panelRole must be one of/) expect(adminRule(await build({}))).toBeTypeOf('function') expect(adminRule(await build({ accounts: { panelRole: 'user' } }))).toBeUndefined() expect(adminRule(await build({ accounts: { panelRole: false } }))).toBeUndefined() expect(adminRule(await build({ accounts: false }))).toBeUndefined() // without `access` there are no roles to ask about expect(adminRule(await ipalKit({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined() }) test("the project's own rule wins: on its own collection, and through access.authAccess", async () => { const mine = () => true const own = await build({}, { collections: [{ slug: 'users', access: { admin: mine }, auth: true, fields: [] }] } as never) expect(adminRule(own)).toBe(mine) const injected = await build({ access: { authAccess: { admin: mine }, authCollection: 'users' } }) expect(adminRule(injected)).toBe(mine) // the project's own collection without a rule gets the plugin's const plain = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never) expect(adminRule(plain)).toBeTypeOf('function') }) test('the rule looks at the role, not at the second factor, and only at staff accounts', () => { const source = { staffCollections: ['users'] } const ask = (user: unknown, minimum?: 'admin' | 'editor') => panelAccess(minimum)({ req: { payload: source, user } } as never) expect(ask({ collection: 'users', roles: ['editor'] })).toBe(true) expect(ask({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] })).toBe(true) // still owes its code: the 2FA screens are part of the panel expect(ask({ collection: 'users', roles: ['user'] })).toBe(false) expect(ask({ collection: 'users', roles: [] })).toBe(false) expect(ask({ collection: 'users' })).toBe(false) expect(ask({ collection: 'customers', roles: ['admin'] })).toBe(false) expect(ask(null)).toBe(false) expect(ask({ collection: 'users', roles: ['editor'] }, 'admin')).toBe(false) }) })