forked from mtusi2026/mtusi2026lab4
37 lines
1.5 KiB
Python
37 lines
1.5 KiB
Python
"""Server-side image validation: real format by content, not by the client's claim."""
|
|
import io
|
|
|
|
from PIL import Image, UnidentifiedImageError
|
|
from PIL.Image import DecompressionBombError
|
|
|
|
CONTENT_TYPE_TO_PIL_FORMAT = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
|
|
|
|
|
class InvalidImage(Exception):
|
|
pass
|
|
|
|
|
|
class ImageTooLarge(InvalidImage):
|
|
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 ImageTooLarge("image exceeds the decoded pixel budget")
|
|
img.load() # forces full decode; raises on truncated/corrupted data
|
|
except DecompressionBombError as exc:
|
|
raise ImageTooLarge("image exceeds the decoded pixel budget") from exc
|
|
except (UnidentifiedImageError, OSError, ValueError) as exc:
|
|
raise InvalidImage(str(exc)) from exc
|