Form attachments: tests for project options and the concurrency guard

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:44:41 +01:00
co-authored by Claude Fable 5.2
parent ea43d94dd2
commit b6f9f34705
+100
View File
@@ -643,3 +643,103 @@ describe('7 · languages, the panel, limits', () => {
expect(await submitForm({ data: answers, files: { attachment: [{ name: 'cv.pdf', 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<void> = 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: '[email protected]',
defaultFromName: 'Acme',
sendEmail: (message) => {
sent.push(message as unknown as Mail)
return Promise.resolve({ messageId: 'ok' })
},
}),
plugins: [
ipalKit({
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'], maxPerMinute: 0 },
},
},
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: '[email protected]', emailTo: '[email protected]', 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<string, string> = { '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<void>((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
})
})