Исправить замечания ревью: битый JPEG, память nginx, 502 вместо 413

JPEG проверяется через djpeg -strict: обрезанный поток с дописанным EOI
теперь даёт 415. Память nginx больше не зависит от тел файлов: загрузка
идёт потоком до API, скачивание без временных файлов, воркеров 2. API не
закрывает соединение при недочитанном теле, что давало HTML 502; nginx
сам отклоняет тела больше лимитов API. Лимит памяти API поднят до 512 MiB
под проверку CMYK-JPEG на 40 Мпикс. Добавлен стресс-тест через LB.
This commit is contained in:
alenchha
2026-11-05 13:53:08 +03:00
parent 2152d0dcad
commit a856128b45
19 changed files with 470 additions and 86 deletions
+36 -15
View File
@@ -1,17 +1,24 @@
"""Integrity checks for uploaded PNG/JPEG with bounded memory.
PNG: own streaming scanner (chunk CRCs, IHDR rules, zlib stream decoded 1 MiB at a time, every row filter byte in
0..4, decoded size equal to the size implied by IHDR, IEND present). JPEG: libjpeg decodes the whole entropy
stream through Pillow in 1/8 scale, so memory stays at ~1/64 of the image. Both finish before anything is stored.
0..4, decoded size equal to the size implied by IHDR, IEND present). JPEG: `djpeg -strict` decodes the whole entropy
stream in a child process at 1/8 scale; Pillow hides libjpeg warnings, and a scan cut short with an appended EOI is
only a warning. Both finish before anything is stored.
"""
import logging
import os
import struct
import subprocess
import threading
import time
import zlib
from PIL import Image
from app import config
from app.errors import ApiError
from app.errors import ApiError, unavailable
log = logging.getLogger("messenger.imagecheck")
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
VALID_DEPTHS = {0: (1, 2, 4, 8, 16), 2: (8, 16), 3: (1, 2, 4, 8), 4: (8, 16), 6: (8, 16)}
@@ -22,6 +29,9 @@ FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"}
FULL_DECODE_MAX_PIXELS = 4000000
SCAN_SECONDS = 10.0
OUT_STEP = 1 << 20
# Progressive 40 Mpx CMYK needs ~320 MiB of coefficients; the cap keeps a hostile file from reaching the container limit.
DJPEG = ("djpeg", "-strict", "-scale", "1/8", "-maxscans", "100", "-maxmemory", "358400", "-outfile", "/dev/null")
jpeg_slot = threading.Lock()
class Invalid(Exception):
@@ -159,6 +169,25 @@ def scan_png(fileobj) -> None:
raise Invalid("pixel data does not match IHDR")
def check_jpeg(fileobj) -> None:
fileobj.flush()
descriptor = fileobj.fileno()
os.lseek(descriptor, 0, os.SEEK_SET)
try:
with jpeg_slot:
done = subprocess.run(DJPEG, stdin=descriptor, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=SCAN_SECONDS, check=False)
except subprocess.TimeoutExpired:
log.error("jpeg_check_timeout")
raise unavailable("Проверка изображения не успела завершиться") from None
# A signal means the checker died (e.g. OOM killer), which says nothing about the file.
if done.returncode < 0:
log.error("jpeg_check_killed signal=%d", -done.returncode)
raise unavailable("Проверка изображения прервана")
if done.returncode != 0:
raise invalid()
def inspect_image(fileobj, size: int, content_type: str) -> None:
"""Raises ApiError 413 (too many pixels) or 415 (not a decodable image of the declared type)."""
try:
@@ -169,21 +198,13 @@ def inspect_image(fileobj, size: int, content_type: str) -> None:
raise invalid()
if width * height > config.MAX_IMAGE_PIXELS:
raise ApiError(413, "payload_too_large", "Изображение превышает 40 млн пикселей")
small = width * height <= FULL_DECODE_MAX_PIXELS
if content_type == "image/png":
scan_png(fileobj)
else:
fileobj.seek(max(0, size - 1024))
if b"\xff\xd9" not in fileobj.read():
raise invalid()
if not small:
if width * height <= FULL_DECODE_MAX_PIXELS:
fileobj.seek(0)
scaled = Image.open(fileobj)
scaled.draft(scaled.mode, (1, 1))
scaled.load()
if small:
fileobj.seek(0)
Image.open(fileobj).load()
Image.open(fileobj).load()
else:
check_jpeg(fileobj)
except ApiError:
raise
except Exception:
+2 -2
View File
@@ -207,7 +207,7 @@ def non_blank(value: object, max_len: int) -> bool:
async def read_json(request: Request, required: Tuple[str, ...], optional: Tuple[str, ...] = ()) -> dict:
if request.headers.get("content-type", "").split(";")[0].strip().lower() != "application/json":
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
too_large = ApiError(413, "payload_too_large", "Тело запроса слишком большое", {"Connection": "close"})
too_large = ApiError(413, "payload_too_large", "Тело запроса слишком большое")
declared = request.headers.get("content-length")
if declared and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES:
raise too_large
@@ -527,7 +527,7 @@ async def upload_attachment(chat_id: str, request: Request):
raise ApiError(415, "unsupported_media_type", "Допускается только image/png или image/jpeg")
declared_length = request.headers.get("content-length")
too_large = ApiError(413, "payload_too_large", "Файл превышает 10 MiB", {"Connection": "close"})
too_large = ApiError(413, "payload_too_large", "Файл превышает 10 MiB")
if declared_length and declared_length.isdigit() and int(declared_length) > config.MAX_UPLOAD_BYTES:
raise too_large
ensure_capacity()