Security: mandatory Turnstile when configured, admin-only test email, roles on create, safer client IP

- Turnstile is on only when both keys are set (panel or env); then submitForm
  requires a valid token, so a bot can no longer skip the check by omitting it.
  Not configured -> no widget, no check. New getTurnstileConfig() for layouts.
- /api/ipal/test-email now requires the admin role (403 for other users).
- roles field: create access is admin-only, so open sign-up can't self-assign admin.
- clientIp reads X-Forwarded-For from the right, accepts Headers, can be pinned
  via option or IPAL_IP_HEADER; exposed on search/MCP routes.
- Pluggable shared rate-limit store (setRateLimitStore) for multi-instance setups.
- Replace the template int.spec with real unit tests in test/ (44 tests).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-15 23:54:25 +02:00
co-authored by Claude Opus 5.5
parent aa284736c9
commit ce0a390351
25 changed files with 786 additions and 133 deletions
+75
View File
@@ -0,0 +1,75 @@
import type { FieldAccess, PayloadRequest } from 'payload'
import { describe, expect, test, vi } from 'vitest'
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'] }
describe('role predicates', () => {
test('hierarchy admin > editor > user', () => {
expect(isAdmin(admin)).toBe(true)
expect(isAdmin(editor)).toBe(false)
expect(isEditor(admin)).toBe(true)
expect(isEditor(user)).toBe(false)
expect(hasMinimumRole(user, 'user')).toBe(true)
})
test('unknown roles and odd shapes grant nothing', () => {
expect(isAdmin({ roles: ['root'] })).toBe(false)
expect(isAdmin({ roles: 'admin' })).toBe(false)
expect(isAdmin(null)).toBe(false)
})
})
describe('roles field', () => {
const field = buildRolesField() as { access: { create: FieldAccess; update: FieldAccess } }
const call = (fn: FieldAccess, u: unknown) => fn({ req: { 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)
})
test('only admins can change roles', () => {
expect(call(field.access.update, editor)).toBe(false)
expect(call(field.access.update, admin)).toBe(true)
})
})
describe('test-email endpoint', () => {
const run = (u: unknown) => {
const sendEmail = vi.fn(async () => ({ sent: true }))
const req = {
data: { to: '[email protected]' },
payload: { logger: { error: vi.fn() }, sendEmail },
user: u,
} as unknown as PayloadRequest
return { response: testEmailEndpoint.handler(req), sendEmail }
}
test('anonymous → 401', async () => {
const { response, sendEmail } = run(null)
expect((await response).status).toBe(401)
expect(sendEmail).not.toHaveBeenCalled()
})
test('logged-in non-admin → 403', async () => {
const { response, sendEmail } = run(editor)
expect((await response).status).toBe(403)
expect(sendEmail).not.toHaveBeenCalled()
})
test('admin → sends', async () => {
const { response, sendEmail } = run(admin)
expect((await response).status).toBe(200)
expect(sendEmail).toHaveBeenCalledOnce()
})
})
+25
View File
@@ -0,0 +1,25 @@
import type { BasePayload } from 'payload'
import { vi } from 'vitest'
type FakeOptions = {
forms?: Record<string, { fields: Record<string, unknown>[] }>
integrations?: Record<string, unknown>
}
/** The slice of the Local API the form/Turnstile code touches. */
export function fakePayload({ forms = {}, integrations = {} }: FakeOptions = {}) {
const create = vi.fn(async () => ({ id: 'sub-1' }))
const payload = {
create,
findByID: vi.fn(async ({ id }: { id: string }) => {
const form = forms[id]
if (!form) {throw new Error('Not Found')}
return { id, ...form }
}),
findGlobal: vi.fn(async () => integrations),
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
updateGlobal: vi.fn(async () => integrations),
}
return { create, payload: payload as unknown as BasePayload }
}
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, test } from 'vitest'
import { buildLocalizedPath, switchLocalePath } from '../src/modules/i18n/localizedPath.js'
import { matchAcceptLanguage, negotiateLocale } from '../src/modules/i18n/negotiateLocale.js'
import { isHoneypotTripped } from '../src/modules/forms/honeypot.js'
const config = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const single = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
describe('negotiateLocale', () => {
test('cookie → Accept-Language → default', () => {
expect(negotiateLocale({ acceptLanguage: 'en', config, cookieLocale: 'pl' })).toBe('pl')
expect(negotiateLocale({ acceptLanguage: 'de-DE,en-US;q=0.8', config })).toBe('en')
expect(negotiateLocale({ acceptLanguage: 'fr', config, cookieLocale: 'xx' })).toBe('pl')
})
test('respects q-values', () => {
expect(matchAcceptLanguage('en;q=0.5,pl;q=0.9', config)).toBe('pl')
expect(matchAcceptLanguage(null, config)).toBeUndefined()
})
})
describe('buildLocalizedPath', () => {
const slugs = { en: 'about', pl: 'o-nas' }
test('prefixes the locale', () => {
expect(buildLocalizedPath({ config, locale: 'en', slugs })).toBe('/en/about')
})
test('home collapses to the locale root, per-locale home slugs', () => {
const home = { en: 'home', pl: 'strona-glowna' }
expect(buildLocalizedPath({ config, homeSlug: home, locale: 'pl', slugs: home })).toBe('/pl')
expect(buildLocalizedPath({ config, homeSlug: home, locale: 'en', slugs: home })).toBe('/en')
})
test('single-locale sites drop the prefix', () => {
expect(buildLocalizedPath({ config: single, locale: 'pl', slugs })).toBe('/o-nas')
expect(buildLocalizedPath({ config: single, locale: 'pl', slugs: { pl: 'home' } })).toBe('/')
})
test('archive entries need a prefix in that locale', () => {
const prefix = { pl: 'artykuly' }
expect(buildLocalizedPath({ config, locale: 'pl', prefix, slugs })).toBe('/pl/artykuly/o-nas')
expect(buildLocalizedPath({ config, locale: 'en', prefix, slugs })).toBeUndefined()
})
test('unknown locale or missing slug → undefined', () => {
expect(buildLocalizedPath({ config, locale: 'de', slugs })).toBeUndefined()
expect(buildLocalizedPath({ config, locale: 'en', slugs: { pl: 'x' } })).toBeUndefined()
})
})
describe('switchLocalePath', () => {
test('never dead-ends: falls back to archive, then locale root', () => {
expect(switchLocalePath({ config, slugs: { pl: 'post' }, targetLocale: 'en', prefix: { en: 'articles', pl: 'artykuly' } })).toBe(
'/en/articles',
)
expect(switchLocalePath({ config, slugs: { pl: 'o-nas' }, targetLocale: 'en' })).toBe('/en')
})
})
describe('honeypot', () => {
test('filled → tripped', () => {
expect(isHoneypotTripped({ company_url: 'http://spam' })).toBe(true)
expect(isHoneypotTripped({ company_url: ' ' })).toBe(false)
expect(isHoneypotTripped({})).toBe(false)
})
})
+51
View File
@@ -0,0 +1,51 @@
import type { Config } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import { ipalKit } from '../src/plugin.js'
const i18n = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const base = (): Config =>
({
collections: [{ slug: 'users', auth: true, fields: [] }],
secret: 'test',
}) as unknown as Config
describe('ipalKit — config transform', () => {
test('adds globals, endpoint, localization and roles', async () => {
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base())
expect(config.globals?.map((g) => g.slug)).toEqual(
expect.arrayContaining(['site-settings', 'site-integrations']),
)
expect(config.endpoints?.some((e) => e.path === '/ipal/test-email')).toBe(true)
expect(config.localization && config.localization.defaultLocale).toBe('pl')
const users = config.collections?.find((c) => c.slug === 'users')
expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true)
})
test('enforces 2FA unless explicitly disabled', async () => {
await expect(ipalKit({ i18n })(base())).rejects.toThrow(/twoFactor\.issuer is required/)
const totp = vi.fn(() => (c: Config) => c)
await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } }))
})
test('enabled: false leaves the config untouched', async () => {
const config = base()
expect(await ipalKit({ enabled: false, i18n, twoFactor: false })(config)).toBe(config)
})
test('invalid i18n fails fast', () => {
expect(() => ipalKit({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow()
})
})
+97
View File
@@ -0,0 +1,97 @@
import { afterEach, describe, expect, test, vi } from 'vitest'
import {
checkRateLimit,
clientIp,
consumeRateLimit,
setRateLimitStore,
} from '../src/modules/shared/rateLimit.js'
const req = (headers: Record<string, string>) => new Request('http://x/', { headers })
describe('clientIp', () => {
afterEach(() => {
vi.unstubAllEnvs()
})
test('prefers cf-connecting-ip, then x-real-ip', () => {
expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-real-ip': '2.2.2.2' }))).toBe('1.1.1.1')
expect(clientIp(req({ 'x-forwarded-for': '9.9.9.9', 'x-real-ip': '2.2.2.2' }))).toBe('2.2.2.2')
})
test('takes X-Forwarded-For from the right, so a spoofed left entry is ignored', () => {
const r = req({ 'x-forwarded-for': '6.6.6.6, 3.3.3.3' })
expect(clientIp(r)).toBe('3.3.3.3')
expect(clientIp(r, { trustedProxies: 2 })).toBe('6.6.6.6')
expect(clientIp(r, { trustedProxies: 5 })).toBe('6.6.6.6')
})
test('a pinned header is the only one read', () => {
const r = req({ 'cf-connecting-ip': '1.1.1.1', 'x-real-ip': '2.2.2.2' })
expect(clientIp(r, { header: 'x-real-ip' })).toBe('2.2.2.2')
expect(clientIp(r, { header: 'x-client-ip' })).toBe('')
})
test('IPAL_IP_HEADER env pins the header', () => {
vi.stubEnv('IPAL_IP_HEADER', 'x-forwarded-for')
expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-forwarded-for': '6.6.6.6, 4.4.4.4' }))).toBe('4.4.4.4')
})
test('accepts Headers (server actions)', () => {
expect(clientIp(new Headers({ 'x-real-ip': '5.5.5.5' }))).toBe('5.5.5.5')
})
test('empty when nothing usable is present', () => {
expect(clientIp(req({}))).toBe('')
})
})
describe('checkRateLimit (in memory)', () => {
test('allows up to max per window, then blocks', () => {
const key = `k-${Math.random()}`
for (let i = 0; i < 3; i++) {expect(checkRateLimit({ key, max: 3 })).toBe(true)}
expect(checkRateLimit({ key, max: 3 })).toBe(false)
})
test('scopes are independent', () => {
const key = `k-${Math.random()}`
expect(checkRateLimit({ key, max: 1, scope: 'a' })).toBe(true)
expect(checkRateLimit({ key, max: 1, scope: 'b' })).toBe(true)
expect(checkRateLimit({ key, max: 1, scope: 'a' })).toBe(false)
})
test('a cost above max is refused outright', () => {
expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false)
})
test('no key → allowed', () => {
expect(checkRateLimit({ key: '', max: 0 })).toBe(true)
})
})
describe('consumeRateLimit', () => {
afterEach(() => setRateLimitStore(null))
test('in memory: blocks after max and reports Retry-After', async () => {
const key = `k-${Math.random()}`
expect((await consumeRateLimit({ key, max: 1, windowMs: 30_000 })).ok).toBe(true)
const blocked = await consumeRateLimit({ key, max: 1, windowMs: 30_000 })
expect(blocked.ok).toBe(false)
expect(blocked.retryAfter).toBeGreaterThan(25)
})
test('uses the configured store', async () => {
const hit = vi.fn(async () => ({ count: 7, resetAt: Date.now() + 10_000 }))
setRateLimitStore({ hit })
const result = await consumeRateLimit({ cost: 2, key: 'ip', max: 5, scope: 'mcp', windowMs: 10_000 })
expect(hit).toHaveBeenCalledWith('mcp:ip', 2, 10_000)
expect(result.ok).toBe(false)
})
test('a failing store lets the request through', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
setRateLimitStore({ hit: () => Promise.reject(new Error('redis down')) })
expect((await consumeRateLimit({ key: 'ip', max: 0 })).ok).toBe(true)
warn.mockRestore()
})
})
+159
View File
@@ -0,0 +1,159 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { fakePayload } from './helpers.js'
vi.mock('server-only', () => ({}))
const forms = {
contact: {
fields: [
{ name: 'name', blockType: 'text', required: true },
{ name: 'consent', blockType: 'checkbox' },
{ blockType: 'message' },
],
},
}
const data = { consent: true, name: 'Ala' }
const keys = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' }
let ipCounter = 0
const nextIp = () => `10.0.0.${++ipCounter}`
function mockSiteverify(body: unknown, status = 200) {
return vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json(body, { status }))
}
describe('submitForm — Turnstile', () => {
beforeEach(() => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
test('not configured → no check, the submission is stored', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch')
const { create, payload } = fakePayload({ forms })
const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload })
expect(result).toEqual({ submissionId: 'sub-1', success: true })
expect(create).toHaveBeenCalledOnce()
expect(fetchSpy).not.toHaveBeenCalled()
})
test('half-configured (site key only) counts as off', async () => {
const { payload } = fakePayload({ forms, integrations: { turnstileSiteKey: 'site' } })
expect((await submitForm({ data, formId: 'contact', ip: nextIp(), payload })).success).toBe(true)
})
test('configured → a MISSING token is rejected (no opting out by omission)', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch')
const { create, payload } = fakePayload({ forms, integrations: keys })
const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload })
expect(result).toEqual({ reason: 'turnstile', success: false })
expect(create).not.toHaveBeenCalled()
expect(fetchSpy).not.toHaveBeenCalled()
})
test('configured from env vars counts too', async () => {
vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', 'site')
vi.stubEnv('TURNSTILE_SECRET_KEY', 'secret')
const { payload } = fakePayload({ forms })
expect(await submitForm({ data, formId: 'contact', ip: nextIp(), payload })).toEqual({
reason: 'turnstile',
success: false,
})
})
test('configured + valid token → stored', async () => {
mockSiteverify({ success: true })
const { create, payload } = fakePayload({ forms, integrations: keys })
const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload, turnstileToken: 'tok' })
expect(result.success).toBe(true)
expect(create).toHaveBeenCalledOnce()
})
test('configured + bad token → rejected', async () => {
mockSiteverify({ 'error-codes': ['invalid-input-response'], success: false })
const { create, payload } = fakePayload({ forms, integrations: keys })
const result = await submitForm({ data, formId: 'contact', ip: nextIp(), payload, turnstileToken: 'bad' })
expect(result).toEqual({ reason: 'turnstile', success: false })
expect(create).not.toHaveBeenCalled()
})
test('configured + Cloudflare rejects OUR secret → allowed by default, refused with reject', async () => {
mockSiteverify({ 'error-codes': ['invalid-input-secret'], success: false })
const { payload } = fakePayload({ forms, integrations: keys })
const base = { data, formId: 'contact', payload, turnstileToken: 'tok' }
expect((await submitForm({ ...base, ip: nextIp() })).success).toBe(true)
expect(await submitForm({ ...base, ip: nextIp(), turnstileOnConfigError: 'reject' })).toEqual({
reason: 'turnstile',
success: false,
})
})
})
describe('submitForm — other gates', () => {
afterEach(() => vi.restoreAllMocks())
test('rate limit per IP', async () => {
const { payload } = fakePayload({ forms })
const ip = nextIp()
for (let i = 0; i < 2; i++) {
expect((await submitForm({ data, formId: 'contact', ip, maxPerMinute: 2, payload })).success).toBe(true)
}
expect(await submitForm({ data, formId: 'contact', ip, maxPerMinute: 2, payload })).toEqual({
reason: 'rate_limited',
success: false,
})
})
test('consent must be checked', async () => {
const { payload } = fakePayload({ forms })
expect(await submitForm({ data: { ...data, consent: false }, formId: 'contact', ip: nextIp(), payload })).toEqual({
field: 'consent',
reason: 'consent',
success: false,
})
})
test('required field, unknown keys, unknown form', async () => {
const { payload } = fakePayload({ forms })
const ip = nextIp()
expect(await submitForm({ data: { consent: true }, formId: 'contact', ip, maxPerMinute: 0, payload })).toEqual({
field: 'name',
kind: 'required',
reason: 'validation',
success: false,
})
expect(
await submitForm({ data: { ...data, admin: 1 }, formId: 'contact', ip, maxPerMinute: 0, payload }),
).toEqual({ kind: 'unknown_fields', reason: 'validation', success: false })
expect(await submitForm({ data, formId: 'nope', ip, maxPerMinute: 0, payload })).toEqual({
reason: 'not_found',
success: false,
})
})
test('the captcha field injected by the widget is not an unknown key', async () => {
const { create, payload } = fakePayload({ forms })
const result = await submitForm({
data: { ...data, 'cf-turnstile-response': 'x' },
formId: 'contact',
ip: nextIp(),
payload,
})
expect(result.success).toBe(true)
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
submissionData: [
{ field: 'name', value: 'Ala' },
{ field: 'consent', value: 'true' },
],
}),
}),
)
})
})