""" Request size limit middleware. Rejects requests with Content-Length exceeding the configured maximum size. Prevents memory exhaustion from uploading huge files. """ from fastapi import Request from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware class RequestSizeLimitMiddleware(BaseHTTPMiddleware): """Middleware to limit request body size.""" def __init__(self, app, max_size: int = 100 * 1024 * 1024): # 100MB default super().__init__(app) self.max_size = max_size async def dispatch(self, request: Request, call_next): """Check Content-Length header and reject if too large.""" if request.method in ["POST", "PUT", "PATCH"]: content_length = request.headers.get("content-length") if content_length: try: size = int(content_length) if size > self.max_size: return JSONResponse( status_code=413, content={ "detail": f"Request body too large. Maximum size: {self.max_size / (1024 * 1024):.0f}MB" }, ) except ValueError: # Invalid Content-Length header, let the request proceed pass return await call_next(request)