diff --git a/src/index.ts b/src/index.ts index e03f19e..9c0c7e3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,8 @@ export { lightboxNotificationFields } from './globals/Notifications/fields.js' export { applyGlobalOverrides } from './globals/overrides.js' export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js' +export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js' +export type { AccountsOptions } from './modules/access/types.js' export type { AccessOption, Role } from './modules/access/index.js' export { adminOnly, diff --git a/src/modules/access/panelRole.ts b/src/modules/access/panelRole.ts new file mode 100644 index 0000000..6095c7e --- /dev/null +++ b/src/modules/access/panelRole.ts @@ -0,0 +1,60 @@ +import type { BasePayload, CollectionConfig, Config } from 'payload' + +import type { Role } from './types.js' + +import { hasMinimumRole } from './predicates.js' +import { ROLE_HIERARCHY } from './types.js' + +/** + * Who may open the admin panel. + * + * Payload lets every account of the login collection into the panel; what it sees there is + * decided per collection. The lowest role (`user`) is the default for a new account and has + * no business in the panel: by default the panel opens for `editor` and above + * (`accounts.panelRole`). It is Payload's own `access.admin` on the login collection, so the + * API is not touched — a `user` account still logs in over the API and gets what its role allows. + * + * The rule looks at the role only, not at the second factor: an editor who has typed the + * password must still reach the 2FA screens, which are part of the panel. + */ +export const DEFAULT_PANEL_ROLE: Role = 'editor' + +/** `access.admin` for a staff collection: the account holds at least `minimum`. */ +export const panelAccess = + (minimum: Role = DEFAULT_PANEL_ROLE): NonNullable['admin']> => + ({ req }) => + hasMinimumRole(req.user, minimum, req.payload) + +/** `accounts.panelRole` → the role to require, or null when the rule is off (`false`, or the lowest role). */ +export function resolvePanelRole(option: false | Role | undefined): null | Role { + if (option === false) {return null} + const role = option ?? DEFAULT_PANEL_ROLE + if (!ROLE_HIERARCHY.includes(role)) { + throw new Error(`[ipal] accounts.panelRole must be one of ${ROLE_HIERARCHY.join(', ')} or false, got ${JSON.stringify(option)}.`) + } + return role === ROLE_HIERARCHY[0] ? null : role +} + +/** + * Sets `access.admin` on the collection that carries the roles, unless the project wrote its + * own (`access.admin` on its collection, or `access.authAccess.admin` for the injected one). + */ +export function applyPanelRole(config: Config, slug: string, minimum: Role): Config { + return { + ...config, + collections: (config.collections ?? []).map((collection) => + collection.slug === slug && !collection.access?.admin ? { ...collection, access: { ...collection.access, admin: panelAccess(minimum) } } : collection, + ), + } +} + +/** + * How many accounts of the collection are below the panel role (no role, or only lower ones), + * and how many there are. For the start-up line that tells a site what the rule did to it. + */ +export async function countBelowPanelRole(payload: BasePayload, slug: string, minimum: Role): Promise<{ all: number; below: number }> { + const allowed = ROLE_HIERARCHY.slice(ROLE_HIERARCHY.indexOf(minimum)) + const all = (await payload.count({ collection: slug as never, overrideAccess: true })).totalDocs + const able = (await payload.count({ collection: slug as never, overrideAccess: true, where: { roles: { in: [...allowed] } } as never })).totalDocs + return { all, below: Math.max(0, all - able) } +} diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index f091783..e562774 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -8,6 +8,23 @@ export const ROLE_HIERARCHY = ['user', 'editor', 'admin'] as const export type Role = (typeof ROLE_HIERARCHY)[number] +/** + * `ipalKit({ accounts })` — rules for the accounts of the staff collection. On by default + * where they apply; each one has its own switch, `accounts: false` turns them all off. + */ +export type AccountsOptions = { + /** + * The lowest role that may open the admin panel. Default `'editor'`: an + * account that holds only `user` (the default role of a new account) sees + * Payload's "Unauthorized" screen instead of the panel; over the API it + * still gets what its role allows. `'user'` or `false` = every account of + * the collection may open the panel, as before. `'admin'` = admins only. + * Needs `access` (the roles). The project's own `access.admin` on the + * collection (or `access.authAccess.admin`) wins. docs/access.md. + */ + panelRole?: false | Role +} + /** * Access-control options. * diff --git a/src/plugin.ts b/src/plugin.ts index 6b7a962..3b714a5 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -2,6 +2,7 @@ import type { BasePayload, Config, PayloadRequest, Plugin } from 'payload' import { deepMergeSimple } from 'payload/shared' +import type { AccountsOptions, Role } from './modules/access/types.js' import type { ResolvedAdminMeta } from './modules/branding/adminMeta.js' import type { IpalOptions, TotpPluginFactory } from './types.js' @@ -12,6 +13,7 @@ import { applyGlobalOverrides } from './globals/overrides.js' import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js' +import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js' import { applyAdminI18n } from './modules/admin-i18n/apply.js' import { buildAdminImageEndpoints } from './modules/branding/adminImages.js' import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js' @@ -194,6 +196,10 @@ export const ipalKit = (options: IpalOptions): Plugin => { /** 2FA collection when "setup required" is on — its existing accounts get their setup window in onInit. */ let setupRequiredFor: null | string = null let setupWindowHours = 0 + /** accounts.panelRole in force: the collection and the role, for the start-up line. */ + let panelRoleFor: { role: Role; slug: string } | null = null + /** `accounts: false` turns every account rule off. */ + const accounts: AccountsOptions | null = options.accounts === false ? null : (options.accounts ?? {}) /** requireSetup.setupNotice / statusField (on unless switched off). */ let setupNotice = true let statusField = false @@ -550,6 +556,14 @@ export const ipalKit = (options: IpalOptions): Plugin => { // for accounts of a staff collection (staffCollectionSlugs). const staff = [...new Set([options.access.authCollection, ...(options.access.staffCollections ?? [])])] config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: staff } } + // Account rules (accounts.*): the lowest role stays out of the panel. + const panelRole = accounts ? resolvePanelRole(accounts.panelRole) : null + const rolesSlug = options.access.authCollection + // the project's own access.admin (or access.authAccess.admin) wins + if (panelRole && !(config.collections ?? []).find((c) => c.slug === rolesSlug)?.access?.admin) { + config = applyPanelRole(config, rolesSlug, panelRole) + panelRoleFor = { slug: rolesSlug, role: panelRole } + } } // For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config // says now, under a token; the Payload instance takes the entry over when the config goes live @@ -836,6 +850,25 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } } + // The panel role: tell a site how many of its accounts the rule keeps out of the panel. + if (panelRoleFor) { + try { + const { all, below } = await countBelowPanelRole(payload, panelRoleFor.slug, panelRoleFor.role) + if (all && below === all) { + payload.logger.error( + `[ipal] No account of "${panelRoleFor.slug}" has the role "${panelRoleFor.role}" or higher, so NOBODY can open the admin panel ` + + '(accounts.panelRole). Give an account the role with a script (payload.update, Local API), or set accounts: { panelRole: false } and redeploy (docs/access.md "Account rules").', + ) + } else if (below) { + payload.logger.warn( + `[ipal] ${below} account(s) of "${panelRoleFor.slug}" are below the role "${panelRoleFor.role}" and cannot open the admin panel ` + + '(accounts.panelRole). Give them a higher role, or set accounts: { panelRole: \'user\' } (docs/access.md "Account rules").', + ) + } + } catch { + /* a database that is not ready must not stop the start */ + } + } // Accounts from before "setup required": their window starts now, not at their creation date. if (setupRequiredFor) { const started = await backfillSetupFrom(payload, setupRequiredFor) diff --git a/src/types.ts b/src/types.ts index 754beb7..e8d3754 100644 --- a/src/types.ts +++ b/src/types.ts @@ -13,7 +13,7 @@ export type TotpPluginFactory = (options: { totp: { issuer: string } }) => Plugin import type { GlobalOverrides } from './globals/overrides.js' -import type { AccessOption } from './modules/access/types.js' +import type { AccessOption, AccountsOptions } from './modules/access/types.js' import type { AdminMetaOptions, AgencyOption } from './modules/branding/adminMeta.js' import type { ConsentLogOptions } from './modules/consent/consentLog.js' import type { CookieScannerOptions } from './modules/consent/scanner/types.js' @@ -34,6 +34,11 @@ import type { StatsOptions } from './modules/stats/collection.js' * Passed by the client project in payload.config.ts. */ export type IpalOptions = { + /** + * Rules for the accounts of the staff collection: who may open the panel + * (`panelRole`). `false` = none of them. docs/access.md "Account rules". + */ + accounts?: AccountsOptions | false /** * Role-based access control. Injects a fixed `roles` field * (admin > editor > user) into the client's auth collection. diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index 27e5570..9c8a135 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -48,7 +48,15 @@ describe('injected auth collection', () => { const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })( empty({ collections: [own] as CollectionConfig[] }), ) - expect(config.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access) + const access = config.collections?.find((c) => c.slug === 'users')?.access + // what the project wrote stays its own… + expect(access?.read).toBe(own.access.read) + // …and the account rules fill in only what it left out (accounts.*; `accounts: false` = nothing added) + expect(access?.admin).toBeTypeOf('function') + const untouched = await ipalKit({ access: { authCollection: 'users' }, accounts: false, i18n, twoFactor: false })( + empty({ collections: [own] as CollectionConfig[] }), + ) + expect(untouched.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access) }) }) diff --git a/test/accountRules.test.ts b/test/accountRules.test.ts new file mode 100644 index 0000000..d427a72 --- /dev/null +++ b/test/accountRules.test.ts @@ -0,0 +1,132 @@ +/** + * 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) + }) +})