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(uploaded-media): return 404 when object-storage key is missing (#71050)

posthog[bot]c63d252c17ed
diff --git a/posthog/api/test/test_uploaded_media.py b/posthog/api/test/test_uploaded_media.py
index b802cd0a99bf..b00890e4528a 100644
--- a/posthog/api/test/test_uploaded_media.py
+++ b/posthog/api/test/test_uploaded_media.py
@@ -223,6 +223,26 @@ class TestMediaAPI(APIBaseTest):
assert download_response.status_code == status.HTTP_200_OK
assert download_response.headers["Content-Disposition"] == expected_disposition
+ def test_download_returns_404_when_object_storage_key_is_missing(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:
+ 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"]
+
+ self.client.logout()
+ with patch(
+ "posthog.api.uploaded_media.object_storage.read_bytes",
+ return_value=None,
+ ):
+ download_response = self.client.get(f"/uploaded_media/{media_id}")
+
+ assert download_response.status_code == status.HTTP_404_NOT_FOUND
+
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 9f618e08c918..e76ab8d5a87b 100644
--- a/posthog/api/uploaded_media.py
+++ b/posthog/api/uploaded_media.py
@@ -123,7 +123,11 @@ def download(request, *args, **kwargs) -> HttpResponse:
if instance.media_location is None:
return HttpResponse(status=404)
- file_bytes = object_storage.read_bytes(instance.media_location)
+ file_bytes = object_storage.read_bytes(instance.media_location, missing_ok=True)
+ if file_bytes is None:
+ # The DB record exists but the underlying object-storage key is gone, so
+ # there's nothing to serve — return a clean 404 rather than a 500.
+ return HttpResponse(status=404)
statsd.incr(
"uploaded_media.served",