Security: staff checks only for staff collections; 2FA covers what the plugin adds

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]>
This commit is contained in:
Radosław Smoliński
2026-11-24 00:31:55 +01:00
co-authored by Claude Fable 5.2
parent bc1045a5b7
commit 0c61ac231b
40 changed files with 1224 additions and 63 deletions
+5 -4
View File
@@ -5,6 +5,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
@@ -17,9 +18,9 @@ const i18n: I18nConfig = {
const empty = (extra: Partial<Config> = {}): Config =>
({ collections: [], secret: 'x', ...extra }) as unknown as Config
const admin = { id: 1, roles: ['admin'] }
const editor = { id: 2, roles: ['editor'] }
const user = { id: 3, roles: ['user'] }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const user = { id: 3, collection: 'users', roles: ['user'] }
/** Runs a collection/global access function the way Payload does. */
const run = (fn: Access | undefined, u: unknown) =>
@@ -52,7 +53,7 @@ describe('injected auth collection', () => {
})
describe('2FA wraps the auth collection people log in with', () => {
const totp = () => vi.fn((_: unknown) => (c: Config) => c)
const totp = () => vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
test('defaults to access.authCollection, not a literal "users"', async () => {
const plugin = totp()
+20
View File
@@ -13,6 +13,26 @@ import { vi } from 'vitest'
export const buildTestConfig = (config: Config) =>
buildConfig({ ...config, typescript: { ...config.typescript, autoGenerate: false } })
/**
* The parts of @clocklimited/payload-2fa that ipalKit checks for after the injected factory ran
* (missingTotpParts): the two fields and the `totp` strategy on the target collection.
* A fake 2FA factory in a test wraps its config in this.
*/
export function withTotpParts(config: Config, collection: string): Config {
return {
...config,
collections: (config.collections ?? []).map((c) =>
c.slug === collection
? {
...c,
auth: { ...(typeof c.auth === 'object' ? c.auth : {}), strategies: [{ name: 'totp', authenticate: () => ({ user: null }) }] },
fields: [...c.fields, { name: 'totpSecret', type: 'text' }, { name: 'hasTotp', type: 'checkbox', virtual: true }],
}
: c,
),
}
}
type FakeOptions = {
forms?: Record<string, { fields: Record<string, unknown>[] }>
integrations?: Record<string, unknown>
+89
View File
@@ -0,0 +1,89 @@
import type { SanitizedConfig } from 'payload'
import { GRAPHQL_POST, REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
import { AsyncLocalStorage } from 'node:async_hooks'
import { createServer, type Server } from 'node:http'
/**
* Payload's own REST and GraphQL route handlers (the ones a Next app mounts under /api) behind a real HTTP
* server, so a test sends real requests: login, cookies, `Authorization` headers.
*
* @clocklimited/payload-2fa reads and writes its cookie through `next/headers`, which only works inside a Next
* request. A test file that turns 2FA on mocks that module with `nextHeadersMock` below:
* vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
*/
type CookieJar = { incoming: Map<string, string>; outgoing: string[] }
const jar = new AsyncLocalStorage<CookieJar>()
export const nextHeadersMock = {
cookies: () => {
const store = jar.getStore()
return Promise.resolve({
get: (name: string) => (store?.incoming.has(name) ? { name, value: store.incoming.get(name)! } : undefined),
set: (name: string, value: string) => {
store?.outgoing.push(`${name}=${value}; Path=/; HttpOnly`)
},
})
},
headers: () => Promise.resolve(new Headers()),
}
export type TestServer = { close: () => Promise<void>; url: string }
export async function startPayloadServer(config: Promise<SanitizedConfig>): Promise<TestServer> {
const rest = { DELETE: REST_DELETE(config), GET: REST_GET(config), PATCH: REST_PATCH(config), POST: REST_POST(config) }
const graphql = GRAPHQL_POST(config)
const server: Server = createServer((req, res) => {
const chunks: Buffer[] = []
req.on('data', (c: Buffer) => chunks.push(c))
req.on('end', () => {
void (async () => {
const url = new URL(req.url ?? '/', `http://${req.headers.host}`)
const headers = new Headers()
for (const [k, v] of Object.entries(req.headers)) {
if (typeof v === 'string') {headers.set(k, v)}
}
const method = (req.method ?? 'GET').toUpperCase()
const body = method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks)
const request = new Request(url, { body, headers, method })
const incoming = new Map(
(req.headers.cookie ?? '').split(';').map((p) => p.trim()).filter(Boolean).map((p) => {
const i = p.indexOf('=')
return [p.slice(0, i), p.slice(i + 1)] as [string, string]
}),
)
const store: CookieJar = { incoming, outgoing: [] }
try {
const response = await jar.run(store, async () => {
if (url.pathname === '/api/graphql') {return graphql(request)}
const handler = rest[method as keyof typeof rest]
if (!handler) {return new Response('Method not allowed', { status: 405 })}
const slug = url.pathname.replace(/^\/api\/?/, '').split('/').filter(Boolean)
return handler(request, { params: Promise.resolve({ slug }) })
})
const setCookies = [...response.headers.getSetCookie(), ...store.outgoing]
response.headers.forEach((value, key) => {
if (key !== 'set-cookie') {res.setHeader(key, value)}
})
if (setCookies.length) {res.setHeader('set-cookie', setCookies)}
res.statusCode = response.status
res.end(Buffer.from(await response.arrayBuffer()))
} catch (err) {
res.statusCode = 500
res.end(err instanceof Error ? err.stack : String(err))
}
})()
})
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
const port = typeof address === 'object' && address ? address.port : 0
return {
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
url: `http://127.0.0.1:${port}`,
}
}
/** `name=value` pairs of a response's Set-Cookie headers, ready for a `cookie` request header. */
export const cookiesOf = (res: Response): string[] => res.headers.getSetCookie().map((c) => c.split(';')[0])
+15
View File
@@ -0,0 +1,15 @@
import { createHmac } from 'node:crypto'
/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) — the code an authenticator app shows for `secret` (base32). */
export function totp(secret: string, now = Date.now()): string {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
let bits = ''
for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')}
const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
const counter = Buffer.alloc(8)
counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / 30)))
const hmac = createHmac('sha1', key).update(counter).digest()
const offset = hmac[hmac.length - 1] & 0xf
const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
return code.toString().padStart(6, '0')
}
+4 -2
View File
@@ -5,6 +5,7 @@ import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = {
defaultLocale: 'pl',
@@ -40,7 +41,7 @@ describe('ipalKit — config transform', () => {
/no 2FA plugin was injected/,
)
const totp = vi.fn(() => (c: Config) => c)
const totp = vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection))
await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } }))
})
@@ -119,7 +120,8 @@ describe('options that keep features reachable and overridable', () => {
test('without `access` (no roles field) admin and editor features stay reachable for logged-in users', async () => {
const config = await ipalKit({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base())
const users = config.collections!.find((c) => c.slug === 'users')!
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } } }, user }) as never
// `admin.user` is what Payload's sanitize fills in: the panel's login collection = the staff collection.
const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never
const member = { id: 1, collection: 'users', email: '[email protected]' }
const run = (access: unknown, user: unknown) => (access as (a: { req: unknown }) => unknown)({ req: req(user) })
+163
View File
@@ -0,0 +1,163 @@
/**
* The rules behind test/securityHttp.test.ts, one by one: who is staff (userMeetsRole), when the second
* factor counts as passed, and what ipalKit does with a 2FA plugin it does not recognise.
*/
import type { Access, Config } from 'payload'
import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { adminOrSelfIn } from '../src/modules/access/access.js'
import { staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
import { guardPayloadAccess, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
const fakeTotp = (o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)
/** A payload as the access functions see it: sanitized `admin.user`, the collections by slug, `custom`. */
const payloadOf = (config: Config, adminUser = 'users') =>
({
collections: Object.fromEntries((config.collections ?? []).map((c) => [c.slug, { config: c }])),
config: { admin: { user: adminUser }, collections: config.collections, custom: config.custom, globals: config.globals },
}) as never
const twoAuth = (): Config =>
({
collections: [
{ slug: 'customers', auth: true, fields: [] },
{ slug: 'partners', auth: true, fields: [] },
],
secret: 'x',
}) as unknown as Config
describe('userMeetsRole: who is staff', () => {
test('with roles: the role decides; an account of another auth collection never passes', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['user'] } }, 'editor')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
expect(userMeetsRole({ payload, user: { collection: 'no-such-collection' } }, 'user')).toBe(false)
expect(userMeetsRole({ payload, user: null }, 'user')).toBe(false)
})
test('without `access`: every account of the panel collection passes, other auth collections do not', async () => {
const config = await ipalKit({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users'])
expect(userMeetsRole({ payload, user: { collection: 'users' } }, 'admin')).toBe(true)
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('access.staffCollections names more staff collections, on purpose', async () => {
const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth())
const payload = payloadOf(config)
expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners'])
expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
})
test('without a payload only a held role counts', () => {
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
})
})
describe('adminOrSelfIn', () => {
const run = (fn: Access, user: unknown) => fn({ req: { user } } as never)
test('"self" is an account of that collection only', () => {
const access = adminOrSelfIn('users')
expect(run(access, { id: 5, collection: 'users', roles: ['user'] })).toEqual({ id: { equals: 5 } })
expect(run(access, { id: 5, collection: 'customers' })).toBe(false) // same id, other collection
expect(run(access, { id: 1, collection: 'users', roles: ['admin'] })).toBe(true)
expect(run(access, null)).toBe(false)
})
})
describe('secondFactorPassed', () => {
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } } as never
const cases: [string, unknown, boolean][] = [
['no user', null, true],
['password and code (the totp strategy)', { _strategy: 'totp', collection: 'users', hasTotp: true }, true],
['API key', { _strategy: 'api-key', collection: 'users', hasTotp: true }, true],
['TOTP not set up yet', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true],
['password only', { _strategy: 'local-jwt', collection: 'users', hasTotp: true }, false],
['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false],
['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false],
['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true],
]
test.each(cases)('%s', (_, user, expected) => {
expect(secondFactorPassed({ payload, user })).toBe(expected)
})
test('2FA off: everyone passes', () => {
expect(secondFactorPassed({ payload: { config: {} } as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } })).toBe(true)
})
test('requireSecondFactor wraps once and keeps the inner rule', () => {
const inner: Access = ({ req }) => Boolean((req.user as { ok?: boolean } | null)?.ok)
const wrapped = requireSecondFactor(inner)
expect(requireSecondFactor(wrapped)).toBe(wrapped)
const call = (user: unknown) => wrapped({ req: { payload, user } } as never)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true, ok: true })).toBe(true)
expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe(false)
expect(call({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, ok: true })).toBe(false)
})
})
describe('ipalKit and the 2FA plugin', () => {
const passwordOnly = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] }
const verified = { ...passwordOnly, _strategy: 'totp' }
test('every collection and global in the config is guarded, whenever it was added', async () => {
const config = await ipalKit({
access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, forms: {}, i18n, stats: true,
twoFactor: { issuer: 'A', plugin: fakeTotp as never },
})({ collections: [{ slug: 'pages', fields: [] }], globals: [{ slug: 'own', fields: [] }], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
const open: string[] = []
const check = (kind: string, slug: string, access: Record<string, unknown> | undefined, ops: string[]) => {
for (const op of ops) {
const fn = access?.[op] as ((a: unknown) => unknown) | undefined
if (!fn || fn({ req: { payload, user: passwordOnly } }) !== false) {open.push(`${kind} ${slug}.${op}`)}
}
}
for (const c of config.collections ?? []) {check('collection', c.slug, c.access as never, ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])}
for (const g of config.globals ?? []) {check('global', g.slug, g.access as never, ['read', 'readDrafts', 'readVersions', 'update'])}
expect(open).toEqual([])
// and a verified admin still gets in
const integrations = config.globals!.find((g) => g.slug === 'site-integrations')!
expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true)
})
test('onInit guards what a later plugin added; Payload\'s own collections are left alone', () => {
const late = { slug: 'late', access: {} as Record<string, unknown> }
const internal = { slug: 'payload-preferences', access: {} as Record<string, unknown> }
const payload = { config: { collections: [late, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [] } } as never
expect(guardPayloadAccess(payload)).toEqual(['late'])
expect((late.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false)
expect(internal.access.read).toBeUndefined()
expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time
})
test('a 2FA plugin without the parts the guard relies on stops the start', async () => {
const unknown = () => (c: Config) => c
const run = (guard?: false) =>
ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config)
await expect(run()).rejects.toThrow(/did not add the `totpSecret` field, the `hasTotp` field, the `totp` auth strategy/)
// twoFactor.guard: false = the package alone, as before
const config = await run(false)
expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined()
})
test('twoFactor: false — no guard, a password is enough (as documented)', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
const payload = payloadOf(config)
const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: unknown) => unknown
expect(read({ req: { payload, user: { collection: 'users', roles: ['admin'] } } })).toBe(true)
})
})
+258
View File
@@ -0,0 +1,258 @@
/**
* 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)
})
})
+79
View File
@@ -0,0 +1,79 @@
/**
* The documented non-interactive paths keep working with 2FA on (real HTTP, see securityHttp.test.ts):
* an API key of a staff account, and the bearer token of GET /api/ipal/doctor.
*/
import type { Payload } 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, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const API_KEY = 'b7f0c3a2-5d1e-4f6a-9c8b-0e1d2f3a4b5c'
const DOCTOR_TOKEN = 'doctor-token-0123456789-0123456789-abcdef'
let server: TestServer
let payload: Payload
beforeAll(async () => {
process.env.IPAL_DOCTOR_TOKEN = DOCTOR_TOKEN
const config = buildTestConfig({
collections: [
// The project's own staff collection, with API keys.
{ slug: 'users', auth: { useAPIKey: true }, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: { issuer: 'Example', plugin: payloadTotp },
}),
],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.create({
collection: 'users' as never,
data: { apiKey: API_KEY, email: '[email protected]', enableAPIKey: true, password: 'a-long-test-password-1', roles: ['admin'], totpSecret: 'JBSWY3DPEHPK3PXP' } as never,
})
}, 120_000)
afterAll(async () => {
delete process.env.IPAL_DOCTOR_TOKEN
await server?.close()
await payload?.destroy?.()
})
const get = (pathname: string, authorization?: string) =>
fetch(`${server.url}/api${pathname}`, { headers: authorization ? { authorization } : {} })
test('an API key of an admin account reads Site integrations and form submissions without a TOTP code', async () => {
const key = `users API-Key ${API_KEY}`
expect((await get('/globals/site-integrations', key)).status).toBe(200)
expect((await get('/form-submissions', key)).status).toBe(200)
expect((await get('/users', key)).status).toBe(200)
expect((await get('/globals/site-integrations', 'users API-Key wrong-key')).status).toBe(403)
})
test('GET /api/ipal/doctor answers its bearer token, and nobody else', async () => {
const ok = await get('/ipal/doctor', `Bearer ${DOCTOR_TOKEN}`)
expect(ok.status).toBe(200)
expect(await ok.json()).toMatchObject({ usersWithout2fa: 0 })
expect((await get('/ipal/doctor')).status).toBe(401)
expect((await get('/ipal/doctor', 'Bearer not-the-token-0123456789-0123456789')).status).toBe(401)
})
+3 -2
View File
@@ -5,12 +5,13 @@ import { describe, expect, test } from 'vitest'
import { bottomOverlap } from '../src/modules/consent/CookieButton.js'
import { TOTP_TEXTS } from '../src/modules/security/totp/totpTexts.js'
import { ipalKit } from '../src/plugin.js'
import { withTotpParts } from './helpers.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
/** Stand-in for @clocklimited/payload-2fa: its own texts and the two views, as the package adds them. */
const fakeTotp = () => (config: Config) => ({
...config,
const fakeTotp = (o: { collection: string }) => (config: Config) => ({
...withTotpParts(config, o.collection),
admin: {
...config.admin,
components: {