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]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
cd74d7decb
commit
e24c918d4b
@@ -216,7 +216,10 @@ describe('attachments', () => {
|
||||
])
|
||||
// The draft is addressed and labelled like any message, and asks for an id that survives the move to Sent Items.
|
||||
expect(graph.calls[0].body).toMatchObject({ subject: 'Application', toRecipients: [{ emailAddress: { address: '[email protected]' } }] })
|
||||
expect(graph.calls[0].headers.Prefer).toBe('IdType="ImmutableId"')
|
||||
// every call on the draft carries the immutable-id preference (the pre-authenticated upload URL takes no headers of ours)
|
||||
const onGraph = graph.calls.filter((c) => c.url.startsWith('https://graph.microsoft.com/'))
|
||||
expect(onGraph.length).toBeGreaterThanOrEqual(6)
|
||||
expect(onGraph.every((c) => c.headers.Prefer === 'IdType="ImmutableId"')).toBe(true)
|
||||
expect((graph.calls[1].body as { AttachmentItem: unknown }).AttachmentItem).toMatchObject({ name: 'cv.pdf', attachmentType: 'file', size: 10 * MB })
|
||||
// Every byte, in order, in pieces under 4 MB, without the bearer token on the pre-authenticated URL.
|
||||
expect(Buffer.compare(Buffer.concat(graph.uploaded), bytes(10 * MB))).toBe(0)
|
||||
|
||||
@@ -20,7 +20,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vite
|
||||
import type { FormFileScanInput } from '../src/modules/forms/attachments/config.js'
|
||||
|
||||
import { getFormAttachments } from '../src/modules/forms/attachments/config.js'
|
||||
import { handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js'
|
||||
import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
@@ -738,7 +738,7 @@ describe('options a project can set', () => {
|
||||
await slowScan
|
||||
return { ok: true }
|
||||
},
|
||||
submit: { allowedOrigins: ['https://app.example'], maxPerMinute: 0 },
|
||||
submit: { allowedOrigins: ['https://app.example'], idleTimeoutMs: 300, maxPerMinute: 0, timeoutMs: 1500 },
|
||||
},
|
||||
},
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
@@ -801,4 +801,154 @@ describe('options a project can set', () => {
|
||||
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<Uint8Array>) => {
|
||||
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 = <T>(promise: Promise<T>, 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<Uint8Array>({
|
||||
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<Uint8Array>({
|
||||
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
|
||||
})
|
||||
|
||||
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<Uint8Array>({
|
||||
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<Uint8Array>({
|
||||
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<Uint8Array>({
|
||||
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<Uint8Array>({
|
||||
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<void>((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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,14 +8,16 @@ import { fileFieldLimits, resolveFormAttachments } from '../src/modules/forms/at
|
||||
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 { limitInMB } from '../src/modules/forms/attachments/fileGate.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', () => ({}))
|
||||
|
||||
@@ -125,6 +127,22 @@ describe('limits', () => {
|
||||
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'])
|
||||
})
|
||||
@@ -272,4 +290,12 @@ describe('messages and helpers', () => {
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user