The panel opens for editor and above by default: Payload's access.admin on the collection that carries the roles. An account that holds only `user` sees "Unauthorized" there; the API is not touched. The rule looks at the role, not at the second factor, so the 2FA screens stay reachable. accounts.panelRole: 'user' | false (everyone, as before) | 'admin'; accounts: false turns the account rules off; the project's own access.admin wins. At start the log says how many accounts the rule keeps out, and is an error when it keeps everyone out. Co-Authored-By: Claude Fable 5.2 <[email protected]>
133 lines
7.2 KiB
TypeScript
133 lines
7.2 KiB
TypeScript
/**
|
|
* 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<string, string>
|
|
const call = (pathname: string, session: Session = {}, init: RequestInit = {}) =>
|
|
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...session, ...(init.headers as Record<string, string> | 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<Session> => {
|
|
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<string, unknown>) => 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: '[email protected]', roles: ['admin'] })
|
|
await make('users', { email: '[email protected]', roles: ['editor'] })
|
|
await make('users', { email: '[email protected]', roles: ['user'] })
|
|
await make('customers', { email: '[email protected]' })
|
|
})
|
|
|
|
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', '[email protected]'))).toBe(true)
|
|
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(true)
|
|
expect(await canAccessAdmin(await login('users', '[email protected]'))).toBe(false)
|
|
expect(await canAccessAdmin(await login('customers', '[email protected]'))).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', '[email protected]')
|
|
const me = (await (await call('/users/me', session)).json()) as { user?: { email?: string } }
|
|
expect(me.user?.email).toBe('[email protected]')
|
|
})
|
|
|
|
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<string, unknown>, incoming: Partial<Config> = {}) =>
|
|
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)
|
|
})
|
|
})
|