"""Bounded image inspection: sniff MIME, enforce pixel limit, verify decoding.""" from io import BytesIO from PIL import Image, UnidentifiedImageError # We enforce the configured limit explicitly before any full decode. Disabling # Pillow's own heuristic keeps the error deterministic for the API contract. Image.MAX_IMAGE_PIXELS = None PNG_MAGIC = b"\x89PNG\r\n\x1a\n" JPEG_MAGIC = b"\xff\xd8\xff" class InvalidImage(Exception): pass class ImageTooLarge(Exception): pass def sniff_content_type(data): if data.startswith(PNG_MAGIC): return "image/png" if data.startswith(JPEG_MAGIC): return "image/jpeg" return None def inspect_image(data, declared_content_type, max_pixels): """Validate bytes and return (actual_content_type, width, height).""" actual = sniff_content_type(data) if actual is None or actual != declared_content_type: raise InvalidImage("unsupported or mismatched image content") try: with Image.open(BytesIO(data)) as image: width, height = image.size if width <= 0 or height <= 0: raise InvalidImage("invalid image dimensions") if width * height > max_pixels: raise ImageTooLarge("decoded pixel limit exceeded") if image.format not in ("PNG", "JPEG"): raise InvalidImage("unsupported image format") image.verify() # verify() checks structure; load() catches truncated payloads and # corrupt compressed streams that would otherwise reach the client. with Image.open(BytesIO(data)) as image: image.load() except ImageTooLarge: raise except (UnidentifiedImageError, OSError, ValueError, SyntaxError): raise InvalidImage("corrupt image") from None return actual, width, height