Skip to content

fix(backend): enforce multipart limits per route - #8251

Merged
krushnarout merged 23 commits into
BasedHardware:mainfrom
RatnamOjha:fix/7130-multipart-route-limits
Jul 15, 2026
Merged

krushnarout merged 23 commits into
BasedHardware:mainfrom
RatnamOjha:fix/7130-multipart-route-limits

Conversation

@RatnamOjha

@RatnamOjha RatnamOjha commented Jun 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #7130

Summary

This PR replaces the backend-wide MultiPartParser.max_part_size = 200 * 1024 * 1024 monkey-patch with explicit, route-appropriate multipart limits.

The previous startup-time mutation made every multipart endpoint inherit the voice-message endpoint's 200 MB allowance. That preserved uploads after Starlette introduced a default multipart-part limit, but it also allowed endpoints handling small images or form payloads to accept parts far larger than their use case requires.

This change:

  • removes the global Starlette parser mutation from backend/main.py;
  • introduces a reusable multipart parsing utility with per-route configuration;
  • enforces the configured limit for both uploaded files and ordinary multipart fields;
  • supports FastAPI endpoints declared with UploadFile = File(...);
  • supports endpoints that parse forms manually with request.form();
  • preserves application/x-www-form-urlencoded behavior for Twilio form posts;
  • declares explicit limits on every upload route covered by the issue;
  • adds parser, compatibility, global-state, and production-route coverage tests.

Motivation

The old global cap used the voice-message PCM ceiling as the default for all multipart endpoints:

MultiPartParser.max_part_size = 200 * 1024 * 1024

That meant an authenticated request could send a part of up to 200 MB to routes that normally process only a thumbnail, profile sample, chat attachment, import archive, sync chunk, or small phone-call form.

Per-route caps reduce the maximum allocation available through each endpoint to a value appropriate for that endpoint's actual workload. This narrows the memory-exhaustion surface without reducing the existing voice-message allowance.

Dependency state

The issue originally suggested upgrading from Starlette 0.40.x to 0.46.x because Request.form(max_part_size=...) became available in newer Starlette releases.

The repository has moved forward since the issue was opened and currently pins:

  • fastapi==0.121.0
  • starlette==0.49.1

Therefore, this PR does not include an additional dependency bump.

There is also an important Starlette 0.49.1 detail: max_part_size limits in-memory non-file form fields, but uploaded file bytes are streamed into UploadFile without applying that same size check. Calling Request.form(max_part_size=...) alone would not fully satisfy the security goal for file uploads.

To cover both cases, this PR adds FileSizeLimitedMultiPartParser, which:

  • retains Starlette's existing non-file field enforcement;
  • counts uploaded file bytes as parser callbacks arrive;
  • rejects a file part as soon as its cumulative size exceeds the route limit;
  • tracks the size independently across multiple incoming request chunks;
  • keeps Starlette's existing MultiPartException cleanup behavior.

Implementation

Shared multipart utility

backend/utils/multipart.py contains:

  • named constants for each upload category;
  • @max_part_size(...), which attaches the selected cap to a FastAPI endpoint;
  • MultipartMaxPartSizeRoute, a custom APIRoute that parses and caches multipart data with the endpoint's declared cap before FastAPI resolves File(...) parameters;
  • FileSizeLimitedMultiPartParser, which extends Starlette's parser to enforce the cap on file parts as well as regular fields;
  • parse_multipart_form(...), for endpoints that manually parse the request body.

The parsed FormData is cached on the request, matching Starlette's normal request-form behavior. FastAPI can then resolve UploadFile parameters without reparsing or rereading the request stream.

Manual form parsing

Two routes parse their request bodies manually:

  • /v2/voice-message/transcribe
  • /v1/phone/twiml

They call parse_multipart_form(...) directly so their existing control flow and dependency order remain intact.

For non-multipart content types, the helper delegates to the normal request.form() implementation. This is necessary for Twilio, which normally sends application/x-www-form-urlencoded payloads.

Route limits

Area Route Limit Notes
Voice messages POST /v2/voice-messages 200 MB Preserves the existing voice/PCM ceiling
Voice transcription POST /v2/voice-message/transcribe 200 MB Applies only to multipart mode; the octet-stream path retains _MAX_PCM_BODY_BYTES
Chat files POST /v2/files 50 MB Explicit chat attachment limit
Chat files (legacy) POST /v1/files 50 MB Matches the v2 chat-file route
Sync audio (deprecated) POST /v1/sync-local-files 50 MB Keeps the legacy endpoint aligned with v2
Sync audio POST /v2/sync-local-files 50 MB Appropriate for sync audio batches
Speech profile POST /v3/upload-audio 25 MB Covers the expected 5-120 second profile sample
App creation POST /v1/apps 10 MB App image plus form metadata
App update PATCH /v1/apps/{app_id} 10 MB Optional app image
Persona creation POST /v1/personas 10 MB Persona image plus form metadata
Persona update PATCH /v1/personas/{persona_id} 10 MB Optional persona image
App thumbnail POST /v1/app/thumbnails 10 MB Thumbnail-specific upload
Limitless import POST /v1/import/limitless 100 MB ZIP import payload
Twilio form POST /v1/phone/twiml 5 MB Small webhook form; URL-encoded requests remain supported

Request behavior

Within the limit

  • Multipart fields and files are parsed normally.
  • UploadFile endpoints receive the same objects they received before.
  • Existing route business logic is unchanged.
  • URL-encoded form requests continue through Starlette's normal parser.

Over the limit

  • Parsing stops when the current multipart part exceeds its route's cap.
  • Temporary files opened by Starlette are closed through the existing parser error path.
  • The request returns HTTP 400 with Starlette's multipart size error.
  • The endpoint's application logic does not run.

The limit is per multipart part, matching Starlette's max_part_size model and the scope of #7130. It is not a total request-body-size limit.

Security impact

Before this PR, all multipart routes effectively inherited a 200 MB per-part allowance.

After this PR:

  • image-oriented endpoints are limited to 10 MB;
  • speech profiles are limited to 25 MB;
  • chat and sync uploads are limited to 50 MB;
  • imports are limited to 100 MB;
  • phone-call multipart forms are limited to 5 MB;
  • only voice-message routes retain the 200 MB allowance they require.

This reduces the worst-case per-part allocation available through smaller upload surfaces while retaining current functionality for large voice payloads.

Tests

Added backend/tests/unit/test_multipart_limits.py with coverage for:

  • rejecting a file part one byte over its limit;
  • accepting a file part exactly at its limit;
  • counting a file part correctly when its bytes arrive across multiple request chunks;
  • rejecting an oversized non-file multipart field;
  • preserving application/x-www-form-urlencoded form parsing;
  • confirming the global Starlette MultiPartParser.max_part_size value is not mutated;
  • auditing the production routes to ensure each expected route declares the intended named limit.

Focused test command:

cd backend
pytest tests/unit/test_multipart_limits.py -v

Result:

7 passed

Additional validation:

python -m py_compile \
  backend/utils/multipart.py \
  backend/main.py \
  backend/routers/apps.py \
  backend/routers/chat.py \
  backend/routers/imports.py \
  backend/routers/phone_calls.py \
  backend/routers/speech_profile.py \
  backend/routers/sync.py \
  backend/tests/unit/test_multipart_limits.py

git diff --check

Both completed successfully.

Product invariants affected

  • INV-MEM-1

Compatibility and risk

  • No API paths, request field names, or response schemas change.
  • No database or storage migration is required.
  • The octet-stream desktop PTT path remains governed by its existing 200 MB body check.
  • The change affects multipart parsing only.
  • The custom route class is enabled only on routers containing capped upload endpoints.
  • Routes without @max_part_size(...) continue using FastAPI's normal request handling.
  • Manual parsers preserve URL-encoded form requests.
  • Oversized multipart requests may now fail earlier than before, which is the intended behavior.

Out of scope

  • This PR does not introduce a total request-body-size limit.
  • It does not change downstream file-type, duration, quota, authentication, or rate-limit validation.
  • It does not change audio decoding, transcription, conversation lifecycle, WebSocket behavior, or the listen/pusher protocol.
  • It does not alter dependency versions because the repository already uses versions newer than those proposed in the original issue.

Reviewer guide

The main review points are:

  1. backend/utils/multipart.py: parser behavior, file-byte accounting, request form caching, and URL-encoded fallback.
  2. Router declarations: whether each route has an appropriate named limit.
  3. backend/main.py: confirmation that the global monkey-patch is fully removed.
  4. backend/tests/unit/test_multipart_limits.py: boundary, split-chunk, compatibility, and route-audit coverage.

Review in cubic

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

backend: cap multipart upload size per-route instead of globally

5 participants