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(conversations): preserve filename on uploaded media downloads (#70778)

Alex Vcbaf0fc2c472
diff --git a/posthog/api/test/test_uploaded_media.py b/posthog/api/test/test_uploaded_media.py
index c3f372f904be..b802cd0a99bf 100644
--- a/posthog/api/test/test_uploaded_media.py
+++ b/posthog/api/test/test_uploaded_media.py
@@ -190,6 +190,39 @@ class TestMediaAPI(APIBaseTest):
assert download_response.headers["Content-Type"].startswith("application/octet-stream")
assert download_response.headers.get("Content-Disposition", "").startswith("attachment")
+ @parameterized.expand(
+ [
+ ("plain", "example.docx", 'attachment; filename="example.docx"'),
+ ("quotes", 'a"b.docx', 'attachment; filename="a\\"b.docx"'),
+ ("crlf_injection", "evil.docx\r\nSet-Cookie: x=1", 'attachment; filename="evil.docxSet-Cookie: x=1"'),
+ ("unicode", "réport.docx", "attachment; filename=\"rport.docx\"; filename*=UTF-8''r%C3%A9port.docx"),
+ ]
+ )
+ def test_download_preserves_filename(self, _name: str, file_name: str, expected_disposition: str) -> 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:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/uploaded_media",
+ {"image": image},
+ format="multipart",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ media_id = response.json()["id"]
+
+ UploadedMedia.objects.filter(id=media_id).update(
+ content_type="application/octet-stream", file_name=file_name
+ )
+
+ self.client.logout()
+ with patch(
+ "posthog.api.uploaded_media.object_storage.read_bytes",
+ return_value=b"bytes",
+ ):
+ download_response = self.client.get(f"/uploaded_media/{media_id}")
+
+ assert download_response.status_code == status.HTTP_200_OK
+ assert download_response.headers["Content-Disposition"] == expected_disposition
+
def test_rejects_upload_when_object_storage_is_unavailable(self) -> None:
with override_settings(OBJECT_STORAGE_ENABLED=False):
fake_big_file = SimpleUploadedFile(name="test_image.jpg", content=b"", content_type="image/jpeg")
diff --git a/posthog/api/uploaded_media.py b/posthog/api/uploaded_media.py
index b6a1735a123f..9f618e08c918 100644
--- a/posthog/api/uploaded_media.py
+++ b/posthog/api/uploaded_media.py
@@ -1,7 +1,9 @@
from io import BytesIO
from typing import Optional
+from urllib.parse import quote
from django.http import HttpResponse
+from django.utils.http import content_disposition_header
from django.views.decorators.csrf import csrf_exempt
import structlog
@@ -51,6 +53,33 @@ 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.
+
+ Without an explicit filename the browser falls back to the URL's last path
+ segment — here the media UUID — so downloads lose their name and extension.
+
+ file_name is attacker-influenced (inbound email/Slack attachments), so strip
+ control characters (defends against CR/LF header injection) before encoding.
+ Non-ASCII names get a quote-escaped ASCII ``filename`` fallback for legacy
+ browsers alongside the RFC 5987 ``filename*`` parameter.
+ """
+ if not file_name:
+ return "attachment"
+
+ cleaned = "".join(ch for ch in file_name if ch.isprintable()).strip()
+ if not cleaned:
+ return "attachment"
+
+ try:
+ cleaned.encode("ascii")
+ return content_disposition_header(as_attachment=True, filename=cleaned) or "attachment"
+ except UnicodeEncodeError:
+ ascii_fallback = cleaned.encode("ascii", "ignore").decode().strip() or "download"
+ escaped = ascii_fallback.replace("\\", "\\\\").replace('"', '\\"')
+ return f"attachment; filename=\"{escaped}\"; filename*=UTF-8''{quote(cleaned, safe='')}"
+
+
def validate_image_file(file: Optional[bytes], user: int) -> bool:
"""
Django validates file content type by reading "magic bytes" from the start of the file.
@@ -115,7 +144,7 @@ def download(request, *args, **kwargs) -> HttpResponse:
response_content_type = instance.content_type
else:
response_content_type = "application/octet-stream"
- response_headers["Content-Disposition"] = "attachment"
+ response_headers["Content-Disposition"] = _attachment_disposition(instance.file_name)
return HttpResponse(
file_bytes,