Security review fixes: staff collection first everywhere, 2FA package endpoints guarded, per-entity opt-out, hot reload
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]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
97ee1289aa
commit
32faaa5e30
+36
-5
@@ -2,15 +2,18 @@ import type { FieldAccess, PayloadRequest } from 'payload'
|
||||
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, adminOrSelfIn, requireRole, requireRoleField } from '../src/modules/access/access.js'
|
||||
import { hasMinimumRole, isAdmin, isEditor } from '../src/modules/access/predicates.js'
|
||||
import { buildRolesField } from '../src/modules/access/rolesField.js'
|
||||
import { testEmailEndpoint } from '../src/modules/email/test/testEmailEndpoint.js'
|
||||
|
||||
vi.mock('payload', () => ({ addDataAndFileToRequest: vi.fn(async () => {}) }))
|
||||
|
||||
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'] }
|
||||
/** `req.payload` as far as the role checks read it: the panel logs in with `users`. */
|
||||
const payload = { config: { admin: { user: 'users' } } } as never
|
||||
|
||||
describe('role predicates', () => {
|
||||
test('hierarchy admin > editor > user', () => {
|
||||
@@ -26,16 +29,44 @@ describe('role predicates', () => {
|
||||
expect(isAdmin({ roles: 'admin' })).toBe(false)
|
||||
expect(isAdmin(null)).toBe(false)
|
||||
})
|
||||
|
||||
test('a role counts only on an account of a staff collection', () => {
|
||||
const member = { id: 1, collection: 'members', roles: ['admin'] }
|
||||
expect(isAdmin(member, payload)).toBe(false)
|
||||
expect(isEditor(member, payload)).toBe(false)
|
||||
expect(hasMinimumRole(member, 'user', payload)).toBe(false)
|
||||
expect(isAdmin({ id: 1, roles: ['admin'] }, payload)).toBe(false) // no collection: not an authenticated staff account
|
||||
expect(isAdmin(admin, payload)).toBe(true)
|
||||
// named in access.staffCollections → its roles count
|
||||
const withMembers = { config: { admin: { user: 'users' }, custom: { ipal: { staffCollections: ['members'] } } } } as never
|
||||
expect(isAdmin(member, withMembers)).toBe(true)
|
||||
})
|
||||
|
||||
test('every ready access function refuses that account', () => {
|
||||
const member = { id: 1, collection: 'members', roles: ['admin'] }
|
||||
const req = { payload, user: member }
|
||||
for (const fn of [adminOnly, adminOrEditor, requireRole('user'), adminOrSelfIn('users')]) {
|
||||
expect(fn({ req } as never)).toBe(false)
|
||||
}
|
||||
for (const fn of [adminOnlyField, adminOrEditorField, requireRoleField('user')]) {
|
||||
expect(fn({ req } as never)).toBe(false)
|
||||
}
|
||||
// adminOrSelf cannot know the collection it guards: no admin shortcut, only the id rule (use adminOrSelfIn)
|
||||
expect(adminOrSelf({ req } as never)).toEqual({ id: { equals: 1 } })
|
||||
expect(adminOnly({ req: { payload, user: admin } } as never)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('roles field', () => {
|
||||
const field = buildRolesField() as { access: { create: FieldAccess; update: FieldAccess } }
|
||||
const call = (fn: FieldAccess, u: unknown) => fn({ req: { user: u } } as never)
|
||||
const call = (fn: FieldAccess, u: unknown) => fn({ req: { payload, user: u } } as never)
|
||||
|
||||
test('only admins can set roles on create — no self-promotion via sign-up', () => {
|
||||
expect(call(field.access.create, null)).toBe(false)
|
||||
expect(call(field.access.create, user)).toBe(false)
|
||||
expect(call(field.access.create, admin)).toBe(true)
|
||||
// an "admin" of another auth collection is nobody here
|
||||
expect(call(field.access.create, { id: 1, collection: 'members', roles: ['admin'] })).toBe(false)
|
||||
})
|
||||
|
||||
test('only admins can change roles', () => {
|
||||
@@ -49,7 +80,7 @@ describe('test-email endpoint', () => {
|
||||
const sendEmail = vi.fn(async () => ({ sent: true }))
|
||||
const req = {
|
||||
data: { to: '[email protected]' },
|
||||
payload: { logger: { error: vi.fn() }, sendEmail },
|
||||
payload: { config: { admin: { user: 'users' } }, logger: { error: vi.fn() }, sendEmail },
|
||||
user: u,
|
||||
} as unknown as PayloadRequest
|
||||
return { response: testEmailEndpoint.handler(req), sendEmail }
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { postgresAdapter } from '@payloadcms/db-postgres'
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
|
||||
/**
|
||||
* The database of the HTTP security tests. SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` points them at a
|
||||
* real Postgres (numeric ids, like SQLite — the adapters where an id of one auth collection can equal an id of
|
||||
* another):
|
||||
* docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17
|
||||
* IPAL_TEST_POSTGRES_URI=postgres://postgres:[email protected]:55432/postgres pnpm vitest run test/securityHttp.test.ts
|
||||
* Each test file gets its own schema (`name`), so the files can run one after another against one server.
|
||||
*/
|
||||
export function testDatabase(name: string) {
|
||||
const uri = process.env.IPAL_TEST_POSTGRES_URI
|
||||
if (uri) {return postgresAdapter({ pool: { connectionString: uri }, push: true, schemaName: `${name}_${Date.now()}` })}
|
||||
return sqliteAdapter({ client: { url: 'file::memory:' }, push: true })
|
||||
}
|
||||
@@ -9,8 +9,8 @@ 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 { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js'
|
||||
import { guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed } from '../src/modules/security/totp/secondFactor.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
|
||||
@@ -42,6 +42,9 @@ describe('userMeetsRole: who is staff', () => {
|
||||
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)
|
||||
// a role value on an account of a non-staff collection counts for nothing
|
||||
expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'user')).toBe(false)
|
||||
expect(userMeetsRole({ payload, user: { roles: ['admin'] } }, 'user')).toBe(false) // no collection at all
|
||||
expect(userMeetsRole({ payload, user: null }, 'user')).toBe(false)
|
||||
})
|
||||
|
||||
@@ -58,12 +61,17 @@ describe('userMeetsRole: who is staff', () => {
|
||||
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', roles: ['admin'] } }, 'admin')).toBe(false)
|
||||
expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false)
|
||||
})
|
||||
|
||||
test('without a payload only a held role counts', () => {
|
||||
test('without a payload: the staff collections of the config ipalKit built last; only a held role counts', async () => {
|
||||
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config)
|
||||
expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false)
|
||||
expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true)
|
||||
expect(userMeetsRole({ user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false)
|
||||
expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // isAdmin(req.user) in a hook
|
||||
expect(isAdmin({ collection: 'users', roles: ['admin'] })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -154,6 +162,54 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined()
|
||||
})
|
||||
|
||||
test('per-entity opt-out: the package key and ipal-kit\'s key, operation by operation', async () => {
|
||||
const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
|
||||
collections: [
|
||||
{ slug: 'a', custom: { totp: { disableAccessWrapper: { read: true } } }, fields: [] },
|
||||
{ slug: 'b', custom: { ipal: { secondFactor: false } }, fields: [] },
|
||||
],
|
||||
globals: [{ slug: 'g', custom: { ipal: { secondFactor: { read: false } } }, fields: [] }],
|
||||
secret: 'x',
|
||||
} as unknown as Config)
|
||||
const payload = payloadOf(config)
|
||||
// an operation without a function = Payload's default: any logged-in account
|
||||
const call = (access: unknown, op: string) => {
|
||||
const fn = (access as Record<string, ((a: unknown) => unknown) | undefined> | undefined)?.[op]
|
||||
return fn ? fn({ req: { payload, user: passwordOnly } }) : true
|
||||
}
|
||||
const col = (slug: string) => config.collections!.find((c) => c.slug === slug)!.access
|
||||
expect(call(col('a'), 'read')).toBe(true)
|
||||
expect(call(col('a'), 'update')).toBe(false)
|
||||
// opted out of everything and no rule of its own: left exactly as the project wrote it (Payload's default applies)
|
||||
expect(col('b')).toBeUndefined()
|
||||
const g = config.globals!.find((x) => x.slug === 'g')!.access
|
||||
expect(call(g, 'read')).toBe(true)
|
||||
expect(call(g, 'update')).toBe(false)
|
||||
// ipal-kit's key reaches the package in its own key, so the package leaves the operation alone too
|
||||
expect((config.globals!.find((x) => x.slug === 'g')!.custom as { totp: unknown }).totp).toEqual({ disableAccessWrapper: { read: true } })
|
||||
})
|
||||
|
||||
test("the 2FA package's endpoints: accounts of the 2FA collection only; management needs the second factor", async () => {
|
||||
const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } }
|
||||
const inner = () => Promise.resolve(Response.json({ ok: true }))
|
||||
const call = async (path: string, user: unknown) => {
|
||||
const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise<Response>, path }, 'users')
|
||||
return (await endpoint.handler({ payload, user } as never)).status
|
||||
}
|
||||
const customer = { id: 1, collection: 'customers' }
|
||||
const newcomer = { id: 2, _strategy: 'local-jwt', collection: 'users', hasTotp: false }
|
||||
for (const path of ['/setup-totp', '/verify-totp', '/remove-totp', '/admin/reset-user-totp', '/some-future-endpoint']) {
|
||||
expect([path, await call(path, customer)]).toEqual([path, 403])
|
||||
expect([path, await call(path, null)]).toEqual([path, 200]) // no user: the package answers itself
|
||||
}
|
||||
expect(await call('/setup-totp', newcomer)).toBe(200)
|
||||
expect(await call('/verify-totp', passwordOnly)).toBe(200)
|
||||
expect(await call('/remove-totp', passwordOnly)).toBe(403)
|
||||
expect(await call('/admin/reset-user-totp', passwordOnly)).toBe(403)
|
||||
expect(await call('/some-future-endpoint', passwordOnly)).toBe(403)
|
||||
expect(await call('/admin/reset-user-totp', verified)).toBe(200)
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
+149
-6
@@ -7,7 +7,6 @@
|
||||
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'
|
||||
@@ -16,6 +15,7 @@ import { afterAll, beforeAll, describe, 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'
|
||||
|
||||
@@ -34,17 +34,37 @@ const latePlugin: Plugin = (config: Config) => ({
|
||||
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: [] },
|
||||
// Another one that happens to have its own `roles` field with the same values, settable at sign-up.
|
||||
{
|
||||
slug: 'members',
|
||||
access: { create: () => true },
|
||||
auth: true,
|
||||
fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }],
|
||||
},
|
||||
// The 2FA package's own per-entity opt-out, and ipal-kit's.
|
||||
{
|
||||
slug: 'open-notes',
|
||||
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
|
||||
custom: { totp: { disableAccessWrapper: { read: true } } },
|
||||
fields: [{ name: 'note', type: 'text' }],
|
||||
},
|
||||
{
|
||||
slug: 'open-tasks',
|
||||
access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) },
|
||||
custom: { ipal: { secondFactor: { read: false } } },
|
||||
fields: [{ name: 'task', type: 'text' }],
|
||||
},
|
||||
{ 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'])
|
||||
const PROJECT_SLUGS = new Set(['customers', 'media', 'members', 'open-notes', 'open-tasks', '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 sessions = {} as Record<'anonymous' | 'customer' | 'member' | 'newcomer' | 'passwordOnly' | 'verified', Session>
|
||||
|
||||
const api = (pathname: string, session: Session, init: RequestInit = {}) =>
|
||||
fetch(`${server.url}/api${pathname}`, {
|
||||
@@ -67,11 +87,11 @@ async function login(collection: string, email: string): Promise<{ cookies: stri
|
||||
return { cookies: cookiesOf(res), token: body.token }
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
const makeConfig = () =>
|
||||
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 }),
|
||||
db: testDatabase('sechttp'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
ipalKit({
|
||||
@@ -88,6 +108,9 @@ beforeAll(async () => {
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = makeConfig()
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
|
||||
@@ -101,6 +124,15 @@ beforeAll(async () => {
|
||||
await user('[email protected]', {})
|
||||
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
|
||||
|
||||
// Signed up over the API, asking for the admin role in its own collection.
|
||||
const signUp = await fetch(`${server.url}/api/members`, {
|
||||
body: JSON.stringify({ email: '[email protected]', password: PASSWORD, roles: ['admin'] }),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
method: 'POST',
|
||||
})
|
||||
expect(signUp.status).toBe(201)
|
||||
sessions.member = { headers: { authorization: `JWT ${(await login('members', '[email protected]')).token}` } }
|
||||
|
||||
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}` } }
|
||||
@@ -256,3 +288,114 @@ describe('what must keep working', () => {
|
||||
expect((await api('/globals/site-integrations', sessions.anonymous)).status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a role value on an account of a non-staff collection counts for nothing (members with roles: [admin])', () => {
|
||||
test('REST: it gets exactly what an anonymous visitor gets', 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.member), await readStatus(kind, slug, sessions.anonymous)]
|
||||
if (read[0] !== read[1]) {more.push(`read ${kind} ${slug}: member ${read[0]}, anonymous ${read[1]}`)}
|
||||
if (kind === 'collection' && slug === 'form-submissions') {continue}
|
||||
const write = [await writeStatus(kind, slug, sessions.member), await writeStatus(kind, slug, sessions.anonymous)]
|
||||
if (write[0] !== write[1]) {more.push(`write ${kind} ${slug}: member ${write[0]}, anonymous ${write[1]}`)}
|
||||
}
|
||||
}
|
||||
expect(more).toEqual([])
|
||||
})
|
||||
|
||||
test('REST: no secrets, no user list, no submissions, no staff endpoints, no unlock, no role change', async () => {
|
||||
const integrations = await api('/globals/site-integrations', sessions.member)
|
||||
expect(integrations.status).toBe(403)
|
||||
expect(await integrations.text()).not.toContain('S3CRET')
|
||||
for (const p of ['/users', '/form-submissions', '/consent-records', '/stats-visits', '/ipal/cookie-scan']) {
|
||||
expect([p, (await api(p, sessions.member)).status]).toEqual([p, 403])
|
||||
}
|
||||
expect((await api('/ipal/test-email', sessions.member, { body: '{}', method: 'POST' })).status).toBe(403)
|
||||
expect((await api('/users/unlock', sessions.member, { body: JSON.stringify({ email: '[email protected]' }), method: 'POST' })).status).toBe(403)
|
||||
const staff = await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })
|
||||
const patch = await api(`/users/${staff.docs[0].id}`, sessions.member, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })
|
||||
expect(patch.status).toBe(403)
|
||||
const after = (await payload.findByID({ id: staff.docs[0].id, collection: 'users' as never })) as unknown as { roles: string[] }
|
||||
expect(after.roles).toEqual(['admin'])
|
||||
})
|
||||
|
||||
test('GraphQL: the same', async () => {
|
||||
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ Users { totalDocs } }', '{ FormSubmissions { totalDocs } }']) {
|
||||
const out = await gql(sessions.member, query)
|
||||
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
|
||||
expect(JSON.stringify(out)).not.toContain('S3CRET')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("the 2FA package's endpoints accept accounts of the 2FA collection only", () => {
|
||||
const secretOf = async (email: string) => {
|
||||
const found = await payload.find({ collection: 'users' as never, showHiddenFields: true, where: { email: { equals: email } } })
|
||||
return (found.docs[0] as { id: number | string; totpSecret?: null | string })
|
||||
}
|
||||
|
||||
test('an account of another collection cannot set the TOTP secret of the staff account with the same id', async () => {
|
||||
// SQL adapters number each collection from 1: the first customer and the first staff account share an id.
|
||||
const customer = (await (await api('/customers/me', sessions.customer)).json()) as { user: { id: number | string } }
|
||||
const admin = await secretOf('[email protected]')
|
||||
const ATTACKER = 'KRSXG5CTMVRXEZLU'
|
||||
const res = await api('/setup-totp', sessions.customer, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
expect(res.headers.getSetCookie().join(';')).not.toContain('payload-totp')
|
||||
const after = await secretOf('[email protected]')
|
||||
expect(after.totpSecret).toBe(TOTP_SECRET)
|
||||
// the case this test is about: the two accounts really share an id (SQL adapters; on MongoDB ids never repeat)
|
||||
expect(String(customer.user.id)).toBe(String(admin.id))
|
||||
// an account of yet another auth collection is refused the same way
|
||||
const member = await api('/setup-totp', sessions.member, { body: JSON.stringify({ secret: ATTACKER, token: totp(ATTACKER) }), method: 'POST' })
|
||||
expect(member.status).toBe(403)
|
||||
})
|
||||
|
||||
test('verify, remove and the admin management endpoints refuse it as well', async () => {
|
||||
for (const p of ['/verify-totp', '/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
|
||||
const res = await api(p, sessions.customer, { body: JSON.stringify({ token: '000000', userId: '1' }), method: 'POST' })
|
||||
expect([p, res.status]).toEqual([p, 403])
|
||||
}
|
||||
})
|
||||
|
||||
test('a staff password without the code cannot reset or remove TOTP', async () => {
|
||||
const admin = await secretOf('[email protected]')
|
||||
for (const p of ['/remove-totp', '/admin/remove-user-totp', '/admin/reset-user-totp']) {
|
||||
const res = await api(p, sessions.passwordOnly, { body: JSON.stringify({ token: totp(TOTP_SECRET), userId: String(admin.id) }), method: 'POST' })
|
||||
expect([p, res.status]).toEqual([p, 403])
|
||||
}
|
||||
expect((await secretOf('[email protected]')).totpSecret).toBe(TOTP_SECRET)
|
||||
})
|
||||
})
|
||||
|
||||
describe('per-entity opt-out from the second factor', () => {
|
||||
test("the package's key: custom.totp.disableAccessWrapper.<operation>", async () => {
|
||||
expect((await api('/open-notes', sessions.passwordOnly)).status).toBe(200) // read opted out
|
||||
expect((await api('/open-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403) // create not
|
||||
expect((await api('/open-notes', sessions.anonymous)).status).toBe(403) // its own rule still applies
|
||||
})
|
||||
|
||||
test("ipal-kit's key: custom.ipal.secondFactor", async () => {
|
||||
expect((await api('/open-tasks', sessions.passwordOnly)).status).toBe(200)
|
||||
expect((await api('/open-tasks', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
// Last: it replaces the running config.
|
||||
describe('dev hot reload', () => {
|
||||
test('a freshly built config is guarded again, also what a later plugin added', async () => {
|
||||
// What Payload's reload() does to the instance: a newly built and sanitized config, no onInit.
|
||||
const fresh = await makeConfig()
|
||||
payload.config = fresh
|
||||
payload.collections = Object.fromEntries(
|
||||
fresh.collections.map((c) => [c.slug, { config: c, customIDType: payload.collections[c.slug as never]?.customIDType }]),
|
||||
) as never
|
||||
payload.globals = { config: fresh.globals }
|
||||
|
||||
expect((await api('/late-notes', sessions.passwordOnly)).status).toBe(403)
|
||||
expect((await api('/late-notes', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403)
|
||||
expect((await api('/globals/site-integrations', sessions.passwordOnly)).status).toBe(403)
|
||||
expect((await api('/late-notes', sessions.verified)).status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* 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)
|
||||
})
|
||||
@@ -5,7 +5,6 @@
|
||||
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'
|
||||
@@ -14,6 +13,7 @@ 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 { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
@@ -32,7 +32,7 @@ beforeAll(async () => {
|
||||
{ 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 }),
|
||||
db: testDatabase('sechttp_tok'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
ipalKit({
|
||||
|
||||
Reference in New Issue
Block a user