from __future__ import annotations import io import os from typing import Tuple from PIL import Image, UnidentifiedImageError from .errors import AppError PNG_MAGIC = b"\x89PNG\r\n\x1a\n" JPEG_MAGIC = b"\xff\xd8\xff" def max_upload_bytes() -> int: return max(1, int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))) def max_image_pixels() -> int: return max(1, int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))) def validate_filename(filename: str) -> str: if len(filename) < 1 or len(filename) > 255: raise AppError(400, "invalid_request", "filename length is invalid") for ch in filename: code = ord(ch) if ch in "/\\" or code == 0 or code < 32: raise AppError(400, "invalid_request", "filename contains forbidden characters") return filename def sniff_image(data: bytes, declared_content_type: str) -> str: if declared_content_type not in {"image/png", "image/jpeg"}: raise AppError(415, "unsupported_media_type", "Unsupported media type") if data.startswith(PNG_MAGIC): detected = "image/png" elif data.startswith(JPEG_MAGIC): detected = "image/jpeg" else: raise AppError(415, "unsupported_media_type", "Unsupported or corrupted image") if detected != declared_content_type: raise AppError(415, "unsupported_media_type", "Content-Type does not match body") return detected def validate_image_pixels(data: bytes, content_type: str) -> Tuple[int, int]: Image.MAX_IMAGE_PIXELS = max_image_pixels() try: with Image.open(io.BytesIO(data)) as img: fmt = (img.format or "").upper() if content_type == "image/png" and fmt != "PNG": raise AppError(415, "unsupported_media_type", "Invalid PNG image") if content_type == "image/jpeg" and fmt not in {"JPEG", "MPO"}: raise AppError(415, "unsupported_media_type", "Invalid JPEG image") width, height = img.size if width < 1 or height < 1: raise AppError(415, "unsupported_media_type", "Invalid image dimensions") if width * height > max_image_pixels(): raise AppError(413, "payload_too_large", "Image exceeds pixel limit") img.load() return width, height except AppError: raise except Image.DecompressionBombError as exc: raise AppError(413, "payload_too_large", "Image exceeds pixel limit") from exc except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as exc: raise AppError(415, "unsupported_media_type", "Unsupported or corrupted image") from exc