Files
romm/backend/handler/middleware/upload_size_middleware.py
Georges-Antoine Assi 96833892ce security: enforce asset upload limits before spooling, cover screenshots
Addresses the Greptile review on #3952.

- Reject oversized asset uploads from Content-Length in middleware, before
  FastAPI parses and spools the multipart body to temporary storage. The
  handler-level check stays as a backstop for chunked requests.
- Apply the limit to screenshot fields on the save, state and standalone
  screenshot endpoints, not just the primary file.
- Clamp the autocleanup limit to at least 1 so a non-positive value cannot
  wipe every save in a slot.
- Document the new settings in env.template.

Rename MAX_SAVE_UPLOAD_SIZE_BYTES to MAX_ASSET_UPLOAD_SIZE_BYTES now that it
covers states and screenshots too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 09:24:42 -04:00

65 lines
2.1 KiB
Python

from re import Pattern
from starlette.datastructures import Headers
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
class UploadSizeLimitMiddleware:
"""Reject oversized uploads on the given paths from their Content-Length.
FastAPI resolves `UploadFile` parameters (spooling the whole multipart body
to temporary storage) before the endpoint runs, so a handler-level size
check cannot prevent the disk usage it is meant to bound. Rejecting here,
before the body is read, is what actually caps it.
"""
UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH"})
def __init__(
self,
app: ASGIApp,
*,
max_size: int,
paths: list[Pattern],
) -> None:
self.app = app
self.max_size = max_size
self.paths = paths
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if (
scope["type"] != "http"
or not self.max_size
or scope["method"] not in self.UNSAFE_METHODS
or not any(pattern.match(scope["path"]) for pattern in self.paths)
):
await self.app(scope, receive, send)
return
content_length = Headers(scope=scope).get("content-length")
if content_length is not None:
try:
declared_size = int(content_length)
except ValueError:
response = JSONResponse(
{"detail": "Invalid Content-Length header"}, status_code=400
)
await response(scope, receive, send)
return
if declared_size > self.max_size:
response = JSONResponse(
{
"detail": (
f"Request body exceeds the maximum allowed size of "
f"{self.max_size} bytes"
)
},
status_code=413,
)
await response(scope, receive, send)
return
await self.app(scope, receive, send)