M1-1 the first-user route is the plugin's own endpoint in front of Payload's; nothing is read from the path.
M1-2 the account rules are put on the collections before the 2FA package wraps them.
M1-6 the admin rule only where the roles are the plugin's; other staff collections: an account of that collection.
update / delete get the matching defaults (accounts.adminOnlyWrite); doctor rule staff-accounts-open.
M1-5 access.firstUserAdmin: false with a role below the panel role: the default panel role steps aside, an explicit one is refused.
M1-3 a save that changes the SMTP server, port, user or encryption must send the password again (secrets.reenterOnChange);
new panel field smtpRequireTls.
M1-4 a restore of a version masks the secrets (maskSecretsOnRestore).
M1-7 a refused origin is logged once with the ways to allow it; default ports are normalised.
Minors: m1 day boundary, m3 e-mail check on reset and bulk update, m4 text of 'all', m5 the mask is never kept.
The account suite runs with 2FA off and on.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
99 lines
6.0 KiB
TypeScript
99 lines
6.0 KiB
TypeScript
/**
|
|
* 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 { ipalKit } 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<string, string>
|
|
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<Session> => {
|
|
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: [ipalKit({ 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: '[email protected]', password: PASSWORD, roles: ['superadmin'] })).status).toBe(200)
|
|
const boss = await login('users', '[email protected]')
|
|
// the first M1 cut: 403 — the plugin looked for one of ITS roles and found none
|
|
expect((await call('/users', boss, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
|
|
const writer = await login('users', '[email protected]')
|
|
// the project's roles are the project's to enforce: inside the collection nothing changed
|
|
expect((await call('/users', writer, 'POST', { email: '[email protected]', password: PASSWORD, roles: ['writer'] })).status).toBe(201)
|
|
const third = await idOf('users', '[email protected]')
|
|
expect((await call(`/users/${third}`, boss, 'PATCH', { roles: ['superadmin'] })).status).toBe(200)
|
|
expect((await call(`/users/${third}`, boss, 'DELETE')).status).toBe(200)
|
|
})
|
|
|
|
test('an account of another collection, a half-signed-in one and nobody stay out', async () => {
|
|
expect((await call('/customers', {}, 'POST', { email: '[email protected]', password: PASSWORD })).status).toBe(201)
|
|
const visitor = await login('customers', '[email protected]')
|
|
const halfRes = await call('/users/login', {}, 'POST', { email: '[email protected]', password: PASSWORD })
|
|
const half: Session = { authorization: `JWT ${((await halfRes.json()) as { token: string }).token}` } // the password only
|
|
const victim = await idOf('users', '[email protected]')
|
|
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: '[email protected]', password: 'taken-over-password-1' })).status).not.toBe(200)
|
|
expect(await staffCollectionsOpenToOthers(payload as never)).toEqual([])
|
|
})
|