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:
Radosław Smoliński
2026-11-13 17:02:10 +01:00
co-authored by Claude Fable 5.2
parent cd74d7decb
commit e24c918d4b
13 changed files with 311 additions and 30 deletions
+10
View File
@@ -71,8 +71,18 @@ export type FormSubmitEndpointOptions = {
clientIp?: ClientIpOptions
/** Honeypot field name. Default HONEYPOT_FIELD. */
honeypotField?: string
/**
* A stalled upload: no byte of the request body for this long (ms) and the request is given up (408).
* Default 30000; 0 = no idle limit.
*/
idleTimeoutMs?: number
/** Max submissions per IP per minute. Default 5; 0 turns it off. */
maxPerMinute?: number
/**
* Ceiling for the whole request — upload, checks and e-mail (ms). Past it the request is answered 408 and
* everything it held is released. Default 300000 (5 minutes); 0 = no ceiling.
*/
timeoutMs?: number
turnstileHostnames?: string[]
turnstileOnConfigError?: 'allow' | 'reject'
}
+3 -1
View File
@@ -97,7 +97,9 @@ export function createFileGate({
if ('refused' in match) {return { failure: match.refused === 'type' ? { ...refusedFailure, kind: 'file_type' } : refusedFailure }}
const maxBytes = Math.max(0, Math.min(limits.maxBytes, limits.maxTotalBytes - total))
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(limits.maxBytes), optional })
// The limit the message names is what this file may really have: the per-file limit, or what is left of
// the submission's total when other files used part of it (the whole total when nothing is left).
const tooLarge = (): FormFileFailure => ({ field: fieldName, file, kind: 'file_too_large', max: limitInMB(maxBytes > 0 ? maxBytes : limits.maxTotalBytes), optional })
let checked = false
return {
slot: {
+85 -15
View File
@@ -41,6 +41,14 @@ let active = 0
/** Attempt keys being handled right now → their outcome, so a duplicate request waits instead of sending twice. */
const inflight = new Map<string, Promise<SubmitFormResult>>()
/** No byte of the body for this long → the upload is given up (a stalled or dropped connection). */
const IDLE_TIMEOUT_MS = 30_000
/** The whole request — upload, checks and e-mail — may take this long. */
const REQUEST_TIMEOUT_MS = 300_000
/** What the endpoint is holding right now — for monitoring and tests: both are 0 when nothing is in flight. */
export const formSubmitState = () => ({ active, inflight: inflight.size })
function originAllowed(req: PayloadRequest, allowed: readonly string[] = []): boolean {
const headers = req.headers
const origin = headers.get('origin')
@@ -75,6 +83,11 @@ function localeOf(payload: BasePayload, value: unknown): string | undefined {
* After a refusal nothing more is kept: the rest of the body is read and
* thrown away (so the browser gets the answer instead of a broken connection),
* and past the hard ceiling the connection is cut.
*
* A body that breaks off, stalls (`submit.idleTimeoutMs`) or runs past the
* request ceiling (`submit.timeoutMs`) is aborted: streams torn down, buffers
* dropped, the request answered. On EVERY way out the slot of the concurrency
* guard and the attempt key are released.
*/
export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
const { payload } = req
@@ -119,6 +132,8 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
let registered: string | undefined
let settle: ((result: SubmitFormResult) => void) | undefined
let final: SubmitFormResult = { reason: 'error', success: false }
/** HTTP status of an aborted request (413 over the ceiling, 408 timed out, 400 broken body). */
let abortStatus: number | undefined
try {
final = await new Promise<SubmitFormResult>((resolve) => {
const fields: Record<string, string> = {}
@@ -142,6 +157,44 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
outcome ??= result
}
/** File parts not read to their end yet — torn down when the request is aborted. */
const open = new Set<Readable>()
let settled = false
/** The parser reached the end of the body, or the request was aborted — no second ending. */
let done = false
/** The submission is being stored and e-mailed: its files must stay until that is over. */
let storing = false
let idleTimer: ReturnType<typeof setTimeout> | undefined
let requestTimer: ReturnType<typeof setTimeout> | undefined
/** The one way out: answers the request and stops the timers. Later calls do nothing. */
const conclude = (result: SubmitFormResult) => {
if (settled) {return}
settled = true
clearTimeout(idleTimer)
clearTimeout(requestTimer)
resolve(result)
}
/**
* Gives the request up NOW — a body that broke off (the visitor's connection dropped), stalled, or went
* over the ceiling. Waiting for the parser would wait forever: a file part of a broken body never ends.
* So everything is torn down here — the file streams (their read loops throw and let go of what they
* hold), the parser, the body — the buffers are dropped, and the request is answered. The slot of the
* concurrency guard and the attempt key are released by the `finally` below, as on every other way out.
*/
const abort = (status: number) => {
if (settled) {return}
done = true
stop({ reason: 'error', success: false })
abortStatus = status
source.unpipe(parser)
for (const stream of open) {stream.destroy(new Error('upload aborted'))}
open.clear()
parser.destroy()
source.destroy()
if (gate && !storing) {gate.accepted.length = 0}
conclude(outcome ?? { reason: 'error', success: false })
}
/** 5–8: everything that must hold before the first file byte is accepted. */
const beforeFiles = async () => {
locale = localeOf(payload, fields._locale) ?? locale
@@ -201,6 +254,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
let chunks: Buffer[] = []
let size = 0
let headChecked = false
// An aborted request destroys this stream: the loop throws and `chunks` goes with it.
for await (const chunk of stream as AsyncIterable<Buffer>) {
if (outcome) {continue} // refused: read on and keep nothing
size += chunk.length
@@ -221,6 +275,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
}
}
}
open.delete(stream)
if (outcome) {return}
if (stream.truncated) {return refuse(slot.tooLarge())}
// 13–14. Whole-file checks and the optional scan.
@@ -233,7 +288,11 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
fields[name] = value
})
parser.on('file', (name, stream, info) => {
open.add(stream)
stream.on('error', () => undefined) // a torn-down part must not become an unhandled stream error
chain = chain.then(() => receiveFile(name, stream, info.filename ?? '')).catch((err) => {
open.delete(stream)
if (settled) {return} // aborted: already answered, nothing to add
stream.resume()
payload.logger.error(`[ipal] Form file could not be read: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
@@ -255,34 +314,45 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
if (missing) {stop(await fileFailure(payload, (stored as { formId: string }).formId, missing, locale))}
}
// 15. Store the answers and the file metadata, e-mail the files, drop the buffers.
if (!outcome && gate && stored) {stop(await storeSubmission({ ...(stored), files: (gate).accepted }))}
if (!outcome && !settled && gate && stored) {
storing = true
stop(await storeSubmission({ ...(stored), files: (gate).accepted }))
}
} catch (err) {
payload.logger.error(`[ipal] Form submit failed: ${(err as Error).message}`)
stop({ reason: 'error', success: false })
}
resolve(outcome ?? { reason: 'error', success: false })
conclude(outcome ?? { reason: 'error', success: false })
}
let done = false
const once = (run: () => void) => () => {
parser.on('close', () => {
if (done) {return}
done = true
run()
}
parser.on('close', once(() => void finish()))
const broken = once(() => {
stop({ reason: 'error', success: false })
void finish()
})
// A body that breaks off mid-upload (or a parser error) never reaches 'close' on its own: abort.
const broken = () => {
if (!done) {abort(400)}
}
parser.on('error', broken)
source.on('error', broken)
// Hard ceiling on what is read at all, whatever Content-Length said.
// A stalled upload: no byte for too long while the body is still coming. And a ceiling on the whole request.
const idleMs = submit.idleTimeoutMs ?? IDLE_TIMEOUT_MS
const requestMs = submit.timeoutMs ?? REQUEST_TIMEOUT_MS
const watchIdle = () => {
clearTimeout(idleTimer)
if (idleMs > 0 && !settled && !done) {idleTimer = setTimeout(() => !done && abort(408), idleMs)}
}
watchIdle()
if (requestMs > 0) {requestTimer = setTimeout(() => abort(408), requestMs)}
source.on('end', () => clearTimeout(idleTimer)) // the body is in; from here only the request ceiling applies
source.on('data', (chunk: Buffer) => {
watchIdle()
// Hard ceiling on what is read at all, whatever Content-Length said (or did not say: a chunked body).
received += chunk.length
if (received > hardCap) {
stop({ reason: 'error', success: false })
source.destroy(new Error('request body over the limit'))
}
if (received > hardCap) {abort(413)}
})
source.pipe(parser)
})
@@ -291,5 +361,5 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
if (registered) {inflight.delete(registered)}
settle?.(final)
}
return respond(final)
return respond(final, abortStatus)
}
+10 -2
View File
@@ -366,9 +366,17 @@ export async function submitForm(args: SubmitFormArgs): Promise<SubmitFormResult
const hasFiles = Object.values(files ?? {}).some((list) => list.length > 0)
const attachments = getFormAttachments(payload)
if (!attachments || (!hasFiles && validation.fileFields.length === 0)) {
if (!attachments || validation.fileFields.length === 0) {
// A file without the feature (or without a File field) is an unknown field.
if (hasFiles) {return { kind: 'unknown_fields', reason: 'validation', success: false }}
if (hasFiles) {
// Never dropped silently: the caller sent files this site (or this form) does not take.
payload.logger.warn(
attachments
? `[ipal] submitForm: files were sent to form ${formId}, which has no File field — refused.`
: '[ipal] submitForm: files were sent, but forms.attachments is off — refused. Turn it on in ipalKit({ forms: { attachments: true } }).',
)
return { kind: 'unknown_fields', reason: 'validation', success: false }
}
return storeSubmission({ attemptKey, formId, locale, payload, validation })
}