89 lines
2.8 KiB
Python
89 lines
2.8 KiB
Python
import json
|
||
from typing import Callable
|
||
|
||
# Запас под заголовки multipart (boundary, Content-Disposition и т.п.)
|
||
MULTIPART_OVERHEAD = 64 * 1024
|
||
|
||
|
||
class _BodyTooLarge(Exception):
|
||
pass
|
||
|
||
|
||
class BodySizeLimitMiddleware:
|
||
"""
|
||
Отклоняет слишком большие тела запросов с 413, не дочитывая их.
|
||
|
||
Без этого Starlette сначала целиком принимает multipart (с диска), и только
|
||
потом роутер видит размер — гигабайтный аплоад забивает диск и канал.
|
||
Content-Length проверяется сразу; для chunked-запросов байты считаются
|
||
на лету.
|
||
"""
|
||
|
||
def __init__(self, app, limit_for_path: Callable[[str], int]):
|
||
self.app = app
|
||
self.limit_for_path = limit_for_path
|
||
|
||
async def __call__(self, scope, receive, send):
|
||
if scope["type"] != "http":
|
||
await self.app(scope, receive, send)
|
||
return
|
||
|
||
limit = self.limit_for_path(scope.get("path", ""))
|
||
|
||
content_length = None
|
||
for name, value in scope.get("headers", []):
|
||
if name == b"content-length":
|
||
content_length = value
|
||
break
|
||
|
||
if content_length is not None:
|
||
try:
|
||
declared = int(content_length)
|
||
except ValueError:
|
||
await self._reject(send, 400, "INVALID_REQUEST", "Invalid Content-Length")
|
||
return
|
||
if declared > limit:
|
||
await self._reject(send, 413, "PAYLOAD_TOO_LARGE", "Request body too large")
|
||
return
|
||
|
||
received = 0
|
||
rejected = False
|
||
|
||
async def limited_receive():
|
||
nonlocal received, rejected
|
||
message = await receive()
|
||
if message["type"] == "http.request":
|
||
received += len(message.get("body", b""))
|
||
if received > limit:
|
||
rejected = True
|
||
raise _BodyTooLarge()
|
||
return message
|
||
|
||
async def guarded_send(message):
|
||
# После превышения лимита ответ приложения (обычно 400 «ошибка
|
||
# разбора тела») подменяем на 413
|
||
if not rejected:
|
||
await send(message)
|
||
|
||
try:
|
||
await self.app(scope, limited_receive, guarded_send)
|
||
except _BodyTooLarge:
|
||
pass
|
||
|
||
if rejected:
|
||
await self._reject(send, 413, "PAYLOAD_TOO_LARGE", "Request body too large")
|
||
|
||
@staticmethod
|
||
async def _reject(send, status: int, code: str, message: str):
|
||
body = json.dumps({"code": code, "message": message}).encode()
|
||
await send({
|
||
"type": "http.response.start",
|
||
"status": status,
|
||
"headers": [
|
||
(b"content-type", b"application/json"),
|
||
(b"content-length", str(len(body)).encode()),
|
||
(b"connection", b"close"),
|
||
],
|
||
})
|
||
await send({"type": "http.response.body", "body": body})
|