fix: исправить загрузку вложений через async-поток Starlette

Co-authored-by: aider (deepseek/deepseek-chat) <aider@aider.chat>
This commit is contained in:
Evgeny Bushkov
2026-11-06 16:57:18 +03:00
co-authored by aider
parent d4a73152e4
commit 0d58963bc3
3 changed files with 33 additions and 17 deletions
+2 -2
View File
@@ -67,8 +67,8 @@ async def upload_attachment(
if declared not in ("image/png", "image/jpeg"): if declared not in ("image/png", "image/jpeg"):
raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg") raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg")
# Читаем тело потоково с жёстким лимитом. # Читаем тело потоково с жёстким лимитом (async-итератор Starlette).
data, sha, actual = s3.read_upload(request.stream(), declared) data, sha, actual = await s3.read_upload(request.stream(), declared)
att_id = uuid.uuid4() att_id = uuid.uuid4()
key = s3.new_object_key(str(cid), str(att_id)) key = s3.new_object_key(str(cid), str(att_id))
+31 -14
View File
@@ -23,6 +23,13 @@ logger = logging.getLogger("messenger.s3")
PNG_MAGIC = b"\x89PNG\r\n\x1a\n" PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
JPEG_MAGIC = b"\xff\xd8\xff" JPEG_MAGIC = b"\xff\xd8\xff"
# Жёсткий лимит Pillow: любая попытка декодировать больше пикселей
# бросает DecompressionBombError до выделения памяти под растр.
Image.MAX_IMAGE_PIXELS = settings.max_image_pixels
# Сколько байт достаточно, чтобы прочитать заголовок PNG/JPEG и размеры.
_HEADER_BYTES = 64 * 1024
def _client(): def _client():
return boto3.client( return boto3.client(
@@ -63,19 +70,23 @@ def _detect_mime(head: bytes) -> str | None:
return None return None
def _validate_image(data: bytes, declared_mime: str) -> str: def _validate_header(header: bytes, declared_mime: str) -> str:
"""Проверяет magic bytes, декодирует заголовок, считает пиксели. """Проверяет magic bytes и размеры по заголовку.
Полное декодирование не выполняется: Pillow читает только заголовок
(IHDR для PNG, SOF для JPEG), что не выделяет память под растр.
Возвращает фактический MIME. Бросает ApiError(415/413). Возвращает фактический MIME. Бросает ApiError(415/413).
""" """
actual = _detect_mime(data[:16]) actual = _detect_mime(header[:16])
if actual is None: if actual is None:
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG") raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
if actual != declared_mime: if actual != declared_mime:
raise ApiError(415, "unsupported_media_type", "Content-Type не совпадает с содержимым") raise ApiError(415, "unsupported_media_type", "Content-Type не совпадает с содержимым")
try: try:
with Image.open(io.BytesIO(data)) as img: with Image.open(io.BytesIO(header)) as img:
width, height = img.size width, height = img.size
except Image.DecompressionBombError:
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
except (UnidentifiedImageError, OSError): except (UnidentifiedImageError, OSError):
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
if width <= 0 or height <= 0: if width <= 0 or height <= 0:
@@ -85,28 +96,34 @@ def _validate_image(data: bytes, declared_mime: str) -> str:
return actual return actual
def read_upload(stream: BinaryIO, declared_mime: str) -> tuple[bytes, str, str]: async def read_upload(stream, declared_mime: str) -> tuple[bytes, str, str]:
"""Читает поток с лимитом, возвращает (bytes, sha256, actual_mime). """Читает async-поток Starlette с лимитом.
Файл ≤10 MiB, поэтому держим его в памяти — это упрощает валидацию Возвращает (bytes, sha256, actual_mime). Файл ≤10 MiB, поэтому держим
и не создаёт неограниченного потребления RAM (лимит жёсткий). его в памяти — это упрощает валидацию и не создаёт неограниченного
потребления RAM (лимит жёсткий). Валидация заголовка выполняется по
первым 64 KiB до полного чтения тела.
""" """
limit = settings.max_upload_bytes limit = settings.max_upload_bytes
buf = bytearray() buf = bytearray()
hasher = hashlib.sha256() hasher = hashlib.sha256()
while True: header_checked = False
chunk = stream.read(settings.upload_chunk_size) actual = ""
async for chunk in stream:
if not chunk: if not chunk:
break continue
buf.extend(chunk) buf.extend(chunk)
hasher.update(chunk) hasher.update(chunk)
if len(buf) > limit: if len(buf) > limit:
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
if not header_checked and len(buf) >= _HEADER_BYTES:
actual = _validate_header(bytes(buf[:_HEADER_BYTES]), declared_mime)
header_checked = True
if not buf: if not buf:
raise ApiError(400, "invalid_request", "Пустое тело запроса") raise ApiError(400, "invalid_request", "Пустое тело запроса")
data = bytes(buf) if not header_checked:
actual = _validate_image(data, declared_mime) actual = _validate_header(bytes(buf), declared_mime)
return data, hasher.hexdigest(), actual return bytes(buf), hasher.hexdigest(), actual
def put_object(key: str, data: bytes, content_type: str) -> None: def put_object(key: str, data: bytes, content_type: str) -> None:
-1
View File
@@ -69,7 +69,6 @@ def make_user(label):
) )
assert status == 201, (status, user) assert status == 201, (status, user)
basic = base64.b64encode((username + ":" + password).encode()).decode() basic = base64.b64encode((username + ":" + password).encode()).decode()
status, session, _ = request("POST", "/api/v1/auth/sessions", raw=b"", content_type=None) if False else (None, None, None)
# Basic-вход: используем заголовок Authorization напрямую. # Basic-вход: используем заголовок Authorization напрямую.
req = urllib.request.Request( req = urllib.request.Request(
BASE_URL + "/api/v1/auth/sessions", BASE_URL + "/api/v1/auth/sessions",