"""Request limits applied before FastAPI parses multipart uploads.""" from __future__ import annotations from fastapi import HTTPException from starlette.responses import JSONResponse from starlette.types import ASGIApp, Message, Receive, Scope, Send ENHANCE_PATH = "/api/enhance" MULTIPART_OVERHEAD_BYTES = 64 * 1024 def _route_path(scope: Scope) -> str: """Return the request path after the ASGI root path, like Starlette routing.""" path = scope.get("path", "") root_path = scope.get("root_path", "") if not root_path or not path.startswith(root_path): return path if path == root_path: return "" if path[len(root_path)] == "/": return path[len(root_path) :] return path class UploadBodyTooLarge(HTTPException): """The complete multipart request exceeded its bounded size.""" def __init__(self, max_request_bytes: int) -> None: super().__init__( status_code=413, detail=( "The upload request exceeds the configured file-size limit " f"of {max_request_bytes - MULTIPART_OVERHEAD_BYTES:,} bytes." ), ) class UploadBodyLimitMiddleware: """Bound enhancement request bodies before Starlette spools multipart files.""" def __init__(self, app: ASGIApp, max_request_bytes: int) -> None: self.app = app self.max_request_bytes = max_request_bytes async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if ( scope["type"] != "http" or scope.get("method") != "POST" or _route_path(scope) != ENHANCE_PATH ): await self.app(scope, receive, send) return content_length = self._content_length(scope) if content_length is not None and content_length > self.max_request_bytes: response = JSONResponse( status_code=413, content={ "error": { "code": "upload_too_large", "message": self._error_message(), } }, ) await response(scope, receive, send) return bytes_received = 0 async def limited_receive() -> Message: nonlocal bytes_received message = await receive() if message["type"] == "http.request": bytes_received += len(message.get("body", b"")) if bytes_received > self.max_request_bytes: raise UploadBodyTooLarge(self.max_request_bytes) return message await self.app(scope, limited_receive, send) @staticmethod def _content_length(scope: Scope) -> int | None: for name, value in scope.get("headers", []): if name.lower() == b"content-length": try: length = int(value) except (TypeError, ValueError): return None return length if length >= 0 else None return None def _error_message(self) -> str: max_file_bytes = self.max_request_bytes - MULTIPART_OVERHEAD_BYTES return f"The upload exceeds the {max_file_bytes:,}-byte limit."