Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(uploads): decode only the image formats each endpoint accepts (#104003)

Tom Piccirelloc37e8a29abb9
diff --git a/posthog/api/test/test_uploaded_media.py b/posthog/api/test/test_uploaded_media.py
index 39adc61acba9..18609aeb1964 100644
--- a/posthog/api/test/test_uploaded_media.py
+++ b/posthog/api/test/test_uploaded_media.py
@@ -161,6 +161,19 @@ class TestMediaAPI(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ def test_rejects_a_headerless_dib_even_though_pillow_reports_it_as_bmp(self) -> None:
+ buffer = io.BytesIO()
+ Image.new("RGB", (2, 2), color="red").save(buffer, format="DIB")
+ fake_file = SimpleUploadedFile(name="logo.bmp", content=buffer.getvalue(), content_type="image/bmp")
+ with self.settings(OBJECT_STORAGE_ENABLED=True, OBJECT_STORAGE_MEDIA_UPLOADS_FOLDER=TEST_BUCKET):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/uploaded_media",
+ {"image": fake_file},
+ format="multipart",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+ assert UploadedMedia.objects.count() == 0
+
def test_download_sets_nosniff_and_strict_csp(self) -> None:
with self.settings(OBJECT_STORAGE_ENABLED=True, OBJECT_STORAGE_MEDIA_UPLOADS_FOLDER=TEST_BUCKET):
with open(get_path_to("a-small-but-valid.gif"), "rb") as image:
diff --git a/posthog/api/uploaded_media.py b/posthog/api/uploaded_media.py
index 580a41e2b43f..f1723bf3a437 100644
--- a/posthog/api/uploaded_media.py
+++ b/posthog/api/uploaded_media.py
@@ -23,41 +23,21 @@ from statshog.defaults.django import statsd
from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models import UploadedMedia
-from posthog.models.uploaded_media import MEDIA_PURPOSES, PRIVATE_MEDIA_PURPOSES, ObjectStorageUnavailable
+from posthog.models.uploaded_media import (
+ MEDIA_PURPOSES,
+ PRIVATE_MEDIA_PURPOSES,
+ ObjectStorageUnavailable,
+ is_inline_safe_content_type,
+ sniff_image_content_type,
+)
from posthog.storage import object_storage
from posthog.storage.object_storage import ObjectStorageError
FOUR_MEGABYTES = 4 * 1024 * 1024
-# Content types safe to render inline in a browser when served from the
-# unauthenticated /uploaded_media endpoint. Anything outside this set is
-# served as a download with a generic content type so stored HTML/SVG/etc.
-# cannot execute script in the application origin.
-_INLINE_SAFE_CONTENT_TYPES = frozenset(
- {
- "image/png",
- "image/jpeg",
- "image/jpg",
- "image/gif",
- "image/webp",
- "image/avif",
- "image/bmp",
- }
-)
-
logger = structlog.getLogger(__name__)
-def _normalize_content_type(value: str | None) -> str:
- if not value:
- return ""
- return value.split(";", 1)[0].strip().lower()
-
-
-def _is_inline_safe_content_type(content_type: str | None) -> bool:
- return _normalize_content_type(content_type) in _INLINE_SAFE_CONTENT_TYPES
-
-
def _attachment_disposition(file_name: str | None) -> str:
"""Build a Content-Disposition header that preserves the original filename.
@@ -85,7 +65,7 @@ def _attachment_disposition(file_name: str | None) -> str:
return f"attachment; filename=\"{escaped}\"; filename*=UTF-8''{quote(cleaned, safe='')}"
-def validate_image_file(file: Optional[bytes], user: int) -> bool:
+def validate_image_file(file: Optional[bytes], user: int, *, formats: tuple[str, ...]) -> bool:
"""
Django validates file content type by reading "magic bytes" from the start of the file.
It doesn't then check that file really is the type it claims to be.
@@ -94,12 +74,13 @@ def validate_image_file(file: Optional[bytes], user: int) -> bool:
We would store that and then serve it back to a dashboard. ☠️
Here we check that the file is actually a valid image file by opening and transposing it.
+ `formats` names the Pillow formats the caller accepts; bytes in any other format fail the check.
"""
if file is None:
return False
try:
- im = Image.open(BytesIO(file))
+ im = Image.open(BytesIO(file), formats=formats)
ImageOps.mirror(im)
im.close()
return True
@@ -113,33 +94,6 @@ def validate_image_file(file: Optional[bytes], user: int) -> bool:
return False
-# Guards against a decompression bomb: a small, highly-compressed file that decodes to an
-# enormous bitmap. Checked from the header, before Pillow decodes the full image into memory.
-_MAX_IMAGE_PIXELS = 50_000_000
-
-
-def sniff_image_content_type(data: Optional[bytes]) -> Optional[str]:
- """Determine an image's real content type from its bytes — never trust a caller's claim.
-
- Accepts only what `download` will serve inline: storing a format that always comes back
- as an attachment gives the caller a URL no image tag can render. Returns None for
- anything else, so the caller rejects rather than stores a type that misdescribes the
- bytes.
- """
- if not data:
- return None
- try:
- with Image.open(BytesIO(data)) as image:
- width, height = image.size
- if width * height > _MAX_IMAGE_PIXELS:
- return None
- image.load()
- content_type = Image.MIME.get(image.format or "")
- except Exception:
- return None
- return content_type if content_type in _INLINE_SAFE_CONTENT_TYPES else None
-
-
def _try_delete_object(location: Optional[str]) -> bool:
"""Delete a staged object, reporting failure instead of raising it.
@@ -214,7 +168,7 @@ def download(request, *args, **kwargs) -> HttpResponse:
"Cache-Control": "public, max-age=315360000, immutable",
}
- if _is_inline_safe_content_type(instance.content_type):
+ if is_inline_safe_content_type(instance.content_type):
response_content_type = instance.content_type
else:
response_content_type = "application/octet-stream"
diff --git a/posthog/models/uploaded_media.py b/posthog/models/uploaded_media.py
index e361692a36e7..be9ad6bd160e 100644
--- a/posthog/models/uploaded_media.py
+++ b/posthog/models/uploaded_media.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from io import BytesIO
from typing import Optional
from django.conf import settings
@@ -6,6 +7,7 @@ from django.db import models
from django.db.models import Q
import structlog
+from PIL import Image
from posthog.exceptions_capture import capture_exception
from posthog.models.team import Team
@@ -39,6 +41,63 @@ PRIVATE_MEDIA_PURPOSES = frozenset({MEDIA_PURPOSE_DESKTOP_FEEDBACK})
# cost of waiting is one unlisted row and its staged bytes.
ABANDONED_UPLOAD_AGE = timedelta(hours=24)
+# Content types safe to render inline in a browser when served from the
+# unauthenticated /uploaded_media endpoint. Anything outside this set is
+# served as a download with a generic content type so stored HTML/SVG/etc.
+# cannot execute script in the application origin.
+_INLINE_SAFE_CONTENT_TYPES = frozenset(
+ {
+ "image/png",
+ "image/jpeg",
+ "image/jpg",
+ "image/gif",
+ "image/webp",
+ "image/avif",
+ "image/bmp",
+ }
+)
+
+# The Pillow formats behind the content types above. Image.open without formats= tries every
+# format Pillow can parse, so pass this to decode only the formats that download() serves inline.
+INLINE_SAFE_IMAGE_FORMATS = ("PNG", "JPEG", "GIF", "WEBP", "AVIF", "BMP")
+
+
+def _normalize_content_type(value: str | None) -> str:
+ if not value:
+ return ""
+ return value.split(";", 1)[0].strip().lower()
+
+
+def is_inline_safe_content_type(content_type: str | None) -> bool:
+ return _normalize_content_type(content_type) in _INLINE_SAFE_CONTENT_TYPES
+
+
+# Guards against a decompression bomb: a small, highly-compressed file that decodes to an
+# enormous bitmap. Checked from the header, before Pillow decodes the full image into memory.
+_MAX_IMAGE_PIXELS = 50_000_000
+
+
+def sniff_image_content_type(data: Optional[bytes]) -> Optional[str]:
+ """Determine an image's real content type from its bytes — never trust a caller's claim.
+
+ Accepts only what `download` will serve inline: storing a format that always comes back
+ as an attachment gives the caller a URL no image tag can render. Returns None for
+ anything else, so the caller rejects rather than stores a type that misdescribes the
+ bytes.
+ """
+ if not data:
+ return None
+ try:
+ with Image.open(BytesIO(data), formats=INLINE_SAFE_IMAGE_FORMATS) as image:
+ width, height = image.size
+ if width * height > _MAX_IMAGE_PIXELS:
+ return None
+ image.load()
+ content_type = Image.MIME.get(image.format or "")
+ except Exception:
+ return None
+ return content_type if content_type in _INLINE_SAFE_CONTENT_TYPES else None
+
class UploadedMedia(UUIDTModel, RootTeamMixin):
team = models.ForeignKey("Team", on_delete=models.CASCADE)
diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.py
index 36bcfcb924f9..59b0892403fa 100644
--- a/products/conversations/backend/api/tests/test_email_endpoints.py
+++ b/products/conversations/backend/api/tests/test_email_endpoints.py
@@ -15,6 +15,7 @@ from PIL import Image
from posthog.models.comment import Comment
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team import Team
+from posthog.models.uploaded_media import UploadedMedia
from posthog.models.user import User
from products.conversations.backend.api.tests.mailgun_signing import MailgunWebhookTestMixin, post_mailgun
@@ -44,6 +45,12 @@ def _make_png_bytes() -> bytes:
return buf.getvalue()
+def _make_image_bytes(image_format: str) -> bytes:
+ buf = BytesIO()
+ Image.new("RGB", (1, 1), color="red").save(buf, format=image_format)
+ return buf.getvalue()
+
+
class TestEmailConnectDomainCaseInsensitivity(BaseTest):
def setUp(self):
super().setUp()
@@ -2686,9 +2693,17 @@ class TestEmailInboundAttachments(MailgunWebhookTestMixin, BaseTest):
"stripped-text": "See attached",
}
+ @parameterized.expand(
+ [
+ ("png", _make_png_bytes(), "image/png"),
+ ("jpeg_labelled_png", _make_image_bytes("JPEG"), "image/jpeg"),
+ ]
+ )
@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")
- def test_inbound_with_image_attachment(self, mock_storage: MagicMock):
- attachment = SimpleUploadedFile("photo.png", _make_png_bytes(), content_type="image/png")
+ def test_inbound_with_image_attachment(
+ self, _name: str, content: bytes, expected_content_type: str, mock_storage: MagicMock
+ ):
+ attachment = SimpleUploadedFile("photo.png", content, content_type="image/png")
data = self._base_post_data("<[email protected]>")
with self.settings(OBJECT_STORAGE_ENABLED=True):
@@ -2708,7 +2723,8 @@ class TestEmailInboundAttachments(MailgunWebhookTestMixin, BaseTest):
assert image_nodes[0]["attrs"]["alt"] == "photo.png"
assert comment.item_context["email_attachments"] is not None
assert len(comment.item_context["email_attachments"]) == 1
- assert comment.item_context["email_attachments"][0]["content_type"] == "image/png"
+ assert comment.item_context["email_attachments"][0]["content_type"] == expected_content_type
+ assert UploadedMedia.objects.get(team=self.team).content_type == expected_content_type
@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")
def test_inbound_with_non_image_attachment(self, mock_storage: MagicMock):
@@ -2789,9 +2805,15 @@ class TestEmailInboundAttachments(MailgunWebhookTestMixin, BaseTest):
assert comment.content == "See attached"
assert comment.rich_content is None
+ @parameterized.expand(
+ [
+ ("html", b"<html>not an image</html>"),
+ ("tiff", _make_image_bytes("TIFF")),
+ ]
+ )
@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")
- def test_inbound_invalid_image_is_rejected(self, mock_storage: MagicMock):
- fake_image = SimpleUploadedFile("evil.png", b"<html>not an image</html>", content_type="image/png")
+ def test_inbound_invalid_image_is_rejected(self, _name: str, content: bytes, mock_storage: MagicMock):
+ fake_image = SimpleUploadedFile("evil.png", content, content_type="image/png")
data = self._base_post_data("<[email protected]>")
with self.settings(OBJECT_STORAGE_ENABLED=True):
diff --git a/products/conversations/backend/api/tests/test_teams_image_sync.py b/products/conversations/backend/api/tests/test_teams_image_sync.py
index 6cf44d99209f..cc6b5ffb2db9 100644
--- a/products/conversations/backend/api/tests/test_teams_image_sync.py
+++ b/products/conversations/backend/api/tests/test_teams_image_sync.py
@@ -2,6 +2,8 @@ from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
+from parameterized import parameterized
+
from products.conversations.backend.teams_attachments import (
_download_image,
extract_teams_bot_attachments,
@@ -57,27 +59,41 @@ class TestTeamsImageIngest(SimpleTestCase):
assert images == []
mock_download.assert_not_called()
+ @parameterized.expand(
+ [
+ ("pdf", "application/pdf", "invoice.pdf", b"%PDF-1.4 fake content"),
+ ("heic", "image/heic", "photo.heic", b"\x00\x00\x00\x18ftypheic fake content"),
+ ]
+ )
@patch("products.conversations.backend.teams_attachments.save_file_to_uploaded_media")
@patch("products.conversations.backend.teams_attachments._download_image")
- def test_extract_bot_attachments_keeps_non_image_file(self, mock_download: MagicMock, mock_save: MagicMock) -> None:
- mock_download.return_value = b"%PDF-1.4 fake content"
- mock_save.return_value = "https://app.posthog.com/uploaded_media/pdf"
+ def test_extract_bot_attachments_keeps_file_served_as_download(
+ self,
+ _name: str,
+ content_type: str,
+ file_name: str,
+ content: bytes,
+ mock_download: MagicMock,
+ mock_save: MagicMock,
+ ) -> None:
+ mock_download.return_value = content
+ mock_save.return_value = "https://app.posthog.com/uploaded_media/file"
fake_team = MagicMock()
fake_team.id = 1
attachments = [
{
- "contentType": "application/pdf",
- "contentUrl": "https://smba.trafficmanager.net/files/invoice.pdf",
- "name": "invoice.pdf",
+ "contentType": content_type,
+ "contentUrl": f"https://smba.trafficmanager.net/files/{file_name}",
+ "name": file_name,
}
]
results = extract_teams_bot_attachments(attachments, fake_team, "bot-token")
assert len(results) == 1
- assert results[0]["mimetype"] == "application/pdf"
- assert results[0]["name"] == "invoice.pdf"
+ assert results[0]["mimetype"] == content_type
+ assert results[0]["name"] == file_name
# Non-image bytes are stored without image validation
assert mock_save.call_args.kwargs["validate_images"] is False
diff --git a/products/conversations/backend/services/attachments.py b/products/conversations/backend/services/attachments.py
index 4f7e5a93281b..c959307e2bac 100644
--- a/products/conversations/backend/services/attachments.py
+++ b/products/conversations/backend/services/attachments.py
@@ -1,16 +1,19 @@
"""Shared attachment helpers for conversations channels (email, Slack, etc.)."""
import re
-from io import BytesIO
from typing import Any
from django.conf import settings
import structlog
-from PIL import Image
from posthog.models.team import Team
-from posthog.models.uploaded_media import UploadedMedia, save_content_to_object_storage
+from posthog.models.uploaded_media import (
+ UploadedMedia,
+ is_inline_safe_content_type,
+ save_content_to_object_storage,
+ sniff_image_content_type,
+)
logger = structlog.get_logger(__name__)
@@ -37,18 +40,18 @@ def sanitize_attachment_filename(name: str | None) -> str:
return name or "attachment"
-def is_valid_image(content: bytes) -> bool:
- """Verify bytes are a real image (prevents serving disguised malicious content).
+def resolve_attachment_content_type(content: bytes, declared_content_type: str) -> str | None:
+ """Return the content type to store for an attachment, or None when its bytes are not a valid image.
- Uses the same PIL open + transpose check as the frontend upload API.
+ The media endpoint serves only inline-safe types inline, so only those get a decode, which
+ prevents serving disguised content as an image. For them the stored type comes from the
+ decoded bytes, not from the sender's claim. The endpoint serves every other type, including
+ image types such as TIFF or HEIC, as an opaque download, so those keep their declared type
+ and are stored without a decode.
"""
- try:
- image = Image.open(BytesIO(content))
- image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
- image.close()
- return True
- except Exception:
- return False
+ if not is_inline_safe_content_type(declared_content_type):
+ return declared_content_type
+ return sniff_image_content_type(content)
def save_file_to_uploaded_media(
@@ -62,16 +65,19 @@ def save_file_to_uploaded_media(
"""Persist a file to object storage via UploadedMedia.
Returns the absolute URL on success, None on failure.
- For image content types, validates the bytes are a real image unless
- validate_images is False.
+ Unless validate_images is False, stores the type that resolve_attachment_content_type
+ returns, and rejects bytes that it finds invalid.
"""
if not settings.OBJECT_STORAGE_ENABLED:
logger.warning("conversations_attachment_no_object_storage", team_id=team.id)
return None
- if validate_images and content_type.startswith("image/") and not is_valid_image(content):
- logger.warning("conversations_attachment_invalid_image", team_id=team.id, file_name=file_name)
- return None
+ if validate_images:
+ resolved_content_type = resolve_attachment_content_type(content, content_type)
+ if resolved_content_type is None:
+ logger.warning("conversations_attachment_invalid_image", team_id=team.id, file_name=file_name)
+ return None
+ content_type = resolved_content_type
uploaded_media = UploadedMedia.objects.create(
team=team,
diff --git a/products/conversations/backend/services/mailgun_events.py b/products/conversations/backend/services/mailgun_events.py
index 396fbaea7e5c..d2e02a9ebcd0 100644
--- a/products/conversations/backend/services/mailgun_events.py
+++ b/products/conversations/backend/services/mailgun_events.py
@@ -48,6 +48,7 @@ from products.conversations.backend.models import (
)
from products.conversations.backend.models.ticket import Ticket
from products.conversations.backend.services.attachments import (
+ resolve_attachment_content_type,
sanitize_attachment_filename,
save_file_to_uploaded_media,
)
@@ -194,13 +195,17 @@ def _extract_attachments(uploaded_files: tuple[UploadedFile, ...], team: Team) -
file_bytes = uploaded_file.read()
safe_name = sanitize_attachment_filename(uploaded_file.name)
- url = save_file_to_uploaded_media(team, safe_name, uploaded_file.content_type or "", file_bytes)
+ content_type = resolve_attachment_content_type(file_bytes, uploaded_file.content_type or "")
+ if content_type is None:
+ logger.warning("email_inbound_attachment_invalid_image", team_id=team.id, file_name=safe_name)
+ continue
+ url = save_file_to_uploaded_media(team, safe_name, content_type, file_bytes, validate_images=False)
if url:
attachments.append(
{
"url": url,
"name": safe_name,
- "content_type": uploaded_file.content_type or "",
+ "content_type": content_type,
"size": uploaded_file.size,
}
)
diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.py
index 347cbedca01c..622303c1d4bc 100644
--- a/products/conversations/backend/slack.py
+++ b/products/conversations/backend/slack.py
@@ -53,7 +53,7 @@ from .services.attachments import (
CONVERSATIONS_MAX_IMAGE_BYTES,
MAX_ATTACHMENTS_PER_MESSAGE,
build_content_with_images,
- is_valid_image,
+ resolve_attachment_content_type,
sanitize_attachment_filename,
save_file_to_uploaded_media,
)
@@ -368,22 +368,23 @@ def _rehost_slack_file(f: dict, team: Team, bot_token: str | None) -> dict | Non
logger.warning("🖼️ slack_file_download_rejected", file_id=file_id, source_url=source_url)
return None
- # Only images get byte-level validation; other types are stored as-is and
- # served as opaque downloads by the media endpoint.
- if is_image and not is_valid_image(file_bytes):
+ # Only types the media endpoint serves inline get byte-level validation; other
+ # types are stored as-is and served as opaque downloads by the media endpoint.
+ content_type = resolve_attachment_content_type(file_bytes, mimetype)
+ if content_type is None:
logger.warning("🖼️ slack_file_invalid_image_content", file_id=file_id)
return None
safe_name = sanitize_attachment_filename(f.get("name"))
- stored_url = save_file_to_uploaded_media(team, safe_name, mimetype, file_bytes, validate_images=False)
+ stored_url = save_file_to_uploaded_media(team, safe_name, content_type, file_bytes, validate_images=False)
if not stored_url:
logger.warning("🖼️ slack_file_copy_save_failed", file_id=file_id)
return None
- attachment = {
+ attachment: dict[str, Any] = {
"url": stored_url,
"name": safe_name,
- "mimetype": mimetype,
+ "mimetype": content_type,
}
if is_image:
attachment["thumb"] = f.get("thumb_360") or f.get("thumb_160")
diff --git a/products/conversations/backend/teams_attachments.py b/products/conversations/backend/teams_attachments.py
index 69a808ffa54e..31595582b14b 100644
--- a/products/conversations/backend/teams_attachments.py
+++ b/products/conversations/backend/teams_attachments.py
@@ -17,7 +17,7 @@ from posthog.models.team.team import Team
from .services.attachments import (
CONVERSATIONS_MAX_IMAGE_BYTES,
MAX_ATTACHMENTS_PER_MESSAGE,
- is_valid_image,
+ resolve_attachment_content_type,
sanitize_attachment_filename,
save_file_to_uploaded_media,
)
@@ -99,19 +99,20 @@ def _download_image(url: str, token: str) -> bytes | None:
def _save_attachment(team: Team, file_bytes: bytes, name: str, mimetype: str) -> dict[str, Any] | None:
"""Validate and persist attachment bytes, returning the attachment dict or None.
- Only ``image/*`` content is byte-validated; other types are stored as-is and
- served as opaque downloads by the media endpoint.
+ Only types the media endpoint serves inline are byte-validated; other types are
+ stored as-is and served as opaque downloads by the media endpoint.
"""
- if mimetype.startswith("image/") and not is_valid_image(file_bytes):
+ content_type = resolve_attachment_content_type(file_bytes, mimetype)
+ if content_type is None:
logger.warning("teams_image_invalid_content", name=name)
return None
safe_name = sanitize_attachment_filename(name)
- stored_url = save_file_to_uploaded_media(team, safe_name, mimetype, file_bytes, validate_images=False)
+ stored_url = save_file_to_uploaded_media(team, safe_name, content_type, file_bytes, validate_images=False)
if not stored_url:
return None
- return {"url": stored_url, "name": safe_name, "mimetype": mimetype}
+ return {"url": stored_url, "name": safe_name, "mimetype": content_type}
def extract_teams_bot_attachments(
diff --git a/products/visual_review/backend/diff.py b/products/visual_review/backend/diff.py
index b2055ff5e0a9..38284122ed8f 100644
--- a/products/visual_review/backend/diff.py
+++ b/products/visual_review/backend/diff.py
@@ -16,7 +16,7 @@ from pixelhog import ClustersResult, Comparison, RowAlignment
from posthog.dataclasses import frozen
from .diff_metadata import ClusterSummary, DiffCluster, RowShift, ShiftBand
-from .facade.contracts import SHIFT_ABSORB_MAX_ROWS
+from .facade.contracts import SHIFT_ABSORB_MAX_ROWS, SNAPSHOT_IMAGE_FORMATS
# Aligned-bbox merge tunables passed through to pixelhog's clusters().
# Catches the "list shifted vertically" pattern where every row of a
@@ -117,7 +117,7 @@ def _relocated_rows(baseline_bytes: bytes, current_bytes: bytes, alignment: RowA
return False
return row(image, start - 1) != band[0] and row(image, end) != band[-1]
- baseline = Image.open(io.BytesIO(baseline_bytes)).convert("RGBA")
+ baseline = Image.open(io.BytesIO(baseline_bytes), formats=SNAPSHOT_IMAGE_FORMATS).convert("RGBA")
# Row pixels -> whether that deleted band stood out where it was.
deleted_rows: dict[bytes, bool] = {}
for seg in deleted:
@@ -128,7 +128,7 @@ def _relocated_rows(baseline_bytes: bytes, current_bytes: bytes, alignment: RowA
deleted_rows[pixels] = deleted_rows.get(pixels, False) or stood_out
del baseline
- current = Image.open(io.BytesIO(current_bytes)).convert("RGBA")
+ current = Image.open(io.BytesIO(current_bytes), formats=SNAPSHOT_IMAGE_FORMATS).convert("RGBA")
relocated = 0
for seg in inserted:
start, end = seg.current_start, seg.current_start + seg.len
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index eb8124230c7b..2dc92773c2c7 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -52,6 +52,10 @@ SSIM_DISSIMILARITY_THRESHOLD = 0.01 # 1% structural difference
# somebody should look at it.
SHIFT_ABSORB_MAX_ROWS = 2
+# The CLI uploads only .png files, so the backend decodes snapshots as PNG and nothing else.
+# Image.open without formats= tries every format Pillow can parse.
+SNAPSHOT_IMAGE_FORMATS = ("PNG",)
+
# --- Input DTOs ---
diff --git a/products/visual_review/backend/hashing.py b/products/visual_review/backend/hashing.py
index c83ce5a07530..27dfbde1e2a8 100644
--- a/products/visual_review/backend/hashing.py
+++ b/products/visual_review/backend/hashing.py
@@ -21,6 +21,8 @@ import io
from blake3 import blake3
from PIL import Image
+from .facade.contracts import SNAPSHOT_IMAGE_FORMATS
+
# Cap decoded pixel count to bound memory. A 7000×7000 RGBA image is ~196 MB —
# plenty for screenshots, well under Pillow's default DecompressionBombWarning.
# Pillow raises DecompressionBombError above this (instead of just warning).
@@ -40,6 +42,6 @@ def hash_image(png_bytes: bytes) -> str:
"""Decode PNG to RGBA pixels and return the BLAKE3 hex digest."""
if len(png_bytes) > _MAX_PNG_BYTES:
raise ImageTooLargeError(f"PNG is {len(png_bytes)} bytes, exceeds {_MAX_PNG_BYTES} limit")
- img = Image.open(io.BytesIO(png_bytes))
+ img = Image.open(io.BytesIO(png_bytes), formats=SNAPSHOT_IMAGE_FORMATS)
img.load()
return blake3(img.convert("RGBA").tobytes()).hexdigest()
diff --git a/products/visual_review/backend/tests/test_hashing.py b/products/visual_review/backend/tests/test_hashing.py
index 29a6870595ba..47cf818eea74 100644
--- a/products/visual_review/backend/tests/test_hashing.py
+++ b/products/visual_review/backend/tests/test_hashing.py
@@ -5,7 +5,7 @@ from pathlib import Path
import pytest
-from PIL import Image
+from PIL import Image, UnidentifiedImageError
from products.visual_review.backend.hashing import ImageTooLargeError, hash_image
@@ -35,6 +35,13 @@ class TestHashImage:
assert hash_image(buf.getvalue()) == hash_image(_png_bytes((10, 20, 30, 255)))
+ @pytest.mark.parametrize("image_format", ["JPEG", "TIFF"])
+ def test_rejects_formats_other_than_png(self, image_format: str):
+ buf = io.BytesIO()
+ Image.new("RGB", (4, 4), (10, 20, 30)).save(buf, format=image_format)
+ with pytest.raises(UnidentifiedImageError):
+ hash_image(buf.getvalue())
+
def test_rejects_payload_over_byte_limit(self):
with pytest.raises(ImageTooLargeError):
hash_image(b"\x89PNG" + b"\x00" * (65 * 1024 * 1024))
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
index a674a16c2839..5a4c02d05a23 100644
--- a/products/web_analytics/backend/api/heatmaps_api.py
+++ b/products/web_analytics/backend/api/heatmaps_api.py
@@ -70,6 +70,7 @@ from products.access_control.backend.presentation.access_control import (
from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.api.heatmaps_utils import (
DEFAULT_TARGET_WIDTHS,
+ HEATMAP_SNAPSHOT_IMAGE_FORMATS,
MAX_TARGET_WIDTHS,
PREWARM_PREVIEW_WIDTH,
PREWARM_TTL,
@@ -152,7 +153,7 @@ def _requests_event_filter(request: request.Request) -> bool:
def _reject_oversized_capture_image(image_bytes: bytes) -> None:
try:
- with Image.open(BytesIO(image_bytes)) as im:
+ with Image.open(BytesIO(image_bytes), formats=HEATMAP_SNAPSHOT_IMAGE_FORMATS) as im:
width, height = im.size
except Exception:
raise ValidationError(code="invalid_image", detail="Uploaded media must be a valid image")
@@ -1426,7 +1427,9 @@ class SavedHeatmapRequestSerializer(serializers.ModelSerializer):
class SavedHeatmapCaptureRequestSerializer(serializers.Serializer):
- image = serializers.ImageField(
+ # FileField, not ImageField: ImageField opens the upload with every Pillow format before
+ # capture() checks it against HEATMAP_SNAPSHOT_IMAGE_FORMATS.
+ image = serializers.FileField(
required=False,
help_text="Single screenshot of the page, captured client-side by the toolbar (JPEG or PNG). Max 20MB. "
"Pair with 'width'. Use 'images'/'widths' instead to save several viewport widths on one heatmap.",
@@ -1438,7 +1441,7 @@ class SavedHeatmapCaptureRequestSerializer(serializers.Serializer):
help_text="Viewport width (CSS pixels) the single 'image' was captured at.",
)
images = serializers.ListField(
- child=serializers.ImageField(),
+ child=serializers.FileField(),
required=False,
allow_empty=False,
max_length=MAX_TARGET_WIDTHS,
@@ -1794,7 +1797,7 @@ class SavedHeatmapViewSet(
image_file.seek(0)
image_bytes = image_file.read()
_reject_oversized_capture_image(image_bytes)
- if not validate_image_file(image_bytes, user=user_id):
+ if not validate_image_file(image_bytes, user=user_id, formats=HEATMAP_SNAPSHOT_IMAGE_FORMATS):
raise ValidationError(code="invalid_image", detail="Uploaded media must be a valid image")
snapshot_bytes.append((width, image_bytes))
diff --git a/products/web_analytics/backend/api/heatmaps_utils.py b/products/web_analytics/backend/api/heatmaps_utils.py
index fe3e800e84ec..9e5f34c9e9bb 100644
--- a/products/web_analytics/backend/api/heatmaps_utils.py
+++ b/products/web_analytics/backend/api/heatmaps_utils.py
@@ -10,6 +10,10 @@ MAX_TARGET_WIDTHS = 16
PREWARM_PREVIEW_WIDTH = 1024
PREWARM_TTL = timedelta(minutes=15)
+# The Pillow formats a stored snapshot can hold: Browserless renders JPEG, and the toolbar capture
+# endpoint accepts JPEG or PNG. Image.open without formats= tries every format Pillow can parse.
+HEATMAP_SNAPSHOT_IMAGE_FORMATS = ("JPEG", "PNG")
+
def heatmaps_flag_enabled(flag: str, distinct_id: str, *, team_id: int, organization_id: str) -> bool:
"""Evaluate a flag with the org/project group context, failing closed when it can't be read."""
diff --git a/products/web_analytics/backend/heatmap_screenshot_grounding.py b/products/web_analytics/backend/heatmap_screenshot_grounding.py
index 81f839cce667..d7090e04786c 100644
--- a/products/web_analytics/backend/heatmap_screenshot_grounding.py
+++ b/products/web_analytics/backend/heatmap_screenshot_grounding.py
@@ -22,6 +22,7 @@ from PIL import Image, ImageDraw, ImageFont
from posthog.sync import database_sync_to_async
+from products.web_analytics.backend.api.heatmaps_utils import HEATMAP_SNAPSHOT_IMAGE_FORMATS
from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
from ee.hogai.llm import MaxChatAnthropic
@@ -118,7 +119,7 @@ def _build_markers(heatmap_data: Mapping[str, object]) -> list[_Marker]:
def _annotate(image_bytes: bytes, markers: list[_Marker]) -> bytes:
"""Draw numbered dots at each marker (rage = red, click = blue), then downscale. Coordinate mapping mirrors
the frontend heatmap overlay: pixel_x = rel_x * width, pixel_y = pointer_y (already document pixels)."""
- img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
+ img = Image.open(io.BytesIO(image_bytes), formats=HEATMAP_SNAPSHOT_IMAGE_FORMATS).convert("RGB")
width, height = img.size
draw = ImageDraw.Draw(img)
radius = max(16, width // 55)
diff --git a/products/web_analytics/backend/test/test_heatmap_screenshot_grounding.py b/products/web_analytics/backend/test/test_heatmap_screenshot_grounding.py
index b8c4cf446032..e9136de3ce1f 100644
--- a/products/web_analytics/backend/test/test_heatmap_screenshot_grounding.py
+++ b/products/web_analytics/backend/test/test_heatmap_screenshot_grounding.py
@@ -7,7 +7,7 @@ from django.test import SimpleTestCase
from asgiref.sync import sync_to_async
from parameterized import parameterized
-from PIL import Image
+from PIL import Image, UnidentifiedImageError
from products.web_analytics.backend.heatmap_screenshot_grounding import (
_annotate,
@@ -50,6 +50,13 @@ class TestMarkersAndAnnotation(SimpleTestCase):
out = _annotate(_jpeg(200, 300), markers)
assert Image.open(io.BytesIO(out)).format == "JPEG"
+ def test_annotate_refuses_a_format_that_snapshots_never_hold(self):
+ buf = io.BytesIO()
+ Image.new("RGB", (200, 300), (240, 240, 240)).save(buf, format="TIFF")
+ markers = _build_markers(_heatmap_data())
+ with self.assertRaises(UnidentifiedImageError):
+ _annotate(buf.getvalue(), markers)
+
class TestFetchScreenshotBytes(APIBaseTest):
def _saved(self, **overrides) -> SavedHeatmap:
diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.py
index 353473db39da..31c422451157 100644
--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py
+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py
@@ -523,6 +523,12 @@ def _jpeg_bytes(width: int = 12, height: int = 12) -> bytes:
return buf.getvalue()
+def _tiff_bytes() -> bytes:
+ buf = BytesIO()
+ Image.new("RGB", (12, 12), (200, 30, 30)).save(buf, format="TIFF")
+ return buf.getvalue()
+
+
@patch("products.web_analytics.backend.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay")
class TestHeatmapToolbarCapture(APIBaseTest):
def setUp(self) -> None:
@@ -587,6 +593,7 @@ class TestHeatmapToolbarCapture(APIBaseTest):
[
("wildcard_url", "https://app.example.com/*", _jpeg_bytes()),
("not_an_image", "https://app.example.com/x", b"<html>not a jpeg</html>"),
+ ("unsupported_format", "https://app.example.com/x", _tiff_bytes()),
]
)
def test_capture_rejects_invalid_input(self, _mock_task: MagicMock, _name: str, url: str, content: bytes) -> None: