Многоагентный аудит + имплементация: один воркер на файл, точечные правки. Верификация: py_compile (47/47 .py) + tsc --noEmit (0 ошибок). Unit-тесты не прогонялись (окружение не поднято: rollup native dep / нет pytest-venv). Полностью исправлено (169): #1336, #1337, #1339, #1340, #1341, #1342, #1343, #1345, #1346, #1348, #1349, #1350, #1351, #1354, #1356, #1358, #1359, #1360, #1362, #1364, #1365, #1366, #1367, #1368, #1369, #1370, #1371, #1372, #1373, #1374, #1375, #1376, #1377, #1378, #1379, #1380, #1381, #1382, #1384, #1385, #1386, #1387, #1388, #1389, #1390, #1391, #1392, #1394, #1395, #1396, #1397, #1399, #1400, #1401, #1402, #1403, #1404, #1408, #1409, #1410, #1411, #1412, #1413, #1414, #1415, #1416, #1417, #1418, #1420, #1423, #1425, #1426, #1427, #1428, #1429, #1430, #1431, #1432, #1433, #1434, #1435, #1437, #1438, #1439, #1440, #1441, #1442, #1443, #1444, #1445, #1446, #1447, #1448, #1449, #1450, #1451, #1452, #1453, #1454, #1455, #1456, #1457, #1458, #1459, #1460, #1461, #1462, #1463, #1464, #1465, #1466, #1467, #1468, #1469, #1471, #1472, #1473, #1474, #1476, #1478, #1479, #1481, #1482, #1483, #1484, #1485, #1487, #1488, #1489, #1490, #1491, #1492, #1493, #1494, #1495, #1496, #1497, #1499, #1500, #1501, #1502, #1504, #1505, #1506, #1507, #1510, #1514, #1515, #1516, #1517, #1518, #1519, #1521, #1522, #1523, #1524, #1525, #1526, #1527, #1528, #1529, #1531, #1532, #1533, #1534, #1535, #1536, #1537, #1538 Частично (9, in-file часть, остаток cross-file): #1361, #1419, #1422, #1424, #1470, #1475, #1477, #1480, #1498 Требуют cross-file (3, не тронуты): #1338, #1363, #1421 Пропущено (1): #1539 Не входило в партию: 22 needs-Leha issue (нужны решения владельца). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
74 lines
3 KiB
Python
74 lines
3 KiB
Python
"""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, ImageOps, 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
|
|
# Bake EXIF Orientation into pixels BEFORE stripping EXIF, else phone
|
|
# portrait photos (Orientation=6/8) end up rotated 90/270° once the tag
|
|
# is gone. No-op when there is no orientation tag.
|
|
img = ImageOps.exif_transpose(img)
|
|
# 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
|