Skip to content

Multipart: limit violations are silently swallowed when the parse completes in the same pump (onDone clobbers the onError exit) #6392

Closed

Description

@Chaoran-Huang

What version of Effect is running?

@effect/platform 0.94.5 (effect 3.x), verified still present in @effect/platform 0.97.0 — the code in question is unchanged.

What steps can reproduce the bug?

Declare any multipart limit and send a small request that violates it — the request succeeds as if the limit didn't exist:

import {
  HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, Multipart,
} from '@effect/platform';
import { BunHttpServer } from '@effect/platform-bun';
import { Effect, Layer, Option, Schema } from 'effect';

const Api = HttpApi.make('T').add(
  HttpApiGroup.make('g').add(
    HttpApiEndpoint.post('up', '/up')
      .setPayload(
        HttpApiSchema.Multipart(Schema.Struct({ documents: Multipart.FilesSchema }), {
          maxParts: Option.some(2),
        }),
      )
      .addSuccess(Schema.String)
      .addError(Multipart.MultipartError, { status: 413 }),
  ),
);
const GroupLive = HttpApiBuilder.group(Api, 'g', (h) => h.handle('up', () => Effect.succeed('ok')));
const { handler } = HttpApiBuilder.toWebHandler(
  HttpApiBuilder.api(Api).pipe(Layer.provide(GroupLive), Layer.provideMerge(BunHttpServer.layerContext)),
);

const fd = new FormData();
for (let i = 0; i < 3; i++) fd.append('documents', new File(['x'], `f${i}.txt`));
const res = await handler(new Request('http://x/up', { method: 'POST', body: fd }));
console.log(res.status); // 200 — expected 413 (MultipartError TooManyParts)

The same holds for maxFileSize and maxFieldSize. maxTotalSize appears to work through HttpApi, but only because withLimitsContext also sets IncomingMessage.MaxBodySize, which the body stream enforces independently and aborts the parse before it completes.

Root cause

It is not a limit-plumbing problem — the annotation, Multipart.withLimits, makeConfig, and multipasta's enforcement all work. multipasta signals a limit violation via onError but (by design, as a callback parser) continues parsing and always fires onDone at the end. Multipart.makeChannel stores both signals in the same slot:

onError(error_) {
  exit = Option.some(Exit.fail(convertError(error_)));
},
onDone() {
  exit = Option.some(Exit.void); // clobbers a previously stored failure
}

The consuming partsChannel only observes exit between pumps, and pump feeds the parser with mailbox.takeAll batches. So whenever the limit error and end-of-parse land in the same pump — always for single-chunk bodies (i.e. every small upload), and commonly otherwise due to batching — onDone overwrites the buffered failure with Exit.void and the violation vanishes.

Discriminating repro, no HTTP involved — the same 3-part body under maxParts: 2 fails or succeeds depending only on chunk timing:

import { Multipart } from '@effect/platform';
import { BunContext } from '@effect/platform-bun'; // or NodeContext
import { Effect, Exit, Option, Stream } from 'effect';

const B = 'testboundary123';
const part = (name: string) =>
  `--${B}\r\ncontent-disposition: form-data; name="documents"; filename="${name}"\r\ncontent-type: text/plain\r\n\r\nhello\r\n`;
const full = part('f0.txt') + part('f1.txt') + part('f2.txt') + `--${B}--\r\n`;
const enc = new TextEncoder();
const headers = { 'content-type': `multipart/form-data; boundary=${B}` };
const splitAt = full.indexOf(`--${B}--`);

const run = (chunks: string[], delayed: boolean) =>
  Effect.runPromiseExit(
    Multipart.withLimits(
      Multipart.toPersisted(
        Stream.pipeThroughChannel(
          Stream.fromIterable(chunks).pipe(
            Stream.mapEffect((c) =>
              delayed ? Effect.as(Effect.sleep('20 millis'), enc.encode(c)) : Effect.succeed(enc.encode(c)),
            ),
          ),
          Multipart.makeChannel<never>(headers),
        ),
      ),
      { maxParts: Option.some(2) },
    ).pipe(Effect.scoped, Effect.provide(BunContext.layer)),
  );

console.log((await run([full], false))._tag);
// Success — limit violation silently swallowed

console.log((await run([full.slice(0, splitAt), full.slice(splitAt)], true))._tag);
// Failure (MultipartError TooManyParts) — error lands in an earlier pump than onDone

What is the expected behavior?

Limit violations fail the parts stream deterministically with the corresponding MultipartError, regardless of how the body is chunked.

Suggested fix

First signal wins — don't let completion overwrite a failure:

onDone() {
  if (Option.isNone(exit)) {
    exit = Option.some(Exit.void);
  }
}

(Possibly also stop buffering parts once a failure is stored.)

Notes

  • Security-relevant: upload size/part caps declared on HttpApi endpoints are silently bypassed for realistic request sizes, which defeats DoS hardening.
  • Platform-agnostic: the clobbering lives in @effect/platform's Multipart.makeChannel, so Node/Bun/web are all affected.
  • Related but distinct: @effect/platform-bun multipart.toPersisted hangs when maxTotalSize is exceeded mid-file #6284 (hang when maxTotalSize trips mid-file, rooted in multipasta's write()); this issue is about violations being swallowed rather than hanging.

Activity

  1. added
    bug
    on Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

4.0bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions