Files
ipal-kit/test/formFileField.test.ts
Radosław SmolińskiandClaude Fable 5.2 e24c918d4b Form files: a dropped, stalled or endless upload is aborted and frees its slot, attempt key and buffers
Security review of 1.16.0 (blocking): a request body that errored mid-file never
resolved, leaking the concurrency slot and the attempt key. Also: idle and request
timeouts (submit.idleTimeoutMs / timeoutMs), ImmutableId preference on every Graph
draft call, the remaining total in the too-large message, files sent to a form
without a File field are refused and logged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:02:10 +01:00

302 lines
20 KiB
TypeScript

import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderTypes.js'
import { fileFieldLimits, resolveFormAttachments } from '../src/modules/forms/attachments/config.js'
import { canCarryFiles, emailAddresses, fixedRecipients, mayCarryFiles } from '../src/modules/forms/attachments/delivery.js'
import { buildFileBlock } from '../src/modules/forms/attachments/fileBlock.js'
import { checkFileContent, matchFileType, oleHasMacros, pdfHasActiveContent, zipEntries } from '../src/modules/forms/attachments/fileChecks.js'
import { createFileGate, limitInMB } from '../src/modules/forms/attachments/fileGate.js'
import { describeFileTypes, FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS, safeFileName } from '../src/modules/forms/attachments/fileTypes.js'
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { fileFieldError, fileFieldRules, initialBuilderValues, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
import { splitFormFiles } from '../src/modules/forms/createSubmitAction.js'
import { publicForm } from '../src/modules/forms/RenderForm.js'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL } from '../src/modules/notifications/defaults.js'
import { resolveFormMessage } from '../src/modules/notifications/resolveFormMessage.js'
import { fakePayload } from './helpers.js'
vi.mock('server-only', () => ({}))
const MB = 1024 * 1024
const options = resolveFormAttachments(true)
const risky = options.risky
describe('file names', () => {
test('the attachment name is rebuilt: no path, no control or bidi characters, the detected extension', () => {
expect(safeFileName('C:\\Users\\jan\\CV Jan Kowalski.PDF', 'pdf')).toBe('CV Jan Kowalski.pdf')
expect(safeFileName('../../etc/passwd', 'pdf')).toBe('passwd.pdf')
expect(safeFileName('cv\u202Efdp.exe', 'pdf')).toBe('cvfdp.pdf')
expect(safeFileName('Życiorys (2026) — wersja #2.docx', 'docx')).toBe('Życiorys (2026) wersja 2.docx')
expect(safeFileName('<script>.pdf', 'pdf')).toBe('script.pdf')
expect(safeFileName('....', 'pdf')).toBe('attachment.pdf')
expect(safeFileName(`${'a'.repeat(300)}.pdf`, 'pdf')).toHaveLength(84)
})
test('the extension decides the type; risky and doubled extensions are refused', () => {
const allowed = ['pdf', 'doc', 'docx']
const match = (name: string, list = allowed, set: ReadonlySet<string> = risky) => {
const result = matchFileType(name, list, options.types, set)
return 'key' in result ? result.key : 'refused'
}
expect(match('cv.pdf')).toBe('pdf')
expect(match('CV.DOCX')).toBe('docx')
expect(match('my.cv.final.pdf')).toBe('pdf') // dots in a name are fine
for (const name of ['cv', 'cv.txt', 'cv.pdf.exe', 'cv.exe.pdf', 'cv.pdf.docx', 'cv.docm', 'cv.zip', 'cv.svg', 'cv.html', 'cv.js.pdf']) {
expect(match(name), name).toBe('refused')
}
expect(match('photo.png')).toBe('refused') // a known type the field does not allow
expect(match('photo.jpeg', ['jpg'])).toBe('jpg')
})
test('a project can allow a refused extension and add its own type', async () => {
const own = resolveFormAttachments({
allowRisky: ['zip'],
fileTypes: { dwg: { detect: (bytes) => bytes[0] === 0x41 && bytes[1] === 0x43, extensions: ['.DWG'], label: 'DWG', mimeType: 'image/vnd.dwg' }, rtf: false, zip: { extensions: ['zip'], label: 'ZIP', mimeType: 'application/zip' } },
})
expect(own.risky.has('zip')).toBe(false)
expect(own.risky.has('exe')).toBe(true)
expect(Object.keys(own.types)).toContain('dwg')
expect(own.types.rtf).toBeUndefined()
expect(matchFileType('plan.dwg', ['dwg'], own.types, own.risky)).toMatchObject({ key: 'dwg' })
expect(matchFileType('files.zip', ['zip'], own.types, own.risky)).toMatchObject({ key: 'zip' })
expect(await checkFileContent('dwg', own.types.dwg, Buffer.from('AC1027....'))).toBeNull()
expect(await checkFileContent('dwg', own.types.dwg, Buffer.from('not a drawing'))).toBe('signature')
// The panel offers exactly the project's types.
expect(JSON.stringify(buildFileBlock(own).fields)).toContain('"value":"dwg"')
})
test('the risky list covers programs, macro files, archives and renderable markup', () => {
for (const extension of ['exe', 'bat', 'js', 'docm', 'xlsm', 'zip', 'rar', 'html', 'svg', 'iso']) {expect(RISKY_FILE_EXTENSIONS, extension).toContain(extension)}
expect(Object.keys(FORM_FILE_TYPES).filter((key) => FORM_FILE_TYPES[key].extensions.some((e) => RISKY_FILE_EXTENSIONS.includes(e)))).toEqual([])
})
})
describe('content checks', () => {
const ole = Buffer.concat([Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]), Buffer.alloc(600)])
test.each([
['pdf', Buffer.from('%PDF-1.4 ....')],
['jpg', Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0])],
['png', Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0])],
['webp', Buffer.from('RIFF\0\0\0\0WEBPVP8 ')],
['rtf', Buffer.from('{\\rtf1\\ansi}')],
['doc', ole],
['xls', ole],
])('%s: the right bytes pass, any other bytes do not', async (key, good) => {
expect(await checkFileContent(key, FORM_FILE_TYPES[key], good)).toBeNull()
expect(await checkFileContent(key, FORM_FILE_TYPES[key], Buffer.from('plain text, not this type'))).toBe('signature')
expect(await checkFileContent(key, FORM_FILE_TYPES[key], Buffer.alloc(0))).toBe('signature')
})
test('programs are refused whatever they claim to be', async () => {
for (const head of [Buffer.from('MZ\x90\0'), Buffer.from([0x7f, 0x45, 0x4c, 0x46]), Buffer.from('#!/bin/sh\n')]) {
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, Buffer.concat([head, Buffer.alloc(64)]))).toBe('signature')
}
})
test('a ZIP without a readable directory is not a document', async () => {
const truncated = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.alloc(200)])
expect(zipEntries(truncated)).toBeNull()
expect(await checkFileContent('docx', FORM_FILE_TYPES.docx, truncated)).toBe('signature')
})
test('legacy Office: a macro storage is found by its UTF-16 name (best-effort)', () => {
expect(oleHasMacros(ole)).toBe(false)
expect(oleHasMacros(Buffer.concat([ole, Buffer.from('_VBA_PROJECT_CUR', 'utf16le')]))).toBe(true)
})
test('strictPdf (optional): active content is refused only when switched on', async () => {
const pdf = Buffer.from('%PDF-1.7\n1 0 obj << /OpenAction 2 0 R /JS (app.alert(1)) >> endobj')
expect(pdfHasActiveContent(pdf)).toBe(true)
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, pdf)).toBeNull()
expect(await checkFileContent('pdf', FORM_FILE_TYPES.pdf, pdf, { strictPdf: true })).toBe('content')
})
})
describe('limits', () => {
test('the editor\'s values are capped by the option and by the e-mail transport', () => {
const field = { allowedTypes: ['pdf', 'nope'], maxFiles: 9, maxSizeMB: 50 }
expect(fileFieldLimits(field, options)).toEqual({ allowedTypes: ['pdf'], maxBytes: 10 * MB, maxFiles: 3, maxTotalBytes: 10 * MB })
expect(fileFieldLimits(field, options, 2_999_999)).toMatchObject({ maxBytes: 2_999_999, maxTotalBytes: 2_999_999 })
expect(fileFieldLimits({}, resolveFormAttachments({ maxSizeMB: 5, maxTotalMB: 12 }))).toMatchObject({ maxBytes: 5 * MB, maxFiles: 1, maxTotalBytes: 12 * MB })
expect(limitInMB(10 * MB)).toBe(10)
expect(limitInMB(2_999_999)).toBe(2.8) // rounded down — never promise more than can be sent
})
test('when earlier files used part of the submission total, the message names what is left', async () => {
const pdf = (size: number) => Buffer.concat([Buffer.from('%PDF-1.7\n'), Buffer.alloc(size - 9, 0x20)])
const gate = createFileGate({ fields: [{ name: 'files', allowedTypes: ['pdf'], maxFiles: 3, maxSizeMB: 10 }], options })
const first = gate.begin('files', 'a.pdf')
if ('failure' in first) {throw new Error('unexpected')}
expect(await gate.finish(first.token, pdf(6 * MB))).toBeNull()
const second = gate.begin('files', 'b.pdf')
if ('failure' in second) {throw new Error('unexpected')}
expect(second.slot.maxBytes).toBe(4 * MB)
expect(second.slot.tooLarge()).toMatchObject({ file: 'b.pdf', kind: 'file_too_large', max: 4 }) // not the per-file 10
expect(await gate.finish(second.token, pdf(4 * MB))).toBeNull()
const third = gate.begin('files', 'c.pdf')
if ('failure' in third) {throw new Error('unexpected')}
expect(third.slot.tooLarge()).toMatchObject({ max: 10 }) // nothing left: the submission's total
})
test('sizes read naturally', () => {
expect([formatFileSize(512), formatFileSize(64_000), formatFileSize(2.14 * MB), formatFileSize(10 * MB)]).toEqual(['512 B', '63 KB', '2.1 MB', '10 MB'])
})
})
describe('which e-mail may carry a file', () => {
const form = {
emails: [
{ bcc: '[email protected]', emailTo: 'HR <[email protected]>, [email protected]' },
{ emailTo: '{{email}}' },
{ cc: '{{email}}', emailTo: '[email protected]' },
{ emailTo: '' },
],
}
test('only e-mails whose recipients are all fixed addresses from the panel', () => {
expect(emailAddresses('HR <[email protected]>; [email protected]')).toEqual(['[email protected]', '[email protected]'])
expect(canCarryFiles(form)).toBe(true)
expect(canCarryFiles({ emails: [{ emailTo: '{{email}}' }] })).toBe(false)
expect(canCarryFiles({ emails: [] })).toBe(false)
const fixed = fixedRecipients(form, '[email protected]')
expect([...fixed].sort()).toEqual(['[email protected]', '[email protected]', '[email protected]', '[email protected]'])
expect(mayCarryFiles({ bcc: '[email protected]', cc: '', to: 'HR <[email protected]>, [email protected]' }, fixed)).toBe(true)
expect(mayCarryFiles({ bcc: '', cc: '', to: '[email protected]' }, fixed)).toBe(false) // the confirmation
expect(mayCarryFiles({ bcc: '', cc: '[email protected]', to: '[email protected]' }, fixed)).toBe(false) // a mixed one
expect(mayCarryFiles({ bcc: '', cc: '', to: '' }, fixed)).toBe(false)
})
})
describe('the form in the browser', () => {
const field: BuilderField = {
name: 'attachment',
allowedTypes: ['pdf', 'docx'],
blockType: 'file',
help: 'PDF or DOCX, up to 2 MB',
label: 'Attachment (optional)',
maxFiles: 2,
maxSizeMB: 2,
resolved: { ...describeFileTypes(['pdf', 'docx']), maxFiles: 2, maxSizeMB: 2, maxTotalMB: 3, typeLabels: 'PDF, DOCX' },
}
const texts = { ...NOTIFICATION_FALLBACK.form }
const form: BuilderFormDoc = { id: 9, fields: [{ name: 'name', blockType: 'text', label: 'Name' }, field], fileSubmitUrl: '/api/ipal/forms/submit' }
test('rules come from what the server resolved, else from the field', () => {
expect(fileFieldRules(field)).toMatchObject({ extensions: ['pdf', 'docx'], maxFiles: 2, maxSizeMB: 2, maxTotalMB: 3 })
expect(fileFieldRules({ name: 'a', allowedTypes: ['pdf'], blockType: 'file' })).toMatchObject({ accept: '.pdf,application/pdf', maxFiles: 1, maxSizeMB: 10, typeLabels: 'PDF' })
})
test('instant checks use the same messages as the server', () => {
const pdf = (name: string, size: number) => ({ name, size })
const hint = ' You can also send the form without the file.'
expect(fileFieldError(field, [pdf('cv.pdf', MB)], texts)).toBeUndefined()
expect(fileFieldError(field, [pdf('cv.pdf', 3 * MB)], texts)).toBe(`The file "cv.pdf" is too large. Choose a file of up to 2 MB.${hint}`)
expect(fileFieldError(field, [pdf('cv.png', 10)], texts)).toBe(`The file "cv.png" is in a format we do not accept. Choose one of: PDF, DOCX.${hint}`)
expect(fileFieldError(field, [pdf('a.pdf', 1), pdf('b.pdf', 1), pdf('c.pdf', 1)], texts)).toBe(`Too many files in "Attachment (optional)". Remove some: the limit is 2.${hint}`)
expect(fileFieldError(field, [pdf('a.pdf', 1.6 * MB), pdf('b.pdf', 1.6 * MB)], texts)).toBe(`The file "b.pdf" is too large. Choose a file of up to 3 MB.${hint}`)
expect(fileFieldError(field, [pdf('cv.pdf', 3 * MB)], NOTIFICATION_FALLBACK_PL.form)).toBe('Plik „cv.pdf” jest za duży. Wybierz plik do 2 MB. Możesz też wysłać formularz bez pliku.')
// A required field: no "send without the file".
expect(fileFieldError({ ...field, required: true }, [pdf('cv.pdf', 3 * MB)], texts)).toBe('The file "cv.pdf" is too large. Choose a file of up to 2 MB.')
// Older text objects without the file keys still give a message.
expect(fileFieldError(field, [pdf('cv.png', 10)], { validation: 'Check the field "{field}".' })).toBe('Check the field "Attachment (optional)".')
})
test('values and validation: a File field starts empty; required and limits are enforced', () => {
expect(initialBuilderValues(form.fields)).toEqual({ name: '', attachment: [] })
expect(validateBuilderFields([field], { attachment: [] }, texts)).toEqual({})
expect(validateBuilderFields([{ ...field, required: true }], { attachment: [] }, texts)).toEqual({ attachment: 'Check the field "Attachment (optional)".' })
expect(validateBuilderFields([field], { attachment: [{ name: 'x.exe', size: 5 }] }, texts).attachment).toContain('is in a format we do not accept')
})
test('markup: a native file input with a label, help text tied to it, accept and multiple', () => {
const html = renderToStaticMarkup(createElement(BuilderForm, { action: async () => ({ success: true }), form, locale: 'en', texts }))
expect(html).toMatch(/<label for="ipal-f-9-attachment">Attachment \(optional\)<\/label><input[^>]*id="ipal-f-9-attachment"/)
const input = /<input[^>]*id="ipal-f-9-attachment"[^>]*>/.exec(html)?.[0] ?? ''
expect(input).toContain('type="file"')
expect(input).toContain('multiple=""')
expect(input).toContain('accept=".pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document"')
expect(input).toContain('aria-describedby="ipal-f-9-attachment-help"')
expect(html).toContain('<p id="ipal-f-9-attachment-help">PDF or DOCX, up to 2 MB</p>')
expect(html).toContain('<ul aria-live="polite" data-ipal="form-files"></ul>')
expect(html).toContain('data-type="file"')
expect(html).not.toMatch(/class="/)
const styled = renderToStaticMarkup(
createElement(BuilderForm, { action: async () => ({ success: true }), classNames: { file: 'f', fileList: 'l', help: 'h' }, form, texts }),
)
expect(styled).toContain('class="f"')
expect(styled).toContain('class="l"')
expect(styled).toContain('class="h"')
})
test('only the public part of the form reaches the browser, with the limits and the submit address', () => {
const doc = { ...form, emails: [{ emailTo: '[email protected]' }] } as BuilderFormDoc
const pub = publicForm(doc)
expect(JSON.stringify(pub)).not.toContain('[email protected]')
expect(pub.fileSubmitUrl).toBe('/api/ipal/forms/submit')
expect(pub.fields?.[1].resolved).toMatchObject({ maxSizeMB: 2 })
})
})
describe('messages and helpers', () => {
const texts = NOTIFICATION_FALLBACK.form
test('every file outcome has its own text; the placeholders are filled', () => {
const fail = (extra: Record<string, unknown>, t = texts) => resolveFormMessage({ field: 'cv', label: 'CV', reason: 'validation', success: false, ...extra } as never, t)
// English: which file, why, what to do
expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 })).toBe('The file "a.pdf" is too large. Choose a file of up to 10 MB.')
expect(fail({ file: 'a.txt', kind: 'file_type', types: 'PDF, DOCX' })).toBe('The file "a.txt" is in a format we do not accept. Choose one of: PDF, DOCX.')
expect(fail({ file: 'a.exe', kind: 'file_refused', types: 'PDF, DOCX' })).toBe(
'The file "a.exe" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (PDF, DOCX).',
)
expect(fail({ kind: 'file_count', max: 2 })).toBe('Too many files in "CV". Remove some: the limit is 2.')
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', reason: 'delivery', success: false }, texts)).toBe(
'We could not send the file "a.pdf". Choose a smaller file or another format and try again.',
)
// an optional field: every file message adds that the form can go without the file
for (const extra of [{ file: 'a.pdf', kind: 'file_too_large', max: 10 }, { file: 'a.txt', kind: 'file_type', types: 'PDF' }, { file: 'a.exe', kind: 'file_refused', types: 'PDF' }, { kind: 'file_count', max: 2 }]) {
expect(fail({ ...extra, optional: true })).toMatch(/ You can also send the form without the file\.$/)
}
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', optional: true, reason: 'delivery', success: false }, texts)).toMatch(/try again\. You can also send the form without the file\.$/)
// Polish
const pl = NOTIFICATION_FALLBACK_PL.form
expect(fail({ file: 'a.pdf', kind: 'file_too_large', max: 10 }, pl)).toBe('Plik „a.pdf” jest za duży. Wybierz plik do 10 MB.')
expect(fail({ file: 'a.txt', kind: 'file_type', types: 'PDF, DOCX' }, pl)).toBe('Plik „a.txt” ma format, którego nie przyjmujemy. Wybierz jeden z: PDF, DOCX.')
expect(fail({ file: 'a.exe', kind: 'file_refused', types: 'PDF, DOCX' }, pl)).toBe(
'Plik „a.exe” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik (PDF, DOCX).',
)
expect(fail({ kind: 'file_count', max: 2, optional: true }, pl)).toBe('Za dużo plików w polu „CV”. Usuń część: limit to 2. Możesz też wysłać formularz bez pliku.')
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', reason: 'delivery', success: false }, pl)).toBe('Nie udało się wysłać pliku „a.pdf”. Wybierz mniejszy plik lub inny format i spróbuj ponownie.')
// Failures that are not about a file keep their own texts
expect(fail({ kind: 'required' })).toBe('Check the field "CV".')
expect(fail({ kind: 'invalid_format', optional: true })).toBe('Check the field "CV".')
expect(resolveFormMessage({ reason: 'error', success: false }, texts)).toBe(texts.error)
expect(resolveFormMessage({ reason: 'rate_limited', success: false }, texts)).toBe(texts.rateLimited)
// Texts written before the file keys existed fall back to the general ones.
const { fileCount: _a, fileNotSent: _b, fileOptional: _f, fileRefused: _g, fileRemove: _c, fileTooLarge: _d, fileType: _e, ...old } = texts
expect(resolveFormMessage({ reason: 'delivery', success: false }, old)).toBe(texts.error)
expect(resolveFormMessage({ field: 'cv', file: 'a.pdf', kind: 'file_too_large', max: 1, reason: 'validation', success: false }, old)).toBe('Check the field "cv".')
})
test('splitFormFiles separates File values from the answers', async () => {
const file = new File([new Uint8Array([1, 2, 3])], 'cv.pdf')
const { fields, files } = await splitFormFiles({ name: 'Jan', attachment: [file], single: file, tags: ['a', 'b'] })
expect(fields).toEqual({ name: 'Jan', tags: ['a', 'b'] })
expect(files?.attachment).toEqual([{ name: 'cv.pdf', data: new Uint8Array([1, 2, 3]) }])
expect(files?.single).toHaveLength(1)
expect(await splitFormFiles({ name: 'Jan', empty: [] })).toEqual({ fields: { name: 'Jan', empty: [] } })
})
test('submitForm({ files }) without forms.attachments: refused and logged, the submission is not stored', async () => {
const { create, payload } = fakePayload({ forms: { f: { fields: [{ name: 'name', blockType: 'text' }] } } })
const result = await submitForm({ data: { name: 'Jan' }, files: { cv: [{ name: 'cv.pdf', data: new Uint8Array([37, 80, 68, 70]) }] }, formId: 'f', maxPerMinute: 0, payload })
expect(result).toMatchObject({ kind: 'unknown_fields', reason: 'validation', success: false })
expect(payload.logger.warn).toHaveBeenCalledWith(expect.stringContaining('forms.attachments is off'))
expect(create).not.toHaveBeenCalled()
})
})