Files
ipal-kit/test/accountRules.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 5d35b2c3f4 M1 (7): a password rule for staff accounts (accounts.password)
When a password is set on a staff collection — a new account, the first-user
screen, a change, a reset by e-mail; panel, API and Local API alike — it must
have at least 12 characters and not be the account's own e-mail address.
Existing passwords are never checked: a shorter one keeps logging in and meets
the rule when it is next changed. accounts.password: { minLength } | false.
No breached-password lookup; checkPassword and the hook are exported.

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

343 lines
22 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 { pbkdf2Sync, randomBytes } from 'node:crypto'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
import { buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from '../src/modules/access/selfRegistration.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: I18nConfig = { 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: 'staff2', auth: true, fields: [] }, // a second staff collection, without roles and without rules
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase('accounts'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, 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?.()
})
// The owner's rule: nobody creates an account for themselves; only the first account of a site, as admin.
describe('no self-registration (accounts.adminOnlyCreate, accounts.firstUserRoute)', () => {
const rolesOf = async (email: string) => ((await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0] as { roles?: string[] } | undefined)?.roles
const count = async (collection: string) => (await payload.count({ collection: collection as never })).totalDocs
test('an empty site: an anonymous request creates no staff account, over REST or GraphQL', async () => {
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['admin'] })).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
const gql = (await (await post('/graphql', { query: `mutation { createUser(data: { email: "[email protected]", password: "${PASSWORD}", roles: [admin] }) { id } }` })).json()) as { errors?: unknown[] }
expect(gql.errors?.length).toBeGreaterThan(0)
expect(await count('users')).toBe(0)
expect(await count('staff2')).toBe(0)
})
test("the first-user route of other empty auth collections is closed — a second STAFF collection included", async () => {
// before: 200 for each of them while empty; a first account in `staff2` would have been staff
expect((await post('/staff2/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect((await post('/members/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect(await count('staff2')).toBe(0)
expect(await count('members')).toBe(0)
})
test('a collection that allows sign-up keeps its routes', async () => {
expect((await post('/customers/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(200)
expect((await post('/customers', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
expect((await post('/members', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
})
test('the first account of the site registers through the first-user route and is an admin; the route then closes', async () => {
const first = await post('/users/first-register', { email: '[email protected]', password: PASSWORD, roles: ['user'] })
expect(first.status).toBe(200)
expect(await rolesOf('[email protected]')).toEqual(['admin'])
expect((await post('/users/first-register', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
expect(await rolesOf('[email protected]')).toBeUndefined()
expect((await post('/users', { email: '[email protected]', password: PASSWORD })).status).toBe(403)
})
test('only an admin creates staff accounts — not an editor, not a plain user, not asking for a role', async () => {
await make('users', { email: '[email protected]', roles: ['editor'] })
await make('users', { email: '[email protected]', roles: ['user'] })
for (const who of ['[email protected]', '[email protected]']) {
const session = await login('users', who)
expect([who, (await post('/users', { email: `by-${who}`, password: PASSWORD, roles: ['admin'] }, session)).status]).toEqual([who, 403])
expect([who, (await post('/staff2', { email: `by-${who}`, password: PASSWORD }, session)).status]).toEqual([who, 403])
}
const admin = await login('users', '[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD, roles: ['editor'] }, admin)).status).toBe(201)
expect(await rolesOf('[email protected]')).toEqual(['editor'])
// an admin of the panel's collection makes the first account of the second staff collection
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, admin)).status).toBe(201)
// a visitor account is nobody here
const visitor = await login('customers', '[email protected]')
expect((await post('/users', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
expect((await post('/staff2', { email: '[email protected]', password: PASSWORD }, visitor)).status).toBe(403)
})
})
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 () => {
const all = (await payload.find({ collection: 'users' as never, limit: 100 })).docs as unknown as { roles?: string[] }[]
const has = (role: string) => all.filter((u) => u.roles?.includes(role)).length
expect(await countBelowPanelRole(payload, 'users', 'editor')).toEqual({ all: all.length, below: all.length - has('admin') - has('editor') })
expect(await countBelowPanelRole(payload, 'users', 'admin')).toEqual({ all: all.length, below: all.length - has('admin') })
expect(has('user')).toBeGreaterThan(0)
})
})
describe('the password rule (accounts.password): twelve characters when a password is set', () => {
let admin: Session
const messageOf = async (res: Response) => JSON.stringify(await res.json())
beforeAll(async () => {
admin = await login('users', '[email protected]')
})
test('a new account: 11 characters refused with a clear message, 12 accepted', async () => {
const short = await post('/users', { email: '[email protected]', password: 'abcdefghijk', roles: ['editor'] }, admin)
expect(short.status).toBe(400)
expect(await messageOf(short)).toMatch(/at least 12 characters/)
expect((await post('/users', { email: '[email protected]', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201)
// counted in characters, not bytes
expect((await post('/users', { email: '[email protected]', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201)
})
test('in Polish for a Polish panel', async () => {
const res = await post('/users', { email: '[email protected]', password: 'krotkie', roles: ['editor'] }, { ...admin, 'accept-language': 'pl' })
expect(res.status).toBe(400)
expect(await messageOf(res)).toMatch(/co najmniej 12 znaków/)
})
test('not the account\'s own e-mail address', async () => {
const same = await post('/users', { email: '[email protected]', password: '[email protected]', roles: ['editor'] }, admin)
expect(same.status).toBe(400)
expect(await messageOf(same)).toMatch(/same as the e-mail/)
})
test('changing a password: checked; changing anything else: not', async () => {
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'tooshort' }), method: 'PATCH' })).status).toBe(400)
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: '[email protected]' }), method: 'PATCH' })).status).toBe(400) // its own address, looked up
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })).status).toBe(200)
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'a-new-long-password' }), method: 'PATCH' })).status).toBe(200)
await login('users', '[email protected]', 'a-new-long-password')
})
test('an EXISTING shorter password keeps logging in — nothing is checked at login', async () => {
// an account as an earlier version left it: a 6-character password, stored the way Payload stored it then
const old = await make('users', { email: '[email protected]', roles: ['editor'] })
const salt = randomBytes(32).toString('hex')
const hash = pbkdf2Sync('short1', salt, 25000, 512, 'sha256').toString('hex')
await payload.db.updateOne({ id: old.id, collection: 'users' as never, data: { hash, salt } as never })
const session = await login('users', '[email protected]', 'short1')
expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('[email protected]')
// the rule meets it the next time the password is changed
expect((await call(`/users/${old.id}`, session, { body: JSON.stringify({ password: 'short2' }), method: 'PATCH' })).status).toBe(400)
})
test('a reset by e-mail is held to the rule too', async () => {
const token = await payload.forgotPassword({ collection: 'users' as never, data: { email: '[email protected]' }, disableEmail: true })
const short = await post('/users/reset-password', { password: 'tooshort', token })
expect(short.status).toBe(400)
expect(await messageOf(short)).toMatch(/at least 12 characters/)
expect((await post('/users/reset-password', { password: 'reset-to-a-long-one', token })).status).toBe(200)
})
test('visitor collections are not touched', async () => {
expect((await post('/customers', { email: '[email protected]', password: 'abc123' })).status).toBe(201)
})
test('the option, the checker and the switch', async () => {
expect(resolvePasswordRule(undefined)).toEqual({ minLength: 12 })
expect(resolvePasswordRule({ minLength: 16 })).toEqual({ minLength: 16 })
expect(resolvePasswordRule(false)).toBeNull()
for (const bad of ['12', 0, -1, 1.5, Number.NaN]) {expect(() => resolvePasswordRule({ minLength: bad as never })).toThrow(/minLength must be/)}
expect(checkPassword('abcdefghijk')).toBe('short')
expect(checkPassword('abcdefghijkl')).toBeNull()
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
const hooks = async (options: Record<string, unknown>) =>
(await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
expect(await hooks({})).toEqual([['customers', 1], ['users', 2]]) // customers: the first-user guard only
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 1], ['users', 1]])
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
})
})
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)
})
})
describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => {
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({
collections: [{ slug: 'staff2', auth: true, fields: [] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'pages', fields: [] }],
secret: 'x',
...incoming,
} as unknown as Config)
const of = (config: Config, slug: string) => config.collections!.find((c) => c.slug === slug)!
test('staff collections without a create rule get the admin rule; a rule the project wrote stays; other collections are not touched', async () => {
const config = await build({})
expect(of(config, 'staff2').access?.create).toBe(staffCreateAccess)
expect(of(config, 'users').access?.create).toBeTypeOf('function') // the injected collection had adminOnly already
expect(String(of(config, 'customers').access?.create)).toContain('true')
expect(of(config, 'pages').access?.create).toBeUndefined()
const mine = () => true
const own = await build({}, { collections: [{ slug: 'users', access: { create: mine }, auth: true, fields: [] }, { slug: 'staff2', auth: true, fields: [] }] } as never)
expect(of(own, 'users').access?.create).toBe(mine)
const ownNoRule = await build({}, { collections: [{ slug: 'users', auth: true, fields: [] }] } as never)
expect(of(ownNoRule, 'users').access?.create).toBe(staffCreateAccess)
})
test('the switches', async () => {
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
const on = await build({})
// staff collections: the first-user guard and the password rule; a visitor collection: the guard only
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([2, 2, 1, 0])
const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all', password: false } })
expect(of(payloadWay, 'staff2').access?.create).toBeUndefined()
expect(guards(payloadWay, 'staff2')).toBe(0)
const off = await build({ accounts: false })
expect(of(off, 'staff2').access?.create).toBeUndefined()
expect(guards(off, 'users')).toBe(0)
await expect(build({ accounts: { firstUserRoute: 'everyone' } })).rejects.toThrow(/firstUserRoute must be/)
// without `access` the rules still apply to the panel's login collection
const noAccess = await ipalKit({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config)
expect(of(noAccess, 'users').access?.create).toBe(staffCreateAccess)
})
test('the first-user guard: the panel collection, a named list, an open collection; nothing else is touched', async () => {
const run = (option: 'panel' | string[], slug: string, create: ((a: { req: { user: unknown } }) => unknown) | undefined, pathname = `/api/${slug}/first-register`, operation = 'create') =>
buildFirstUserGuard(option)({ args: { data: {} }, collection: { slug, access: { create } }, operation, req: { pathname, payload: { config: { admin: { user: 'users' } } }, t: (k: string) => k, user: null } } as never)
await expect(run('panel', 'users', undefined)).resolves.toBeDefined()
await expect(run('panel', 'staff2', ({ req }) => Boolean(req.user))).rejects.toThrow()
await expect(run('panel', 'customers', () => true)).resolves.toBeDefined() // sign-up is open there anyway
await expect(run('panel', 'members', () => { throw new Error('boom') })).rejects.toThrow() // a rule that fails is closed
await expect(run(['staff2'], 'staff2', undefined)).resolves.toBeDefined()
await expect(run(['staff2'], 'users', undefined)).rejects.toThrow() // a list replaces the default
// any other create, and any other operation, is none of its business
await expect(run('panel', 'staff2', undefined, '/api/staff2')).resolves.toBeDefined()
await expect(run('panel', 'staff2', undefined, '/api/staff2/first-register', 'update')).resolves.toBeDefined()
})
test('openSignUpCollections: slugs of auth collections an anonymous request may create in', async () => {
const collections = {
customers: { config: { slug: 'customers', access: { create: () => true }, auth: true } },
members: { config: { slug: 'members', access: { create: ({ req }: { req: { user: unknown } }) => Boolean(req.user) }, auth: true } },
pages: { config: { slug: 'pages', access: { create: () => true } } },
weird: { config: { slug: 'weird', access: { create: () => { throw new Error('x') } }, auth: true } },
}
expect(await openSignUpCollections({ collections } as never)).toEqual(['customers'])
})
})