from __future__ import annotations import unicodedata import warnings from typing import BinaryIO, Optional, Tuple from PIL import Image from app import config from app.errors import ApiError, payload_too_large, unsupported_media_type # Pillow itself refuses > 2x this value; our own check below rejects anything above it before decoding. Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS Image.LOAD_TRUNCATED_IMAGES = False PNG_MAGIC = b"\x89PNG\r\n\x1a\n" JPEG_MAGIC = b"\xff\xd8\xff" FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"} SNIFF_BYTES = 8 # Bidi overrides/isolates make "gpj.exe" look like "exe.jpg"; reject them together with control characters. _BIDI_CONTROLS = set("‪‫‬‭‮⁦⁧⁨⁩‎‏") def validate_filename(name: Optional[str]) -> str: bad = ApiError(400, "invalid_request", "filename must be 1-255 characters without path separators or control characters") if name is None or not 1 <= len(name) <= 255 or not name.strip() or name in (".", ".."): raise bad for ch in name: if ch in "/\\" or ch in _BIDI_CONTROLS or unicodedata.category(ch) in ("Cc", "Zl", "Zp"): raise bad return name def declared_type(header: Optional[str]) -> str: media = (header or "").split(";", 1)[0].strip().lower() if media not in FORMATS: raise unsupported_media_type("Content-Type must be image/png or image/jpeg") return media def sniff(head: bytes) -> Optional[str]: if head.startswith(PNG_MAGIC): return "image/png" if head.startswith(JPEG_MAGIC): return "image/jpeg" return None def _open(fp: BinaryIO, fmt: str) -> Image.Image: fp.seek(0) return Image.open(fp, formats=[fmt]) def inspect(fp: BinaryIO, content_type: str) -> Tuple[int, int]: """Check pixel count from the header, then fully decode to reject corrupted files. Runs in a worker thread under a semaphore: decoding is the only step whose memory grows with pixels. """ fmt = FORMATS[content_type] corrupt = unsupported_media_type("file is not a valid " + fmt + " image") try: with warnings.catch_warnings(): warnings.simplefilter("error", Image.DecompressionBombWarning) with _open(fp, fmt) as im: width, height = im.size if width < 1 or height < 1: raise corrupt if width * height > config.MAX_IMAGE_PIXELS: raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS) if fmt == "PNG": im.verify() # chunk CRCs; the object is unusable afterwards with _open(fp, fmt) as im: if fmt == "JPEG": # DCT scaling still walks the whole entropy-coded stream but allocates 1/64 of the pixels. im.draft(None, (max(1, width // 8), max(1, height // 8))) im.load() except ApiError: raise except (Image.DecompressionBombError, Image.DecompressionBombWarning): raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS) from None except (OSError, SyntaxError, ValueError, EOFError, MemoryError): raise corrupt from None return width, height