Добавить приватные S3-вложения: валидация PNG/JPEG, загрузка и метаданные в БД
Байты хранятся в приватном bucket (случайный ключ, без публичного доступа), метаданные и связи — в PostgreSQL (миграция 003_attachments). Лимиты размера/пикселей проверяются до полной распаковки, идемпотентность учитывает состав вложений. bootstrap_s3 идемпотентно создаёт bucket.
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
"""Bounded image validation: magic+full decode, no trust in declared MIME."""
|
||||
import io
|
||||
from PIL import Image, ImageFile, UnidentifiedImageError
|
||||
from .domain import ApiError
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
|
||||
def validate_image(data, declared_type):
|
||||
if declared_type not in ('image/png', 'image/jpeg'):
|
||||
raise ApiError(415, 'unsupported_media_type', 'PNG or JPEG required')
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ApiError(413, 'payload_too_large', 'Image exceeds 10 MiB')
|
||||
if not data:
|
||||
raise ApiError(415, 'unsupported_media_type', 'Empty image')
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as im:
|
||||
real_type = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(im.format)
|
||||
if real_type is None or real_type != declared_type:
|
||||
raise ApiError(415, 'unsupported_media_type', 'Image content type mismatch')
|
||||
if im.width * im.height > MAX_PIXELS:
|
||||
raise ApiError(413, 'payload_too_large', 'Image pixel limit exceeded')
|
||||
im.load() # reject malformed/truncated payload before PUT
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise ApiError(415, 'unsupported_media_type', 'Invalid image') from None
|
||||
except Image.DecompressionBombError:
|
||||
raise ApiError(413, 'payload_too_large', 'Image pixel limit exceeded') from None
|
||||
Reference in New Issue
Block a user