Files
ipal-kit/src/modules/forms/attachments/submitHandler.ts
T
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

366 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'server-only'
import type { BasePayload, PayloadRequest } from 'payload'
import busboy from 'busboy'
import { Readable } from 'node:stream'
import type { FormNotificationTexts } from '../../notifications/types.js'
import type { SubmitActionResult } from '../createSubmitAction.js'
import type { SubmitFormResult } from '../submitForm.js'
import type { FileGate } from './fileGate.js'
import { mailAttachmentLimit } from '../../email/attachmentLimit.js'
import { getNotificationTexts } from '../../notifications/getNotificationTexts.js'
import { resolveFormMessage } from '../../notifications/resolveFormMessage.js'
import { clientIp } from '../../shared/rateLimit.js'
import { HONEYPOT_FIELD, isHoneypotTripped } from '../honeypot.js'
import {
cleanAttemptKey,
fileFailure,
findSubmitAttempt,
passRateLimit,
passTurnstile,
storeSubmission,
validateSubmitFields,
} from '../submitForm.js'
import { getFormAttachments } from './config.js'
import { canCarryFiles } from './delivery.js'
import { createFileGate } from './fileGate.js'
import { MB } from './fileTypes.js'
/** Room for the text parts and the multipart envelope, on top of the files. */
const ENVELOPE_BYTES = 256 * 1024
/** The answers as JSON: every field is capped at 5000 characters by validation; this is the outer ceiling. */
const VALUES_BYTES = 128 * 1024
const STATUS: Record<string, number> = { consent: 422, delivery: 502, error: 500, not_found: 404, rate_limited: 429, turnstile: 403, validation: 422 }
/** File submissions in flight in this process — the concurrency guard. */
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')
if (origin && allowed.some((a) => a.replace(/\/$/, '') === origin)) {return true}
const site = headers.get('sec-fetch-site')
if (site) {return site === 'same-origin'}
if (!origin) {return true} // not a browser — the gates below still apply
try {
const host = new URL(origin).host
return host === (headers.get('x-forwarded-host') ?? headers.get('host'))
} catch {
return false
}
}
function localeOf(payload: BasePayload, value: unknown): string | undefined {
if (typeof value !== 'string' || !value) {return undefined}
const localization = payload.config.localization
if (!localization) {return undefined}
return localization.localeCodes.includes(value) ? value : undefined
}
/**
* The submit endpoint for forms with files. The request body is read as a
* stream, and every step runs before the next starts:
*
* origin → rate limit → declared size → concurrency guard → the answers
* (honeypot, Turnstile, validation, consent) → is there an e-mail to carry a
* file → per file: field, count, name → size while reading, signature on the
* first bytes → whole-file checks, scan → e-mail → the buffers are dropped.
*
* 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
const options = getFormAttachments(payload)
if (!options) {return Response.json({ success: false }, { status: 404 })}
const submit = options.submit
let locale = localeOf(payload, new URL(req.url ?? 'http://localhost').searchParams.get('locale'))
let texts: FormNotificationTexts | undefined
const respond = async (result: SubmitFormResult, status?: number): Promise<Response> => {
texts ??= (await getNotificationTexts({ locale, payload })).form
const body: SubmitActionResult = result.success
? { message: resolveFormMessage(result, texts), success: true }
: {
message: resolveFormMessage(result, texts),
reason: result.reason,
success: false,
...('field' in result && result.field ? { field: result.field } : {}),
}
return Response.json(body, { headers: { 'Cache-Control': 'no-store' }, status: status ?? (result.success ? 200 : (STATUS[result.reason] ?? 400)) })
}
// 1. Same origin, the right kind of request.
if (!originAllowed(req, submit.allowedOrigins)) {return respond({ reason: 'error', success: false }, 403)}
const contentType = req.headers.get('content-type') ?? ''
if (!/^multipart\/form-data/i.test(contentType) || !req.body) {return respond({ reason: 'error', success: false }, 415)}
// 2. Rate limit — from the headers alone, before a byte of the body.
const ip = clientIp(req.headers, submit.clientIp) || undefined
const limited = await passRateLimit({ ip, maxPerMinute: submit.maxPerMinute })
if (limited) {return respond(limited)}
// 3. A body that declares itself too large is refused unread.
const hardCap = Math.floor(options.maxTotalMB * MB) + ENVELOPE_BYTES
const declared = Number(req.headers.get('content-length'))
if (Number.isFinite(declared) && declared > hardCap) {return respond({ reason: 'error', success: false }, 413)}
// 4. Concurrency guard — each file submission holds its files in memory.
if (options.maxConcurrent > 0 && active >= options.maxConcurrent) {return respond({ reason: 'rate_limited', success: false })}
active++
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> = {}
/** Set once → nothing more is kept; the rest of the body is discarded. */
let outcome: null | SubmitFormResult = null
let gate: FileGate | null = null
let stored: null | Parameters<typeof storeSubmission>[0] = null
let pre: null | Promise<void> = null
let chain: Promise<void> = Promise.resolve()
let received = 0
const source = Readable.fromWeb(req.body as never)
const parser = busboy({
// browsers send file names as UTF-8 ("Życiorys.pdf"); the parser's default would read them as Latin-1
defParamCharset: 'utf8',
headers: { 'content-type': contentType },
limits: { fields: 8, fieldSize: VALUES_BYTES, files: options.maxFiles * 4 + 1, fileSize: Math.floor(options.maxSizeMB * MB) + 1 },
})
const stop = (result: SubmitFormResult) => {
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
const formId = fields._form
let values: unknown
try {
values = JSON.parse(fields._values ?? '')
} catch {
values = null
}
if (!formId || !values || typeof values !== 'object' || Array.isArray(values)) {return stop({ reason: 'error', success: false })}
const data = values as Record<string, unknown>
// Honeypot: a fake success, nothing checked further, nothing kept.
const honeypot = submit.honeypotField ?? HONEYPOT_FIELD
if (isHoneypotTripped(data, honeypot)) {return stop({ submissionId: '', success: true })}
const { [honeypot]: _honeypot, ...answers } = data
const token = fields._token?.trim() || undefined
const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token })
if (blocked) {return stop(blocked)}
const checked = await validateSubmitFields({ data: answers, formId, locale, payload })
if ('failure' in checked) {return stop(checked.failure)}
// A repeated request (same attempt key) gets the first answer; nothing is sent twice.
const attemptKey = cleanAttemptKey(fields._attempt)
if (attemptKey) {
const running = inflight.get(attemptKey)
if (running) {return stop(await running)}
// Registered before the next await, so a twin request arriving now waits for this one.
registered = attemptKey
inflight.set(attemptKey, new Promise<SubmitFormResult>((done) => (settle = done)))
const earlier = await findSubmitAttempt(payload, attemptKey)
if (earlier) {return stop(earlier)}
}
if (checked.validation.fileFields.length > 0 && !canCarryFiles(checked.validation.form)) {return stop({ reason: 'delivery', success: false })}
gate = createFileGate({ fields: checked.validation.fileFields, options, transportMaxBytes: await mailAttachmentLimit(payload) })
stored = { attemptKey, formId, locale, payload, validation: checked.validation }
}
const receiveFile = async (name: string, stream: { truncated?: boolean } & Readable, filename: string) => {
pre ??= beforeFiles()
await pre
if (outcome || !gate || !stored) {return void stream.resume()}
const { formId } = stored
const refuse = async (failure: Parameters<typeof fileFailure>[2]) => stop(await fileFailure(payload, formId, failure, locale))
// 9–10. Field, count and name — before any byte of this file.
const started = gate.begin(name, filename)
if ('failure' in started) {
stream.resume()
return refuse(started.failure)
}
const { slot, token } = started
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
// 11. Size, counted while reading.
if (size > slot.maxBytes) {
chunks = []
await refuse(slot.tooLarge())
continue
}
chunks.push(chunk)
// 12. Signature, as soon as the first bytes are here.
if (!headChecked && size >= 16) {
headChecked = true
const wrong = slot.checkStart(chunks.length === 1 ? chunk : Buffer.concat(chunks))
if (wrong) {
chunks = []
await refuse(wrong)
}
}
}
open.delete(stream)
if (outcome) {return}
if (stream.truncated) {return refuse(slot.tooLarge())}
// 13–14. Whole-file checks and the optional scan.
const failure = await gate.finish(token, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks))
if (failure) {await refuse(failure)}
}
parser.on('field', (name, value, info) => {
if (info.valueTruncated || info.nameTruncated) {return stop({ reason: 'error', success: false })}
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 })
})
})
for (const event of ['fieldsLimit', 'filesLimit', 'partsLimit'] as const) {
parser.on(event, () => stop({ kind: 'unknown_fields', reason: 'validation', success: false }))
}
const finish = async () => {
try {
await chain
if (!outcome) {
pre ??= beforeFiles() // a request without a file part still runs every gate
await pre
}
if (!outcome && gate && stored) {
const missing = (gate).end()
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 && !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 })
}
conclude(outcome ?? { reason: 'error', success: false })
}
parser.on('close', () => {
if (done) {return}
done = true
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)
// 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) {abort(413)}
})
source.pipe(parser)
})
} finally {
active--
if (registered) {inflight.delete(registered)}
settle?.(final)
}
return respond(final, abortStatus)
}