diff --git a/tradein-mvp/backend/app/api/v1/trade_in.py b/tradein-mvp/backend/app/api/v1/trade_in.py index f7a33939..3014e1f6 100644 --- a/tradein-mvp/backend/app/api/v1/trade_in.py +++ b/tradein-mvp/backend/app/api/v1/trade_in.py @@ -28,6 +28,7 @@ from app.schemas.trade_in import ( TradeInEstimateInput, ) from app.services.exporters.trade_in_pdf import generate_trade_in_pdf +from app.services.image_sanitizer import ImageSanitizationError, sanitize_image logger = logging.getLogger(__name__) @@ -479,6 +480,13 @@ async def upload_photo( if len(content) > _MAX_PHOTO_BYTES: raise HTTPException(status_code=413, detail="file too large (max 10 MB)") + # Sanitize: re-encode through Pillow to drop EXIF, kill polyglot payloads, + # cap dimensions. Closes finding #6 from 2026-05-24 audit. + try: + sanitized_bytes, sanitized_ctype = sanitize_image(content) + except ImageSanitizationError as e: + raise HTTPException(status_code=400, detail=str(e)) from e + row = db.execute( text( """ @@ -491,14 +499,15 @@ async def upload_photo( { "eid": str(estimate_id), "fn": file.filename, - "ct": ctype, - "content": content, - "sz": len(content), + "ct": sanitized_ctype, + "content": sanitized_bytes, + "sz": len(sanitized_bytes), }, ).mappings().fetchone() db.commit() logger.info( - "photo uploaded: estimate=%s photo=%s size=%d", estimate_id, row["id"], len(content) + "photo uploaded: estimate=%s photo=%s orig_size=%d sanitized_size=%d ctype=%s", + estimate_id, row["id"], len(content), len(sanitized_bytes), sanitized_ctype, ) return PhotoMeta(**row) diff --git a/tradein-mvp/backend/app/services/image_sanitizer.py b/tradein-mvp/backend/app/services/image_sanitizer.py new file mode 100644 index 00000000..f2df5841 --- /dev/null +++ b/tradein-mvp/backend/app/services/image_sanitizer.py @@ -0,0 +1,70 @@ +"""Image sanitization for user-uploaded photos. + +Re-encodes inbound images through Pillow to: + - strip EXIF (GPS lat/lon, device fingerprint, owner metadata) + - normalize byte stream (a polyglot JPEG with appended payload survives MIME check + but is dropped on re-encode — only the actual image survives) + - enforce max dimension (defend against pixel-flood DoS in downstream renders) + - produce uniform JPEG output (smaller storage; no transparency support needed + for apartment photos) + +Closes finding #6 from 2026-05-24 trade-in audit. +""" + +from __future__ import annotations + +import io +import logging + +from PIL import Image, UnidentifiedImageError + +logger = logging.getLogger(__name__) + +# Max longest edge after re-encode. 2400px = enough for retina apt photo, +# small enough to bound storage & decode cost. +_MAX_DIMENSION = 2400 + +# JPEG quality. 85 is industry standard for photos — visually lossless, +# ~70% size reduction vs original phone JPEGs. +_JPEG_QUALITY = 85 + +# Output content type after sanitization (all inputs transcoded to JPEG). +SANITIZED_CONTENT_TYPE = "image/jpeg" + + +class ImageSanitizationError(ValueError): + """Raised when inbound bytes cannot be decoded as an image.""" + + +def sanitize_image(content: bytes) -> tuple[bytes, str]: + """Decode arbitrary image bytes and re-encode as clean JPEG. + + Args: + content: raw uploaded bytes from the client. + + Returns: + (sanitized_bytes, "image/jpeg") — both ready for storage/serving. + + Raises: + ImageSanitizationError: bytes are not a recognized image format. + """ + try: + with Image.open(io.BytesIO(content)) as img: + img.load() # force full decode; surfaces UnidentifiedImageError early + # Convert any mode (RGBA, P, CMYK, ...) to RGB for JPEG output. + if img.mode != "RGB": + img = img.convert("RGB") + # Resize if oversized; preserve aspect ratio. + if max(img.size) > _MAX_DIMENSION: + img.thumbnail((_MAX_DIMENSION, _MAX_DIMENSION), Image.Resampling.LANCZOS) + buf = io.BytesIO() + # save() does NOT carry over .info / EXIF unless we pass exif=...; we don't. + img.save(buf, format="JPEG", quality=_JPEG_QUALITY, optimize=True) + return buf.getvalue(), SANITIZED_CONTENT_TYPE + except UnidentifiedImageError as e: + raise ImageSanitizationError("not a recognized image format") from e + except Exception as e: + # PIL can raise broad errors (DecompressionBombError, OSError on truncated, ...); + # normalize to one user-facing error type. + logger.warning("image sanitization failed: %s", e) + raise ImageSanitizationError(f"image decode failed: {e}") from e diff --git a/tradein-mvp/backend/pyproject.toml b/tradein-mvp/backend/pyproject.toml index 81f72c5a..63feb98b 100644 --- a/tradein-mvp/backend/pyproject.toml +++ b/tradein-mvp/backend/pyproject.toml @@ -11,6 +11,7 @@ dependencies = [ "pydantic>=2.7.0", "pydantic-settings>=2.3.0", "psycopg[binary]>=3.2.0", + "Pillow>=10.3.0", # photo sanitization re-encode (#6 audit fix) "weasyprint>=62.0", "jinja2>=3.1.0", "httpx>=0.27.0", # для geocoder + scrapers