Files
ipal-kit/test/submitForm.test.ts
T
radoslaw.smolinskiandClaude Opus 5.5 ce0a390351 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]>
2026-10-15 23:54:25 +02:00

160 lines
5.9 KiB
TypeScript

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' },
],
}),
}),
)
})
})