F1: roles count only for accounts of a staff collection, in every exported predicate and access builder (isAdmin, isEditor, hasMinimumRole, adminOnly, adminOrEditor, requireRole, adminOrSelf, adminOrSelfIn, the Field variants, the roles field) and first in userMeetsRole. An account of another auth collection with its own roles: ['admin'] gets nothing. Staff collections: admin.user, access.authCollection, access.staffCollections. Predicates take req.payload as an optional last argument and otherwise use the staff collections of the config ipalKit built in this process. F2: every endpoint @clocklimited/payload-2fa registers answers accounts of the 2FA collection only (setup-totp wrote the secret into the 2FA collection under the caller's id, whatever collection the caller came from); remove and the admin reset/remove endpoints also need the second factor. F3: per-entity opt-out honoured, operation by operation: the package's custom.totp.disableAccessWrapper and ipal-kit's custom.ipal.secondFactor (passed on to the package); the package's global disableAccessWrapper too. F4: a no-user auth strategy on the 2FA collection guards the live config at the start of each request, so entities from plugins listed after ipalKit stay guarded after a dev hot reload and with disableOnInit. Tests through HTTP for all four; the 2FA tests now run on payload-2fa 3.0.0-beta.7 (what client sites use), a second file on beta.1 (alias), and the HTTP files can run against Postgres (IPAL_TEST_POSTGRES_URI). Docs, agent guide, skills and changelog updated; the not-yet-enrolled limitation is stated plainly. Co-Authored-By: Claude Fable 5.2 <[email protected]>
93 lines
4.5 KiB
TypeScript
93 lines
4.5 KiB
TypeScript
/**
|
|
* The same guarantees with the oldest supported 2FA package, @clocklimited/payload-2fa 3.0.0-beta.1 (installed
|
|
* here under the alias `payload-2fa-beta1`). The other HTTP tests run on the version in devDependencies, which is
|
|
* the one client sites use.
|
|
*/
|
|
import type { Payload } from 'payload'
|
|
|
|
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
|
import os from 'os'
|
|
import path from 'path'
|
|
import { getPayload } from 'payload'
|
|
import { payloadTotp } from 'payload-2fa-beta1'
|
|
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
|
|
|
|
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 SECRET = 'JBSWY3DPEHPK3PXP'
|
|
const PASSWORD = 'a-long-test-password-1'
|
|
let server: TestServer
|
|
let payload: Payload
|
|
|
|
const post = (pathname: string, body: unknown, headers: Record<string, string> = {}) =>
|
|
fetch(`${server.url}/api${pathname}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method: 'POST' })
|
|
const get = (pathname: string, headers: Record<string, string>) => fetch(`${server.url}/api${pathname}`, { headers })
|
|
|
|
beforeAll(async () => {
|
|
const config = buildTestConfig({
|
|
admin: { user: 'users' },
|
|
collections: [
|
|
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
|
|
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
|
],
|
|
db: testDatabase('sechttp_b1'),
|
|
editor: lexicalEditor(),
|
|
plugins: [
|
|
ipalKit({
|
|
access: { authCollection: 'users' },
|
|
forms: {},
|
|
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
|
twoFactor: { issuer: 'Example', plugin: payloadTotp as never },
|
|
}),
|
|
],
|
|
secret: 'integration-test-secret-0123456789',
|
|
telemetry: false,
|
|
})
|
|
payload = await getPayload({ config })
|
|
server = await startPayloadServer(config)
|
|
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
|
|
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
|
|
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
|
|
}, 120_000)
|
|
|
|
afterAll(async () => {
|
|
await server?.close()
|
|
await payload?.destroy?.()
|
|
})
|
|
|
|
test('beta.1: password only → refused; password and code → allowed (REST and GraphQL)', async () => {
|
|
const login = await post('/users/login', { email: '[email protected]', password: PASSWORD })
|
|
const cookie = cookiesOf(login).join('; ')
|
|
for (const p of ['/globals/site-integrations', '/form-submissions', '/users', '/globals/site-settings']) {
|
|
expect([p, (await get(p, { cookie })).status]).toEqual([p, 403])
|
|
}
|
|
const before = (await (await post('/graphql', { query: '{ SiteIntegration { smtpPassword } }' }, { cookie })).json()) as { errors?: unknown[] }
|
|
expect(before.errors?.length).toBeGreaterThan(0)
|
|
|
|
const verify = await post('/verify-totp', { token: totp(SECRET) }, { cookie })
|
|
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
|
|
const full = [cookie, ...cookiesOf(verify)].join('; ')
|
|
const integrations = await get('/globals/site-integrations', { cookie: full })
|
|
expect(integrations.status).toBe(200)
|
|
expect(((await integrations.json()) as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
|
|
expect((await get('/form-submissions', { cookie: full })).status).toBe(200)
|
|
})
|
|
|
|
test('beta.1: a customers account cannot use the 2FA endpoints or reach staff data', async () => {
|
|
const login = (await (await post('/customers/login', { email: '[email protected]', password: PASSWORD })).json()) as { token: string }
|
|
const authorization = `JWT ${login.token}`
|
|
const ATTACKER = 'KRSXG5CTMVRXEZLU'
|
|
expect((await post('/setup-totp', { secret: ATTACKER, token: totp(ATTACKER) }, { authorization })).status).toBe(403)
|
|
const admin = await payload.find({ collection: 'users' as never, showHiddenFields: true })
|
|
expect((admin.docs[0] as { totpSecret?: string }).totpSecret).toBe(SECRET)
|
|
expect((await get('/globals/site-integrations', { authorization })).status).toBe(403)
|
|
expect((await get('/form-submissions', { authorization })).status).toBe(403)
|
|
})
|