/** * Form files end to end through a REAL Payload (SQLite in memory): the form is * built in the "panel" (Local API), the browser's multipart request goes to the * real endpoint handler as a stream, and the e-mails land in a recording adapter. * * The groups follow the seven acceptance tests of the client request * (vanstevpl-web, 2026-11-13), re-read for "files are e-mailed, never stored". */ import type { Payload, PayloadEmailAdapter, PayloadRequest } from 'payload' import { sqliteAdapter } from '@payloadcms/db-sqlite' import { lexicalEditor } from '@payloadcms/richtext-lexical' import { readdirSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import zlib from 'node:zlib' import { getPayload } from 'payload' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' import type { FormFileScanInput } from '../src/modules/forms/attachments/config.js' import { getFormAttachments } from '../src/modules/forms/attachments/config.js' import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js' import { submitForm } from '../src/modules/forms/submitForm.js' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' vi.mock('server-only', () => ({})) const MB = 1024 * 1024 const mediaDir = path.join(os.tmpdir(), 'ipal-test-form-files-media') // ---- sample files ------------------------------------------------------------------------- const utf16 = (text: string) => Buffer.from(text, 'utf16le') const pad = (head: Buffer, size: number) => Buffer.concat([head, Buffer.alloc(Math.max(0, size - head.length), 0x20)]) /** A stored (uncompressed) ZIP with the given entries — enough for the container checks. */ function zip(entries: Record): Buffer { const locals: Buffer[] = [] const central: Buffer[] = [] let offset = 0 for (const [name, content] of Object.entries(entries)) { const data = Buffer.from(content) const file = Buffer.from(name) const crc = zlib.crc32(data) const local = Buffer.alloc(30) local.writeUInt32LE(0x04034b50, 0) local.writeUInt16LE(20, 4) local.writeUInt32LE(crc, 14) local.writeUInt32LE(data.length, 18) local.writeUInt32LE(data.length, 22) local.writeUInt16LE(file.length, 26) const header = Buffer.alloc(46) header.writeUInt32LE(0x02014b50, 0) header.writeUInt16LE(20, 4) header.writeUInt16LE(20, 6) header.writeUInt32LE(crc, 16) header.writeUInt32LE(data.length, 20) header.writeUInt32LE(data.length, 24) header.writeUInt16LE(file.length, 28) header.writeUInt32LE(offset, 42) locals.push(local, file, data) central.push(header, file) offset += 30 + file.length + data.length } const directory = Buffer.concat(central) const end = Buffer.alloc(22) end.writeUInt32LE(0x06054b50, 0) end.writeUInt16LE(Object.keys(entries).length, 8) end.writeUInt16LE(Object.keys(entries).length, 10) end.writeUInt32LE(directory.length, 12) end.writeUInt32LE(offset, 16) return Buffer.concat([...locals, directory, end]) } const OLE = Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]) const PDF = pad(Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), 4096) const DOC = pad(Buffer.concat([OLE, utf16('WordDocument')]), 2048) const DOC_MACRO = pad(Buffer.concat([OLE, utf16('WordDocument'), utf16('Macros'), utf16('_VBA_PROJECT')]), 2048) const DOCX = zip({ '[Content_Types].xml': '', 'word/document.xml': '' }) const DOCX_MACRO = zip({ '[Content_Types].xml': '', 'word/document.xml': '', 'word/vbaProject.bin': 'x' }) const EXE = pad(Buffer.from('MZ\x90\x00\x03'), 1024) const ARCHIVE = zip({ 'readme.txt': 'hello' }) // ---- the site ------------------------------------------------------------------------------ type Mail = { attachments?: { content: Buffer; contentType: string; filename: string }[]; html: string; subject: string; to: string } const mails: Mail[] = [] let mailMode: 'ok' | 'refuse' | 'throw' = 'ok' const recordingMail: PayloadEmailAdapter = () => ({ name: 'test-mail', defaultFromAddress: 'site@acme.test', defaultFromName: 'Acme', sendEmail: (message) => { const mail = message as unknown as Mail mails.push(mail) // Only the message that carries a file is refused — like a server with a size limit. if (mail.attachments?.length && mailMode === 'refuse') {return Promise.resolve({ detail: '552 5.3.4 Message size exceeds fixed limit', error: 'The e-mail was not sent.', sent: false })} if (mail.attachments?.length && mailMode === 'throw') {return Promise.reject(new Error('connect ECONNREFUSED'))} return Promise.resolve({ messageId: 'ok' }) }, }) const scanned: FormFileScanInput[] = [] let scanVerdict = true const text = (value: string) => ({ root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: value, version: 1 }], direction: null, format: '', indent: 0, version: 1 }], direction: null, format: '', indent: 0, version: 1, }, }) let payload: Payload let formId: string let ipCounter = 0 beforeAll(async () => { payload = await getPayload({ config: buildTestConfig({ collections: [ { slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: mediaDir } }, ], // SQLite in memory by default; IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI run the same tests there (on // Postgres the e-mails go out after the submission's transaction commits: forms.emailsInTransaction). db: testDatabase('formfiles'), editor: lexicalEditor(), email: recordingMail, plugins: [ iapl({ access: { authCollection: 'users' }, forms: { attachments: { maxConcurrent: 0, maxSizeMB: 1, scan: (file) => { scanned.push(file) return { ok: scanVerdict } }, }, }, i18n: { defaultLocale: 'pl', locales: [ { code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }, { code: 'de', label: 'Deutsch' }, { code: 'nl', label: 'Nederlands' }, ], }, twoFactor: false, }), ], secret: 'form-files-test-secret', telemetry: false, }), }) // Built in the default language first, then the English texts on the same rows. const base = { confirmationMessage: text('Thank you'), emails: [ { emailFrom: 'site@acme.test', emailTo: 'jobs@acme.test', message: text('New application from {{name}}: {{attachment}}'), subject: 'Application' }, { emailFrom: 'site@acme.test', emailTo: '{{email}}', message: text('We got your application, {{name}}.'), subject: 'Thank you' }, ], fields: [ { name: 'name', blockType: 'text', label: 'Name', required: true }, { name: 'email', blockType: 'email', label: 'E-mail', required: true }, { name: 'attachment', allowedTypes: ['pdf', 'doc', 'docx'], blockType: 'file', help: 'PDF, DOC or DOCX, up to 1 MB', label: 'Załącznik (opcjonalnie)', maxFiles: 1, maxSizeMB: 1 }, { name: 'consent', blockType: 'checkbox', label: 'Consent' }, ], title: 'Careers', } const form = (await payload.create({ collection: 'forms' as never, data: base as never, locale: 'pl' })) as unknown as { emails: Record[] fields: Record[] id: number | string } formId = String(form.id) await payload.update({ id: formId, collection: 'forms' as never, data: { confirmationMessage: base.confirmationMessage, emails: form.emails.map((email, i) => ({ ...email, message: base.emails[i].message, subject: base.emails[i].subject })), fields: form.fields.map(({ resolved: _resolved, ...f }) => (f.name === 'attachment' ? { ...f, help: 'PDF, DOC or DOCX, up to 1 MB', label: 'Attachment (optional)' } : f)), } as never, locale: 'en', }) }, 60_000) afterAll(async () => { await payload?.destroy() }) afterEach(() => { mails.length = 0 scanned.length = 0 mailMode = 'ok' scanVerdict = true vi.unstubAllGlobals() delete process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY delete process.env.TURNSTILE_SECRET_KEY }) type Upload = { data: Buffer; field?: string; name: string } type Post = { attempt?: string files?: Upload[] form?: string headers?: Record ip?: string locale?: string token?: string values?: Record } const answers = { name: 'Jan Kowalski', consent: true, email: 'jan@example.com' } /** The browser's request: answers first, files last — to the real handler, body as a stream. */ async function post({ attempt, files = [], form = formId, headers = {}, ip, locale = 'en', token, values = answers }: Post = {}) { const body = new FormData() body.append('_form', form) body.append('_locale', locale) if (attempt) {body.append('_attempt', attempt)} if (token) {body.append('_token', token)} body.append('_values', JSON.stringify(values)) for (const file of files) {body.append(file.field ?? 'attachment', new File([new Uint8Array(file.data)], file.name))} const request = new Request(`http://localhost/api/ipal/forms/submit?locale=${locale}`, { body, headers: { 'sec-fetch-site': 'same-origin', 'x-real-ip': ip ?? `10.9.${Math.floor(++ipCounter / 250)}.${ipCounter % 250}`, ...headers }, method: 'POST', }) const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest) return { body: (await response.json()) as { field?: string; message: string; reason?: string; success: boolean }, status: response.status } } type Submission = { attemptKey?: string filesDelivery?: string filesDeliveryNote?: string id: number | string submissionData: { field: string; value: string }[] submissionFiles?: { field: string; name: string; size: number; type: string }[] } const submissions = async () => (await payload.find({ collection: 'form-submissions' as never, depth: 0, limit: 200, sort: 'createdAt' })).docs as unknown as Submission[] const count = async () => (await payload.count({ collection: 'form-submissions' as never })).totalDocs const withFile = () => mails.filter((m) => m.attachments?.length) describe('1 · a submission without the optional file works as before', () => { test('through the server action path: stored, both e-mails sent, no file data anywhere', async () => { const before = await count() const result = await submitForm({ data: answers, formId, ip: '10.8.0.1', locale: 'en', payload }) expect(result.success).toBe(true) expect(await count()).toBe(before + 1) expect(mails.map((m) => m.to).sort()).toEqual(['jan@example.com', 'jobs@acme.test']) expect(withFile()).toEqual([]) const stored = (await submissions()).at(-1)! expect(stored.submissionData.map((d) => d.field)).toEqual(['name', 'email', 'consent']) expect(stored.filesDelivery ?? null).toBeNull() expect(stored.submissionFiles ?? []).toEqual([]) }) test('through the endpoint without a file part: the same outcome', async () => { const before = await count() const { body, status } = await post() expect({ status, success: body.success }).toEqual({ status: 200, success: true }) expect(await count()).toBe(before + 1) expect(mails).toHaveLength(2) expect(withFile()).toEqual([]) }) }) describe('2 · each allowed format: one submission, the file in the staff e-mail only', () => { test.each([ ['CV Jan Kowalski.pdf', PDF, 'pdf', 'application/pdf'], ['cv.DOC', DOC, 'doc', 'application/msword'], ['Życiorys (2026).docx', DOCX, 'docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'], ])('%s', async (name, data, type, mime) => { const before = await count() const { body, status } = await post({ files: [{ name, data }] }) expect({ status, success: body.success }).toEqual({ status: 200, success: true }) expect(await count()).toBe(before + 1) // The staff e-mail carries the file, byte for byte; the confirmation to the visitor does not. const staff = mails.filter((m) => m.to === 'jobs@acme.test') expect(staff).toHaveLength(1) expect(staff[0].attachments).toHaveLength(1) const attachment = staff[0].attachments![0] expect(Buffer.compare(attachment.content, data)).toBe(0) expect(attachment.contentType).toBe(mime) expect(attachment.filename).toBe(name.replace(/\.[^.]+$/, `.${type}`)) // the visitor's name (also with Polish letters), the detected extension expect(staff[0].html).toContain(attachment.filename) // {{attachment}} → the readable name expect(staff[0].html).toContain('not checked for viruses') const customer = mails.filter((m) => m.to === 'jan@example.com') expect(customer).toHaveLength(1) expect(customer[0].attachments).toBeUndefined() expect(customer[0].html).not.toContain('viruses') // The submission keeps metadata only. const stored = (await submissions()).at(-1)! expect(stored.submissionFiles).toMatchObject([{ name: attachment.filename, type, field: 'attachment', size: data.length }]) expect(stored.filesDelivery).toBe('sent') expect(stored.submissionData.find((d) => d.field === 'attachment')?.value).toMatch(new RegExp(`\\.${type} \\(\\d+ (?:B|KB)\\)$`)) expect(JSON.stringify(stored)).not.toContain(data.toString('base64').slice(0, 40)) expect(scanned.map((s) => s.type)).toEqual([type]) // the optional scan hook saw exactly this file }) }) describe('3 · refused files leave no submission and send no e-mail', () => { // Every refusal is answered AT the File field, says it is the file, why, and what to do next. const TYPES = 'PDF, DOC, DOCX' const wrongFormat = (name: string) => `The file "${name}" is in a format we do not accept. Choose one of: ${TYPES}. You can also send the form without the file.` const notAcceptable = (name: string) => `The file "${name}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (${TYPES}). You can also send the form without the file.` const refused = async (files: Upload[], expected: string, extra: Post = {}) => { const before = await count() const { body, status } = await post({ files, ...extra }) expect(body.success).toBe(false) expect(status).toBe(422) expect(body.message).toBe(expected) expect(body).toMatchObject({ field: 'attachment', reason: 'validation' }) expect(await count()).toBe(before) expect(mails).toEqual([]) } test('oversized: stopped while reading', async () => { await refused( [{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 200_000) }], 'The file "big.pdf" is too large. Choose a file of up to 1 MB. You can also send the form without the file.', ) expect(scanned).toEqual([]) }) test('mismatched: a program named .pdf, a PDF named .docx, an empty file', async () => { await refused([{ name: 'cv.pdf', data: EXE }], notAcceptable('cv.pdf')) await refused([{ name: 'cv.docx', data: PDF }], notAcceptable('cv.docx')) await refused([{ name: 'cv.pdf', data: Buffer.alloc(0) }], notAcceptable('cv.pdf')) }) test('another format: the message names the formats the field takes', async () => { await refused([{ name: 'photo.png', data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }], wrongFormat('photo.png')) await refused([{ name: 'notes.txt', data: Buffer.from('hello') }], wrongFormat('notes.txt')) await refused([{ name: 'cv', data: PDF }], wrongFormat('cv')) }) test('refused files: program, double extension, archive, macro-enabled Office — the message says the file was refused', async () => { await refused([{ name: 'cv.exe', data: EXE }], notAcceptable('cv.exe')) await refused([{ name: 'cv.pdf.exe', data: EXE }], notAcceptable('cv.pdf.exe')) await refused([{ name: 'cv.exe.pdf', data: PDF }], notAcceptable('cv.exe.pdf')) await refused([{ name: 'cv.pdf.docx', data: DOCX }], notAcceptable('cv.pdf.docx')) await refused([{ name: 'cv.zip', data: ARCHIVE }], notAcceptable('cv.zip')) await refused([{ name: 'cv.docm', data: DOCX_MACRO }], notAcceptable('cv.docm')) }) test('the right container with macros inside: DOCX with a macro project, DOC with a macro storage', async () => { await refused([{ name: 'cv.docx', data: DOCX_MACRO }], notAcceptable('cv.docx')) await refused([{ name: 'cv.doc', data: DOC_MACRO }], notAcceptable('cv.doc')) await refused([{ name: 'cv.docx', data: ARCHIVE }], notAcceptable('cv.docx')) // a ZIP that is not a Word file }) test('a program inside an Office file is found also with trailing dots or spaces (Windows drops them)', async () => { for (const entry of ['word/setup.exe', 'word/setup.exe.', 'word/setup.exe ', 'word/setup.EXE. .', 'word/vbaProject.bin.']) { const data = zip({ '[Content_Types].xml': '', [entry]: 'x', 'word/document.xml': '' }) await refused([{ name: 'cv.docx', data }], notAcceptable('cv.docx')) } }) test('extra files: more than the field allows, a file under a key that is no File field', async () => { await refused( [{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }], 'Too many files in "Attachment (optional)". Remove some: the limit is 1. You can also send the form without the file.', ) const before = await count() const { body } = await post({ files: [{ name: 'a.pdf', data: PDF, field: 'name' }], values: { consent: true, email: 'jan@example.com' } }) expect(body.success).toBe(false) expect(await count()).toBe(before) expect(mails).toEqual([]) }) test('direct calls that skip the form: text under the File key, a stringified File, a media id', async () => { const before = await count() for (const attachment of ['[object File]', '65f0c0ffee', { id: 1 }]) { const result = await submitForm({ data: { ...answers, attachment }, formId, ip: '10.8.0.9', maxPerMinute: 0, payload }) expect(result).toMatchObject({ field: 'attachment', reason: 'validation', success: false }) } expect(await count()).toBe(before) }) test('the antivirus hook can refuse a file that passed everything else', async () => { scanVerdict = false await refused([{ name: 'cv.pdf', data: PDF }], notAcceptable('cv.pdf')) expect(scanned).toHaveLength(1) }) test('a body that declares itself too large is refused unread', async () => { const before = await count() const request = new Request('http://localhost/api/ipal/forms/submit?locale=en', { body: 'x', headers: { 'content-length': String(50 * MB), 'content-type': 'multipart/form-data; boundary=x', 'sec-fetch-site': 'same-origin', 'x-real-ip': '10.8.1.1' }, method: 'POST', }) const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest) expect(response.status).toBe(413) expect(await count()).toBe(before) }) }) describe('4 · no gate can be bypassed by attaching a file', () => { const blocked = async (extra: Post, status: number, reason: string | undefined) => { const before = await count() const result = await post({ files: [{ name: 'cv.pdf', data: PDF }], ...extra }) expect(result.status).toBe(status) expect(result.body.reason).toBe(reason) expect(await count()).toBe(before) expect(mails).toEqual([]) expect(scanned).toEqual([]) // the file was never taken in return result } test('missing consent', async () => { const { body } = await blocked({ values: { ...answers, consent: false } }, 422, 'consent') expect(body.message).toMatch(/privacy policy/) }) test('a required field left empty', async () => { await blocked({ values: { consent: true, email: 'jan@example.com' } }, 422, 'validation') }) test('Turnstile configured: no token, and a token Cloudflare rejects', async () => { process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY = 'site-key' process.env.TURNSTILE_SECRET_KEY = 'secret-key' vi.stubGlobal('fetch', vi.fn(async () => Response.json({ 'error-codes': ['invalid-input-response'], success: false }))) await blocked({}, 403, 'turnstile') await blocked({ token: 'forged' }, 403, 'turnstile') }) test('a tripped honeypot: a fake success, nothing stored, nothing sent', async () => { const before = await count() const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }], values: { ...answers, company_url: 'http://spam.example' } }) expect({ status, success: body.success }).toEqual({ status: 200, success: true }) expect(await count()).toBe(before) expect(mails).toEqual([]) expect(scanned).toEqual([]) }) test('rate limit: the sixth request in a minute from one address is refused before its body is read', async () => { const ip = '10.8.2.2' for (let i = 0; i < 5; i++) {await post({ ip, values: { ...answers, consent: false } })} await blocked({ ip }, 429, 'rate_limited') }) test('another site cannot post to the endpoint; REST cannot create a submission', async () => { await blocked({ headers: { origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' } }, 403, 'error') await expect( payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [] } as never, overrideAccess: false }), ).rejects.toThrow() }) test('a file sent before the answers is not accepted', async () => { const before = await count() const body = new FormData() body.append('attachment', new File([new Uint8Array(PDF)], 'cv.pdf')) body.append('_form', formId) body.append('_values', JSON.stringify(answers)) const request = new Request('http://localhost/api/ipal/forms/submit?locale=en', { body, headers: { 'sec-fetch-site': 'same-origin', 'x-real-ip': '10.8.2.9' }, method: 'POST' }) const response = await handleFormSubmit(Object.assign(request, { payload }) as unknown as PayloadRequest) expect(response.status).toBeGreaterThanOrEqual(400) expect(await count()).toBe(before) expect(mails).toEqual([]) }) }) describe('5 · nothing is stored, nothing can be downloaded', () => { test('no upload collection, no file on disk, no route that serves a file', async () => { await post({ files: [{ name: 'cv.pdf', data: PDF }] }) expect(withFile()).toHaveLength(1) // The only upload collection is the project's own Media, and it is empty. const uploads = payload.config.collections.filter((c) => c.upload).map((c) => c.slug) expect(uploads).toEqual(['media']) expect((await payload.count({ collection: 'media' as never })).totalDocs).toBe(0) let onDisk: string[] = [] try { onDisk = readdirSync(mediaDir) } catch { /* the directory was never created */ } expect(onDisk).toEqual([]) // The submission has no upload relation — form-builder's own upload storage stays off. const fields = payload.collections['form-submissions' as never].config.fields.map((f) => ('name' in f ? f.name : '')) expect(fields).not.toContain('submissionUploads') // One endpoint, POST only. const mine = (payload.config.endpoints ?? []).filter((e) => e.path.includes('forms')) expect(mine.map((e) => `${e.method} ${e.path}`)).toEqual(['post /ipal/forms/submit']) }) test('the option is opt-in: without it the config has no File block, no endpoint, no extra fields', async () => { const plain = await buildTestConfig({ collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }], db: sqliteAdapter({ client: { url: 'file::memory:' } }), editor: lexicalEditor(), plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })], secret: 'x', }) const forms = plain.collections.find((c) => c.slug === 'forms')! const blocks = (forms.fields.find((f) => 'name' in f && f.name === 'fields') as { blocks: { slug: string }[] }).blocks.map((b) => b.slug) expect(blocks).not.toContain('file') expect((plain.endpoints ?? []).some((e) => e.path.includes('forms/submit'))).toBe(false) const submissionFields = plain.collections.find((c) => c.slug === 'form-submissions')!.fields.map((f) => ('name' in f ? f.name : '')) expect(submissionFields.filter((name) => /file|attempt/i.test(name))).toEqual([]) expect((plain.custom as { ipal?: { formAttachments?: unknown } } | undefined)?.ipal?.formAttachments).toBeUndefined() }) }) describe('6 · failed send, retry, repeated request', () => { test('the mail server refuses the message: the visitor is told, staff get a notice, the attempt is marked', async () => { mailMode = 'refuse' const before = await count() const { body, status } = await post({ files: [{ name: 'cv.pdf', data: PDF }] }) expect(status).toBe(502) // The visitor is told it is the FILE, at the File field, and what to do — never the mail server's words. expect(body).toEqual({ field: 'attachment', message: 'We could not send the file "cv.pdf". Choose a smaller file or another format and try again. You can also send the form without the file.', reason: 'delivery', success: false, }) expect(JSON.stringify(body)).not.toMatch(/552|size exceeds|smtp|ECONN/i) const stored = (await submissions()).at(-1)! expect(await count()).toBe(before + 1) expect(stored.filesDelivery).toBe('failed') expect(stored.filesDeliveryNote).toContain('552') expect(stored.submissionFiles).toHaveLength(1) // One attempt with the file, then the notice without it. No confirmation to the visitor. expect(mails.map((m) => [m.to, m.attachments?.length ?? 0])).toEqual([['jobs@acme.test', 1], ['jobs@acme.test', 0]]) expect(mails[1].html).toContain('could not be sent') expect(mails[1].html).not.toContain('viruses') // The retry is a new attempt and goes through once. mails.length = 0 mailMode = 'ok' const retry = await post({ files: [{ name: 'cv.pdf', data: PDF }] }) expect(retry.body.success).toBe(true) expect(await count()).toBe(before + 2) expect(withFile()).toHaveLength(1) expect(mails.filter((m) => m.to === 'jan@example.com')).toHaveLength(1) }) test('an adapter that throws is a failed send too', async () => { mailMode = 'throw' const { body } = await post({ files: [{ name: 'cv.pdf', data: PDF }] }) expect(body).toMatchObject({ field: 'attachment', reason: 'delivery' }) expect(body.message).not.toMatch(/ECONNREFUSED/) expect((await submissions()).at(-1)!.filesDelivery).toBe('failed') }) test('the same attempt key again: the first answer, no second submission, no second e-mail', async () => { const before = await count() const attempt = 'attempt-0123456789abcdef' const first = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }) expect(first.body.success).toBe(true) const sent = mails.length const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }) expect(again.body).toEqual(first.body) expect(await count()).toBe(before + 1) expect(mails).toHaveLength(sent) expect(scanned).toHaveLength(1) }) test('two identical requests at the same moment: one submission, one e-mail with the file', async () => { const before = await count() const attempt = 'attempt-concurrent-000001' const [a, b] = await Promise.all([ post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }), post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }), ]) expect(a.body.success && b.body.success).toBe(true) expect(await count()).toBe(before + 1) expect(withFile()).toHaveLength(1) }) test('a failed attempt repeated with its key stays failed and sends nothing more', async () => { mailMode = 'refuse' const attempt = 'attempt-failed-0000000001' await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }) const before = await count() mails.length = 0 mailMode = 'ok' const again = await post({ attempt, files: [{ name: 'cv.pdf', data: PDF }] }) expect(again.body).toMatchObject({ field: 'attachment', reason: 'delivery' }) expect(again.body.message).toContain('We could not send the file "cv.pdf".') expect(await count()).toBe(before) expect(mails).toEqual([]) }) }) describe('7 · languages, the panel, limits', () => { test('messages follow the page language: Polish and English defaults, German and Dutch from the panel', async () => { await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileOptional: 'Sie können das Formular auch ohne Datei senden.', fileTooLarge: 'Die Datei „{file}“ ist zu groß. Wählen Sie eine Datei bis {max} MB.' } } as never, locale: 'de', }) await payload.updateGlobal({ slug: 'notifications' as never, data: { form: { fileOptional: 'U kunt het formulier ook zonder bestand versturen.', fileTooLarge: 'Het bestand "{file}" is te groot. Kies een bestand tot {max} MB.' } } as never, locale: 'nl' }) const big = [{ name: 'big.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 10) }] expect((await post({ files: big, locale: 'pl' })).body.message).toBe('Plik „big.pdf” jest za duży. Wybierz plik do 1 MB. Możesz też wysłać formularz bez pliku.') expect((await post({ files: big, locale: 'en' })).body.message).toBe('The file "big.pdf" is too large. Choose a file of up to 1 MB. You can also send the form without the file.') expect((await post({ files: big, locale: 'de' })).body.message).toBe('Die Datei „big.pdf“ ist zu groß. Wählen Sie eine Datei bis 1 MB. Sie können das Formular auch ohne Datei senden.') expect((await post({ files: big, locale: 'nl' })).body.message).toBe('Het bestand "big.pdf" is te groot. Kies een bestand tot 1 MB. U kunt het formulier ook zonder bestand versturen.') // Every file message in Polish too; the field's label comes from the panel in the page language. const pl = async (files: Upload[]) => (await post({ files, locale: 'pl' })).body.message expect(await pl([{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }])).toBe('Za dużo plików w polu „Załącznik (opcjonalnie)”. Usuń część: limit to 1. Możesz też wysłać formularz bez pliku.') expect(await pl([{ name: 'zdjęcie.png', data: Buffer.alloc(32, 1) }])).toBe('Plik „zdjęcie.png” ma format, którego nie przyjmujemy. Wybierz jeden z: PDF, DOC, DOCX. Możesz też wysłać formularz bez pliku.') expect(await pl([{ name: 'cv.pdf', data: EXE }])).toBe( 'Plik „cv.pdf” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik (PDF, DOC, DOCX). Możesz też wysłać formularz bez pliku.', ) mailMode = 'refuse' expect(await pl([{ name: 'cv.pdf', data: PDF }])).toBe('Nie udało się wysłać pliku „cv.pdf”. Wybierz mniejszy plik lub inny format i spróbuj ponownie. Możesz też wysłać formularz bez pliku.') mailMode = 'ok' // A failure that is not about the file keeps its own message — no file wording. const consent = (await post({ files: [{ name: 'cv.pdf', data: PDF }], locale: 'en', values: { ...answers, consent: false } })).body expect(consent).toMatchObject({ field: 'consent', reason: 'consent' }) expect(consent.message).not.toMatch(/file/i) const missing = (await post({ files: [{ name: 'cv.pdf', data: PDF }], locale: 'en', values: { consent: true, email: 'jan@example.com' } })).body expect(missing).toMatchObject({ field: 'name', message: 'Check the field "Name".' }) }) test('the form the browser gets carries the limits that really apply, and where to post', async () => { const form = (await payload.findByID({ id: formId, collection: 'forms' as never, depth: 0, locale: 'en' })) as unknown as { fields: { blockType: string; help?: string; resolved?: Record }[] fileSubmitUrl?: string } const field = form.fields.find((f) => f.blockType === 'file')! expect(field.help).toBe('PDF, DOC or DOCX, up to 1 MB') expect(field.resolved).toMatchObject({ extensions: ['pdf', 'doc', 'docx'], maxFiles: 1, maxSizeMB: 1, typeLabels: 'PDF, DOC, DOCX' }) expect(String(field.resolved?.accept)).toContain('.pdf') expect(form.fileSubmitUrl).toBe('/api/ipal/forms/submit') }) test('the panel: the File block, its caps, and a form with a File field needs a fixed-recipient e-mail', async () => { const options = getFormAttachments(payload)! expect(options).toMatchObject({ maxFiles: 3, maxSizeMB: 1, maxTotalMB: 1 }) const block = (payload.collections['forms' as never].config.fields.find((f) => 'name' in f && f.name === 'fields') as { blocks: { fields: unknown[]; slug: string }[] }).blocks.find((b) => b.slug === 'file')! expect(JSON.stringify(block.fields)).toContain('Dozwolone typy plików') const fields = [{ name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV' }] const confirmationMessage = text('ok') const refusal = await payload .create({ collection: 'forms' as never, data: { confirmationMessage, emails: [{ emailTo: '{{email}}', message: text('x'), subject: 'x' }], fields, title: 'No staff e-mail' } as never }) .then(() => null, (err: { data?: { errors?: { message: string; path: string }[] } }) => err.data?.errors?.[0]) expect(refusal).toMatchObject({ path: 'emails' }) expect(refusal?.message).toMatch(/fixed recipient|stałym adresem/) await expect(payload.create({ collection: 'forms' as never, data: { confirmationMessage, fields, title: 'No e-mail at all' } as never })).rejects.toThrow() // A size over the cap is refused by the field itself. await expect( payload.create({ collection: 'forms' as never, data: { confirmationMessage, emails: [{ emailTo: 'a@acme.test', message: text('x'), subject: 'x' }], fields: [{ ...fields[0], maxSizeMB: 50 }], title: 'Too big' } as never }), ).rejects.toThrow() }) test('a required File field: the submission without a file is refused', async () => { const required = await payload.create({ collection: 'forms' as never, data: { confirmationMessage: text('ok'), emails: [{ emailFrom: 'site@acme.test', emailTo: 'jobs@acme.test', message: text('x'), subject: 'x' }], fields: [{ name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV', required: true }], title: 'Required file', } as never, locale: 'en', }) const before = await count() const none = await post({ form: String(required.id), values: {} }) expect(none.body).toMatchObject({ field: 'cv', reason: 'validation', success: false }) expect(await submitForm({ data: {}, formId: String(required.id), maxPerMinute: 0, payload })).toMatchObject({ field: 'cv', kind: 'required' }) expect(await count()).toBe(before) // A required field: the same messages, without "send the form without the file". const big = await post({ files: [{ name: 'cv.pdf', data: pad(Buffer.from('%PDF-1.7\n'), MB + 10), field: 'cv' }], form: String(required.id), values: {} }) expect(big.body).toMatchObject({ field: 'cv', message: 'The file "cv.pdf" is too large. Choose a file of up to 1 MB.' }) mailMode = 'refuse' const unsent = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} }) expect(unsent.body).toMatchObject({ field: 'cv', message: 'We could not send the file "cv.pdf". Choose a smaller file or another format and try again.' }) mailMode = 'ok' const ok = await post({ files: [{ name: 'cv.pdf', data: PDF, field: 'cv' }], form: String(required.id), values: {} }) expect(ok.body.success).toBe(true) }) test('submitForm({ files }) — a project\'s own transfer path gets the same checks and the same delivery', async () => { const good = await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: PDF }] }, formId, locale: 'en', maxPerMinute: 0, payload }) expect(good.success).toBe(true) expect(withFile()).toHaveLength(1) expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', data: EXE }] }, formId, maxPerMinute: 0, payload })).toMatchObject({ field: 'attachment', file: 'cv.pdf', kind: 'file_refused', optional: true, types: 'PDF, DOC, DOCX', }) expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.png', data: EXE }] }, formId, maxPerMinute: 0, payload })).toMatchObject({ kind: 'file_type' }) }) }) describe('options a project can set', () => { let other: Payload let otherForm: string const sent: Mail[] = [] let slowScan: null | Promise = null beforeAll(async () => { other = await getPayload({ config: buildTestConfig({ collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: mediaDir } }], db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), email: () => ({ name: 'test-mail-2', defaultFromAddress: 'site@acme.test', defaultFromName: 'Acme', sendEmail: (message) => { sent.push(message as unknown as Mail) return Promise.resolve({ messageId: 'ok' }) }, }), plugins: [ iapl({ access: { authCollection: 'users' }, forms: { attachments: { allowRisky: ['zip'], fileTypes: { zip: { extensions: ['zip'], label: 'ZIP', mimeType: 'application/zip' } }, maxConcurrent: 1, notice: false, path: '/custom/files', scan: async () => { await slowScan return { ok: true } }, submit: { allowedOrigins: ['https://app.example'], idleTimeoutMs: 300, maxPerMinute: 0, timeoutMs: 1500 }, }, }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false, }), ], secret: 'form-files-options-secret', telemetry: false, }), key: 'form-files-options', }) const form = await other.create({ collection: 'forms' as never, data: { confirmationMessage: text('ok'), emails: [{ emailFrom: 'site@acme.test', emailTo: 'office@acme.test', message: text('Files: {{files}}'), subject: 'Files' }], fields: [{ name: 'files', allowedTypes: ['zip', 'pdf'], blockType: 'file', label: 'Files', maxFiles: 2 }], title: 'Archive', } as never, }) otherForm = String(form.id) }, 60_000) afterAll(async () => { await other?.destroy() }) const send = (files: Upload[], headers: Record = { 'sec-fetch-site': 'same-origin' }) => { const body = new FormData() body.append('_form', otherForm) body.append('_values', '{}') for (const file of files) {body.append('files', new File([new Uint8Array(file.data)], file.name))} const request = new Request('http://localhost/api/custom/files', { body, headers, method: 'POST' }) return handleFormSubmit(Object.assign(request, { payload: other }) as unknown as PayloadRequest) } test('an allowed risky type, a custom path, no virus line, an extra allowed origin', async () => { expect((other.config.endpoints ?? []).some((e) => e.path === '/custom/files' && e.method === 'post')).toBe(true) const response = await send([{ name: 'drawings.zip', data: ARCHIVE }, { name: 'cv.pdf', data: PDF }], { origin: 'https://app.example', 'sec-fetch-site': 'cross-site' }) expect(response.status).toBe(200) expect(sent).toHaveLength(1) expect(sent[0].attachments?.map((a) => a.filename)).toEqual(['drawings.zip', 'cv.pdf']) expect(sent[0].html).toContain('drawings.zip (') expect(sent[0].html).not.toContain('viruses') // a program is still refused, and so is an origin that is not on the list expect((await send([{ name: 'setup.exe', data: EXE }])).status).toBe(422) expect((await send([{ name: 'cv.pdf', data: PDF }], { origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' })).status).toBe(403) }) test('the concurrency guard: a second file submission waits its turn with "try again"', async () => { let release = () => {} slowScan = new Promise((resolve) => (release = resolve)) const first = send([{ name: 'cv.pdf', data: PDF }]) await new Promise((resolve) => setTimeout(resolve, 50)) const second = await send([{ name: 'cv.pdf', data: PDF }]) expect(second.status).toBe(429) expect(((await second.json()) as { message: string }).message).toMatch(/Too many attempts/) release() slowScan = null expect((await first).status).toBe(200) expect((await send([{ name: 'cv.pdf', data: PDF }])).status).toBe(200) // the slot is free again }) // ---- uploads that break off, never end, or stall (security review of 1.16.0) ---------------------------- // The request body is built by hand, so the test decides what arrives and when — like a real connection. const BOUNDARY = 'ipalTestBoundary' const part = (name: string, value: string) => `--${BOUNDARY}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n` const prelude = (attempt?: string) => Buffer.from( `${part('_form', otherForm)}${attempt ? part('_attempt', attempt) : ''}${part('_values', '{}')}` + `--${BOUNDARY}\r\nContent-Disposition: form-data; name="files"; filename="cv.pdf"\r\nContent-Type: application/pdf\r\n\r\n`, ) const closing = Buffer.from(`\r\n--${BOUNDARY}--\r\n`) const raw = (body: ReadableStream) => { const request = new Request('http://localhost/api/custom/files', { body, duplex: 'half', headers: { 'content-type': `multipart/form-data; boundary=${BOUNDARY}`, 'sec-fetch-site': 'same-origin' }, method: 'POST', } as RequestInit) return handleFormSubmit(Object.assign(request, { payload: other }) as unknown as PayloadRequest) } const within = (promise: Promise, ms: number) => Promise.race([promise, new Promise<'HUNG'>((resolve) => setTimeout(() => resolve('HUNG'), ms))]) /** Nothing is held, and the endpoint still works: a normal upload goes through (also with the same attempt key). */ const backToNormal = async (attempt?: string) => { expect(formSubmitState()).toEqual({ active: 0, inflight: 0 }) const whole = new ReadableStream({ start(controller) { controller.enqueue(Buffer.concat([prelude(attempt), PDF, closing])) controller.close() }, }) const response = await within(raw(whole), 5000) expect(response).not.toBe('HUNG') expect((response as Response).status).toBe(200) expect(formSubmitState()).toEqual({ active: 0, inflight: 0 }) } test('the connection drops in the middle of a file: the request ends, nothing stays held, the retry works', async () => { const before = (await other.count({ collection: 'form-submissions' as never })).totalDocs const attempt = 'attempt-dropped-00000001' const dropped = new ReadableStream({ start(controller) { controller.enqueue(Buffer.concat([prelude(attempt), PDF.subarray(0, 2000)])) setTimeout(() => controller.error(new Error('ECONNRESET')), 50) }, }) const response = await within(raw(dropped), 3000) expect(response).not.toBe('HUNG') expect((response as Response).status).toBe(400) expect((await other.count({ collection: 'form-submissions' as never })).totalDocs).toBe(before) await backToNormal(attempt) // the browser's retry with the same attempt key is not left waiting }) // Re-review of 1.16.0: the abort can land while the gates before the first file byte are still waiting // (the form look-up, the attempt look-up, Turnstile). The work that resumes afterwards must not leave the // attempt key registered — or every retry with that key would wait on a promise nobody settles. test.each([ ['the form look-up (before the key is registered)', 'findByID'], ['the attempt look-up (after the key is registered)', 'find'], ] as const)('the connection drops while %s is still pending: the key is not left behind', async (_name, method) => { const attempt = `attempt-pending-${method.padEnd(8, '0')}` const original = other[method].bind(other) as (...args: unknown[]) => Promise const slow = vi.spyOn(other, method as 'find').mockImplementation((async (...args: unknown[]) => { await new Promise((resolve) => setTimeout(resolve, 300)) return original(...args) }) as never) const dropped = new ReadableStream({ start(controller) { controller.enqueue(Buffer.concat([prelude(attempt), PDF.subarray(0, 2000)])) setTimeout(() => controller.error(new Error('ECONNRESET')), 30) }, }) const response = await within(raw(dropped), 3000) expect(response).not.toBe('HUNG') expect((response as Response).status).toBe(400) expect(formSubmitState()).toEqual({ active: 0, inflight: 0 }) // …and it is still so once the pending look-ups have finished await new Promise((resolve) => setTimeout(resolve, 1000)) expect(slow).toHaveBeenCalled() slow.mockRestore() expect(formSubmitState()).toEqual({ active: 0, inflight: 0 }) // the browser's retry with the same key is answered at once const started = Date.now() await backToNormal(attempt) expect(Date.now() - started).toBeLessThan(1000) }) test('two dropped uploads do not use up the concurrency slots (maxConcurrent: 1 here)', async () => { for (let i = 0; i < 2; i++) { const dropped = new ReadableStream({ start(controller) { controller.enqueue(Buffer.concat([prelude(), PDF.subarray(0, 500)])) setTimeout(() => controller.error(new Error('ECONNRESET')), 20) }, }) expect(await within(raw(dropped), 3000)).not.toBe('HUNG') } await backToNormal() // 200, not "too many attempts" }) test('a chunked body with no declared length that never stops: cut off at the ceiling', async () => { let sent = 0 let cancelled = false const megabyte = Buffer.alloc(MB, 0x20) const endless = new ReadableStream({ cancel() { cancelled = true }, pull(controller) { controller.enqueue(sent === 0 ? Buffer.concat([prelude('attempt-endless-00000001'), Buffer.from('%PDF-1.7\n')]) : megabyte) sent++ }, }) const response = await within(raw(endless), 10_000) expect(response).not.toBe('HUNG') expect((response as Response).status).toBe(413) expect(cancelled).toBe(true) // the plugin stopped reading; it did not drain an endless body expect(sent).toBeLessThan(20) // about 10 MB + the envelope, not more await backToNormal('attempt-endless-00000001') }, 20_000) test('a stalled upload (no bytes, connection open) is given up after the idle timeout', async () => { const stalled = new ReadableStream({ start(controller) { controller.enqueue(Buffer.concat([prelude('attempt-stalled-00000001'), PDF.subarray(0, 1000)])) // …and then nothing: never closed, never errored }, }) const started = Date.now() const response = await within(raw(stalled), 5000) expect(response).not.toBe('HUNG') expect((response as Response).status).toBe(408) expect(Date.now() - started).toBeLessThan(2000) // idleTimeoutMs: 300 in this config expect(((await (response as Response).json()) as { message: string }).message).toBe('The form could not be sent. Please try again in a moment.') await backToNormal('attempt-stalled-00000001') }) test('a slow trickle that keeps sending is not cut off by the idle timeout', async () => { const body = Buffer.concat([prelude(), PDF, closing]) let offset = 0 const trickle = new ReadableStream({ async pull(controller) { await new Promise((resolve) => setTimeout(resolve, 60)) // well under the idle limit, over many chunks const next = body.subarray(offset, offset + Math.ceil(body.length / 10)) offset += next.length if (next.length) {controller.enqueue(next)} else {controller.close()} }, }) const response = await within(raw(trickle), 5000) expect((response as Response).status).toBe(200) expect(formSubmitState()).toEqual({ active: 0, inflight: 0 }) }) test('the request ceiling: checks that never finish do not hold the request or its slot', async () => { let release = () => {} slowScan = new Promise((resolve) => (release = resolve)) const started = Date.now() const response = await within(send([{ name: 'cv.pdf', data: PDF }]), 5000) expect(response).not.toBe('HUNG') expect((response as Response).status).toBe(408) expect(Date.now() - started).toBeGreaterThanOrEqual(1400) // timeoutMs: 1500 in this config expect(formSubmitState()).toEqual({ active: 0, inflight: 0 }) release() slowScan = null await new Promise((resolve) => setTimeout(resolve, 50)) await backToNormal() }) }) describe('files without the feature', () => { test('submitForm({ files }) on a form without a File field is refused and logged, never dropped silently', async () => { const plain = await payload.create({ collection: 'forms' as never, data: { confirmationMessage: text('ok'), fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'No file field' } as never, }) const warn = vi.spyOn(payload.logger, 'warn') const before = await count() const result = await submitForm({ data: { name: 'Jan' }, files: { cv: [{ name: 'cv.pdf', data: PDF }] }, formId: String(plain.id), maxPerMinute: 0, payload }) expect(result).toMatchObject({ kind: 'unknown_fields', reason: 'validation', success: false }) expect(warn).toHaveBeenCalledWith(expect.stringContaining('has no File field')) expect(await count()).toBe(before) warn.mockRestore() }) })