Files
mtusi2026lab7/src/api/body_limit.py
T

103 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Предел размера тела запроса вне загрузки вложения (лаба 7, рубрика:
«ограничение размера запросов»).
Чистое ASGI-middleware внутри `AuthenticationMiddleware`, до роутера: у
ответа есть `X-Request-Id`, `X-Instance-Id` и строка access-лога. Порядок
кодов прежний — «сначала аутентификация» (`contracts/README.md`): без
токена на защищённой ручке — 401 (тело при этом тоже не читается), с
токеном и на публичных ручках (вход, регистрация) — 400 раньше разбора
тела и проверки Basic. `Content-Length`
больше `REQUEST_BODY_MAX_BYTES` — 400 до вызова приложения, тело не
читается; тело частями — счётчик в обёртке `receive`: как только прочитано
больше предела, приложение получает `http.disconnect`, его ответ на обрыв
заменяется 400, остаток не читается. Уже начатый ответ не трогается.
Загрузка вложения (`POST …/attachments`) — свой предел сервиса (10 MiB,
порядок проверок `src/services/AGENTS.md`). 400, а не 413: на JSON-ручках
`contracts/openapi.json` объявляет 400 `invalid_request`, а 413 — только у
загрузки. В LB предела нет: ответ HAProxy был бы без `X-Instance-Id`, а
контракт допускает это только у ошибок соединения LB (502, 503, 504).
"""
import re
from starlette.requests import HTTPConnection
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from src.api.handlers import error_response
from src.constants import REQUEST_BODY_MAX_BYTES, UPLOAD_PATH_PATTERN
BODY_TOO_LARGE = "Request body is too large"
_UPLOAD_PATH = re.compile(UPLOAD_PATH_PATTERN)
def _declared_length(scope: Scope) -> int | None:
for name, value in scope["headers"]:
if name == b"content-length":
try:
return int(value)
except ValueError:
return None
return None
class BodyLimitMiddleware:
def __init__(
self, app: ASGIApp, *, max_bytes: int = REQUEST_BODY_MAX_BYTES
) -> None:
self.app = app
self.max_bytes = max_bytes
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http" or (
scope["method"] == "POST" and _UPLOAD_PATH.fullmatch(scope["path"])
):
await self.app(scope, receive, send)
return
declared = _declared_length(scope)
if declared is not None and declared > self.max_bytes:
await self._reject(scope, receive, send)
return
received = 0
over = False
started = False
async def limited_receive() -> Message:
nonlocal received, over
if over:
return {"type": "http.disconnect"}
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > self.max_bytes:
over = True
return {"type": "http.disconnect"}
return message
async def guarded_send(message: Message) -> None:
nonlocal started
# ответ приложения на «обрыв» заменяется отказом по размеру
if over and not started:
return
if message["type"] == "http.response.start":
started = True
await send(message)
try:
await self.app(scope, limited_receive, guarded_send)
except Exception:
if not (over and not started):
raise
if over and not started:
await self._reject(scope, receive, send)
async def _reject(self, scope: Scope, receive: Receive, send: Send) -> None:
response = error_response(
HTTPConnection(scope),
status_code=400,
code="invalid_request",
message=BODY_TOO_LARGE,
)
await response(scope, receive, send)