Staff check (userMeetsRole): the 'no roles field = every account passes' rule applied to the account's own collection, so an account of a second auth collection (customers) passed every staff check. It now applies only to staff collections: the panel's login collection plus the new access.staffCollections. The injected auth collection uses the new adminOrSelfIn(slug), so an account of another collection with the same numeric id is not 'self'. 2FA: @clocklimited/payload-2fa wraps the collections and globals present when it runs; ipalKit's own globals and collections were added later and stayed unwrapped, so a password without the TOTP code opened them over REST and GraphQL. ipal-kit now has its own second-factor check (secondFactorPassed / requireSecondFactor): applied to every collection and global at the end of ipalKit, again in onInit for entities added by plugins listed after it, and inside userMeetsRole and the endpoints that take a project access function. It fails closed: an unrecognised user shape is refused, and startup stops when the injected 2FA plugin lacks the parts the check reads (twoFactor.guard: false opts out). Tests through real HTTP requests (REST and GraphQL) against Payload's route handlers, plus the reference smoke test. Docs, agent guide, skills and the reference skills copy updated; changelog entry without a version. Co-Authored-By: Claude Fable 5.2 <[email protected]>
259 lines
14 KiB
TypeScript
259 lines
14 KiB
TypeScript
/**
|
|
* Who reaches what the plugin adds, through real HTTP requests (REST and GraphQL) against a running Payload:
|
|
* - a staff account that typed only its password (TOTP set up, code not entered) gets nothing;
|
|
* - an account of another auth collection (`customers`) gets no more than an anonymous visitor;
|
|
* - a fully verified staff account, an account that still has to set TOTP up, and an API key keep working.
|
|
*/
|
|
import type { CollectionConfig, Config, Payload, Plugin } from 'payload'
|
|
|
|
import { payloadTotp } from '@clocklimited/payload-2fa'
|
|
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
|
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 { ipalKit } from '../src/plugin.js'
|
|
import { buildTestConfig } from './helpers.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 TOTP_SECRET = 'JBSWY3DPEHPK3PXP'
|
|
const PASSWORD = 'a-long-test-password-1'
|
|
|
|
/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */
|
|
const latePlugin: Plugin = (config: Config) => ({
|
|
...config,
|
|
collections: [...(config.collections ?? []), { slug: 'late-notes', fields: [{ name: 'note', type: 'text' }] }],
|
|
})
|
|
|
|
const projectCollections: CollectionConfig[] = [
|
|
// A visitor account collection with open sign-up — a shop or a client zone.
|
|
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
|
|
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
|
|
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
|
]
|
|
const PROJECT_SLUGS = new Set(['customers', 'media', 'pages'])
|
|
|
|
type Session = { headers: Record<string, string> }
|
|
let server: TestServer
|
|
let payload: Payload
|
|
let pluginCollections: string[]
|
|
let pluginGlobals: string[]
|
|
const sessions = {} as Record<'anonymous' | 'customer' | 'newcomer' | 'passwordOnly' | 'verified', Session>
|
|
|
|
const api = (pathname: string, session: Session, init: RequestInit = {}) =>
|
|
fetch(`${server.url}/api${pathname}`, {
|
|
...init,
|
|
headers: { 'content-type': 'application/json', ...session.headers, ...(init.headers as Record<string, string>) },
|
|
})
|
|
const gql = async (session: Session, query: string) => {
|
|
const res = await api('/graphql', session, { body: JSON.stringify({ query }), method: 'POST' })
|
|
return (await res.json()) as { data?: null | Record<string, unknown>; errors?: { message: string }[] }
|
|
}
|
|
|
|
async function login(collection: string, email: string): Promise<{ cookies: string[]; token: string }> {
|
|
const res = await fetch(`${server.url}/api/${collection}/login`, {
|
|
body: JSON.stringify({ email, password: PASSWORD }),
|
|
headers: { 'content-type': 'application/json' },
|
|
method: 'POST',
|
|
})
|
|
const body = (await res.json()) as { token?: string }
|
|
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
|
|
return { cookies: cookiesOf(res), token: body.token }
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
const config = buildTestConfig({
|
|
admin: { user: 'users' }, // the panel logs in with the staff collection, not with `customers`
|
|
collections: projectCollections,
|
|
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
|
editor: lexicalEditor(),
|
|
plugins: [
|
|
ipalKit({
|
|
access: { authCollection: 'users' },
|
|
consentLog: true,
|
|
cookieScanner: { crawl: true },
|
|
forms: {},
|
|
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
|
stats: true,
|
|
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
|
}),
|
|
latePlugin,
|
|
],
|
|
secret: 'integration-test-secret-0123456789',
|
|
telemetry: false,
|
|
})
|
|
payload = await getPayload({ config })
|
|
server = await startPayloadServer(config)
|
|
|
|
pluginCollections = payload.config.collections.map((c) => c.slug).filter((s) => !PROJECT_SLUGS.has(s) && !s.startsWith('payload-'))
|
|
pluginGlobals = payload.config.globals.map((g) => g.slug)
|
|
|
|
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: 'S3CRET' } as never })
|
|
const user = (email: string, extra: object) =>
|
|
payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles: ['admin'], ...extra } as never })
|
|
await user('[email protected]', { totpSecret: TOTP_SECRET })
|
|
await user('[email protected]', {})
|
|
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
|
|
|
|
sessions.anonymous = { headers: {} }
|
|
sessions.passwordOnly = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
|
|
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
|
|
sessions.customer = { headers: { authorization: `JWT ${(await login('customers', '[email protected]')).token}` } }
|
|
|
|
// The full login: password, then the code from the authenticator app → the 2FA cookie.
|
|
const full = await login('users', '[email protected]')
|
|
const verify = await fetch(`${server.url}/api/verify-totp`, {
|
|
body: JSON.stringify({ token: totp(TOTP_SECRET) }),
|
|
headers: { 'content-type': 'application/json', cookie: full.cookies.join('; ') },
|
|
method: 'POST',
|
|
})
|
|
const verified = (await verify.json()) as { message?: string; ok: boolean }
|
|
expect(verified, JSON.stringify({ cookies: full.cookies.map((c) => c.slice(0, 30)), verified })).toMatchObject({ ok: true })
|
|
sessions.verified = { headers: { cookie: [...full.cookies, ...cookiesOf(verify)].join('; ') } }
|
|
}, 120_000)
|
|
|
|
afterAll(async () => {
|
|
await server?.close()
|
|
await payload?.destroy?.()
|
|
})
|
|
|
|
const readStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
|
|
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s)).status
|
|
const writeStatus = async (kind: 'collection' | 'global', slug: string, s: Session) =>
|
|
(await api(kind === 'collection' ? `/${slug}` : `/globals/${slug}`, s, { body: '{}', method: 'POST' })).status
|
|
|
|
describe('what the test set up', () => {
|
|
test('the plugin added the entities this file is about', () => {
|
|
expect(pluginCollections).toEqual(expect.arrayContaining(['users', 'forms', 'form-submissions', 'consent-records', 'cookie-review', 'stats-visits', 'late-notes']))
|
|
expect(pluginGlobals).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications', 'cookie-crawl']))
|
|
})
|
|
})
|
|
|
|
describe('REST: a staff password without the TOTP code opens nothing', () => {
|
|
test('every collection and global is refused, for reading and for writing', async () => {
|
|
const open: string[] = []
|
|
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
|
|
for (const slug of slugs) {
|
|
if ((await readStatus(kind, slug, sessions.passwordOnly)) !== 403) {open.push(`read ${kind} ${slug}`)}
|
|
if ((await writeStatus(kind, slug, sessions.passwordOnly)) !== 403) {open.push(`write ${kind} ${slug}`)}
|
|
}
|
|
}
|
|
expect(open).toEqual([])
|
|
})
|
|
|
|
test('the SMTP password is not returned', async () => {
|
|
const res = await api('/globals/site-integrations', sessions.passwordOnly)
|
|
expect(res.status).toBe(403)
|
|
expect(await res.text()).not.toContain('S3CRET')
|
|
})
|
|
|
|
test("the plugin's own endpoints refuse too", async () => {
|
|
expect((await api('/ipal/test-email', sessions.passwordOnly, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
|
|
expect((await api('/ipal/cookie-scan', sessions.passwordOnly)).status).toBe(403)
|
|
expect((await api('/ipal/cookie-scan', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
|
|
expect((await api('/ipal/cookie-crawl', sessions.passwordOnly)).status).toBe(403)
|
|
expect((await api('/ipal/cookie-approval', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
|
|
})
|
|
})
|
|
|
|
describe('GraphQL: a staff password without the TOTP code opens nothing', () => {
|
|
test.each([
|
|
['Site integrations', '{ SiteIntegration { smtpPassword } }'],
|
|
['form submissions', '{ FormSubmissions { totalDocs } }'],
|
|
['consent records', '{ ConsentRecords { totalDocs } }'],
|
|
['stats', '{ StatsVisits { totalDocs } }'],
|
|
['cookie review', '{ CookieReviews { totalDocs } }'],
|
|
['Site settings (write)', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }'],
|
|
['Notifications (write)', 'mutation { updateNotification(data: {}) { updatedAt } }'],
|
|
])('%s', async (_, query) => {
|
|
const out = await gql(sessions.passwordOnly, query)
|
|
expect(out.errors?.length, JSON.stringify(out)).toBeGreaterThan(0)
|
|
expect(JSON.stringify(out)).not.toContain('S3CRET')
|
|
expect(Object.values(out.data ?? {}).filter((v) => v !== null)).toEqual([])
|
|
})
|
|
})
|
|
|
|
describe('an account of another auth collection (customers) is not staff', () => {
|
|
test('REST: it gets exactly what an anonymous visitor gets, nothing more', async () => {
|
|
const more: string[] = []
|
|
for (const [kind, slugs] of [['collection', pluginCollections.filter((s) => s !== 'late-notes')], ['global', pluginGlobals]] as const) {
|
|
for (const slug of slugs) {
|
|
const read = [await readStatus(kind, slug, sessions.customer), await readStatus(kind, slug, sessions.anonymous)]
|
|
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: customer ${read[0]}, anonymous ${read[1]}`)}
|
|
// Creating a form submission over REST is open to every logged-in account (unchanged, see forms.md).
|
|
if (kind === 'collection' && slug === 'form-submissions') {continue}
|
|
const write = [await writeStatus(kind, slug, sessions.customer), await writeStatus(kind, slug, sessions.anonymous)]
|
|
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: customer ${write[0]}, anonymous ${write[1]}`)}
|
|
}
|
|
}
|
|
expect(more).toEqual([])
|
|
})
|
|
|
|
test('REST: Site integrations, submissions, consent records and stats are refused', async () => {
|
|
for (const p of ['/globals/site-integrations', '/form-submissions', '/consent-records', '/stats-visits', '/cookie-review', '/globals/cookie-crawl']) {
|
|
expect([p, (await api(p, sessions.customer)).status]).toEqual([p, 403])
|
|
}
|
|
expect((await api('/globals/site-settings', sessions.customer, { body: JSON.stringify({ siteName: 'x' }), method: 'POST' })).status).toBe(403)
|
|
expect((await api('/ipal/test-email', sessions.customer, { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })).status).toBe(403)
|
|
expect((await api('/ipal/cookie-scan', sessions.customer)).status).toBe(403)
|
|
})
|
|
|
|
test('GraphQL: the same', async () => {
|
|
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ FormSubmissions { totalDocs } }', '{ ConsentRecords { totalDocs } }', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }']) {
|
|
const out = await gql(sessions.customer, query)
|
|
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
|
|
expect(JSON.stringify(out)).not.toContain('S3CRET')
|
|
}
|
|
})
|
|
|
|
test('its own collection still works for it', async () => {
|
|
expect((await api('/customers/me', sessions.customer)).status).toBe(200)
|
|
})
|
|
})
|
|
|
|
describe('what must keep working', () => {
|
|
test('a fully verified admin reads and writes everything (REST)', async () => {
|
|
const closed: string[] = []
|
|
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
|
|
for (const slug of slugs) {
|
|
const status = await readStatus(kind, slug, sessions.verified)
|
|
if (status !== 200) {closed.push(`read ${kind} ${slug}: ${status}`)}
|
|
}
|
|
}
|
|
expect(closed).toEqual([])
|
|
const integrations = (await (await api('/globals/site-integrations', sessions.verified)).json()) as { smtpPassword?: string }
|
|
expect(integrations.smtpPassword).toBe('S3CRET')
|
|
expect((await api('/globals/site-settings', sessions.verified, { body: JSON.stringify({ siteName: 'Verified' }), method: 'POST' })).status).toBe(200)
|
|
expect((await api('/ipal/cookie-scan', sessions.verified)).status).toBe(200)
|
|
// 400 = past the login and role gates, stopped by the missing recipient
|
|
expect((await api('/ipal/test-email', sessions.verified, { body: '{}', method: 'POST' })).status).toBe(400)
|
|
})
|
|
|
|
test('a fully verified admin reads Site integrations (GraphQL)', async () => {
|
|
const out = await gql(sessions.verified, '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }')
|
|
expect(out.errors).toBeUndefined()
|
|
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
|
|
})
|
|
|
|
test('an account that has not set TOTP up yet can still do so', async () => {
|
|
// The package lets such an account through until TOTP is set up (the setup screen needs it).
|
|
expect((await api('/users/me', sessions.newcomer)).status).toBe(200)
|
|
const setup = await api('/setup-totp', sessions.newcomer, { body: JSON.stringify({ secret: TOTP_SECRET, token: totp(TOTP_SECRET) }), method: 'POST' })
|
|
expect(setup.status).toBe(200)
|
|
expect(((await setup.json()) as { ok: boolean }).ok).toBe(true)
|
|
})
|
|
|
|
test('anonymous visitors still read the public globals and forms', async () => {
|
|
for (const p of ['/globals/site-settings', '/globals/notifications', '/globals/cookie-settings', '/forms']) {
|
|
expect([p, (await api(p, sessions.anonymous)).status]).toEqual([p, 200])
|
|
}
|
|
expect((await api('/globals/site-integrations', sessions.anonymous)).status).toBe(403)
|
|
})
|
|
})
|