fix(tradein-photos): sanitize uploaded images via Pillow re-encode #511
No reviewers
Labels
No labels
admin
analytics
auth
automation
bug
business
chore
ci
compliance
data
data-moat
docs
duplicate
dx
enhancement
Fable 5 ревью
feedback/max
generative
GG-форсайт
needs-discussion
needs-human
observability
pause-bots
performance
priority/p0
priority/p1
priority/p2
priority/p3
scope/backend
scope/db
scope/devops
scope/frontend
scope/qa
scrapers
security
site-finder
stage/1
stage/2
status/blocked
status/done
status/needs-analysis
status/needs-fix
status/qa
status/ready
status/review
status/wip
tech-debt
tradein
ux
week ревью 1
wontfix
вторичка
ИРД
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference: lekss361/gendesign#511
Loading…
Add table
Reference in a new issue
No description provided.
Delete branch "feat/tradein-photo-sanitization"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Closes finding #6 from 2026-05-24 audit.
upload_photopreviously stored raw uploaded bytes verbatim and served them back with the originalimage/*content-type. Risks:estimate_photos.contentforever, and was served back labeled as image — any downstream consumer that sniffs or reuses the bytes could execute the payload.Approach
New
services/image_sanitizer.py(~70 lines, pure — no DB/I/O):Image.open()+img.load()forces full decode (surfaces malformed input early).Image.Resampling.LANCZOSthumbnail.exif=kwarg → metadata dropped.(bytes, "image/jpeg"); raisesImageSanitizationErroron undecodable input.upload_photocallssanitize_image()after the existing 10MB / 12-per-estimate / MIME-whitelist filters. Sanitizer failure → HTTP 400. Stored bytes + content_type are the sanitized ones; log records both original and sanitized sizes for monitoring.Pin
Pillow>=10.3.0explicitly in pyproject.toml (was transitive via weasyprint — pin defends against a weasyprint upgrade silently dropping it).No HEIC support added in this PR — Pillow without
pillow-heifrejects HEIC withUnidentifiedImageError, surfaced as 400. Separate PR if needed.Smoke test (local, in worker)
No existing photo tests in repo → no test fixup needed.
Test plan
POST /api/v1/trade-in/estimate/{id}/photos; download viaGET /photos/{photo_id}; verifyexiftoolshows zero EXIF tags.<?php ?>block); verify stored bytes do not contain the payload.text/plainmasquerading via filename trick; verify 400 (already caught by MIME whitelist) or 400 from sanitizer.Deep Code Review — verdict
Summary
Security review (focus)
img.save()безexif=kwarg: Pillow не переноситinfo['exif']на JPEG output по умолчанию. Подтверждено корректно.Image.open+img.load()декодирует только пиксельные данные;img.save()пишет свежий JPEG поток, любой appended PHP/JS payload отбрасывается. Корректно.PIL.Image.MAX_IMAGE_PIXELSпо умолчанию ≈89M пикселей (DecompressionBombErrorловится вexcept Exception→ 400). В сочетании с upstream_MAX_PHOTO_BYTES = 10 MiBдостаточная защита. Явный коммент проMAX_IMAGE_PIXELSможно добавить, но не блокер.Content-Typeheader.image/jpeg— устраняет MIME confusion для serving endpoint (get_photoотдаётrow.content_typeкакmedia_type).Correctness
convert("RGB")для RGBA/P/CMYK — теряет alpha (для фото квартир OK).img.thumbnail()LANCZOS, preserves aspect ratio.db.commit()после sanitize — sanitize fail → HTTPException 400 до любого DB write. Нет partial state.Performance
run_in_threadpool. Follow-up.Conventions
from __future__ import annotations, type hints, module-private constants,logging.getLogger(__name__)— matches backend conventions.ImageSanitizationError(ValueError)— чистая иерархия.except Exceptionобоснован комментом + logging + typed re-raise — defensive для third-party decoder.Tests (G — minor gap)
image_sanitizer.py(idiomatic case: valid JPEG → EXIF dropped; garbage → raisesImageSanitizationError; 5000×5000 → resized). PR описывает в-worker smoke test, но не покрыт. Не блокер (PR-овский test plan покрывает integration after deploy), но follow-up ticket разумен.Vault cross-ref
/vault-writeзафиксировать sanitization policy (JPEG-only re-encode, 2400px cap, q=85, EXIF drop) вdecisions/. Task для main session.Minor / follow-up
_ALLOWED_IMAGE_TYPESwhitelist'итimage/heic, но безpillow-heifсторонней зависимости Pillow вернётUnidentifiedImageError→ 400. Слегка confusing UX (whitelisted MIME, но reject). Либо удалить heic из whitelist, либо добавитьpillow-heif. Не блокер.Positive
services/image_sanitizer.pypure, без DB/I/O, testable.orig_size+sanitized_size+ctypeдаёт monitoring базу для аудита размеров.Recommended next steps
sanitize_image(3 кейса) + decision запись в vault.run_in_threadpoolдля decode под нагрузкой; убратьimage/heicиз whitelist либо добавитьpillow-heif.