Spaces:
Sleeping
Sleeping
File size: 3,274 Bytes
a027087 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | """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."
|