forked from mtusi2026/mtusi2026lab5
Лаба 5: Redis Streams очередь + асинхронная обработка изображений (оценка 4)
Переиспользован стек lab4 (LB/2 реплики/Postgres/SeaweedFS). upload теперь 202 queued; отдельный worker-процесс генерирует thumbnail/crop/optimized. Transactional outbox закрывает разрыв COMMIT/publish; durable retry (job_retry_schedule) переживает падение worker во время backoff; lease recovery через XAUTOCLAIM; DLQ-реестр (job_failures) с явным operator replay (scripts/replay_failed.py). make test/test-persistence/test-failover/ validate зелёные; в процессе экспериментов найдены и исправлены два реальных бага (неполный try/except вокруг S3-записи вариантов, ошибка типов asyncpg в построении interval) — см. REPORT.md и evidence/. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
"""Server-side image validation: real format by content, not by the client's claim."""
|
||||
import io
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
CONTENT_TYPE_TO_PIL_FORMAT = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||
|
||||
|
||||
class InvalidImage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def validate(data: bytes, declared_content_type: str, max_pixels: int) -> None:
|
||||
"""Raise InvalidImage if the bytes are not a genuine, within-budget PNG/JPEG."""
|
||||
expected_format = CONTENT_TYPE_TO_PIL_FORMAT.get(declared_content_type)
|
||||
if expected_format is None:
|
||||
raise InvalidImage("unsupported content type")
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as img:
|
||||
# Image.open() only parses the header; check the pixel budget
|
||||
# BEFORE calling .load(), which is what actually decodes pixels.
|
||||
if img.format != expected_format:
|
||||
raise InvalidImage("declared content type does not match actual image format")
|
||||
width, height = img.size
|
||||
if width * height > max_pixels:
|
||||
raise InvalidImage("image exceeds the decoded pixel budget")
|
||||
img.load() # forces full decode; raises on truncated/corrupted data
|
||||
except (UnidentifiedImageError, OSError, ValueError) as exc:
|
||||
raise InvalidImage(str(exc)) from exc
|
||||
Reference in New Issue
Block a user