: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(uploaded-media): let staff stop serving a single image (#126134)
posthog[bot]82372abbd258
diff --git a/posthog/admin/admins/uploaded_media_admin.py b/posthog/admin/admins/uploaded_media_admin.pynew file mode 100644index 000000000000..7e421339e3e4--- /dev/null+++ b/posthog/admin/admins/uploaded_media_admin.py@@ -0,0 +1,163 @@+from django.contrib import admin, messages+from django.db.models import QuerySet+from django.http import HttpRequest+from django.urls import reverse+from django.utils.html import format_html++import structlog++from posthog.admin.paginators.no_count_paginator import NoCountPaginator+from posthog.models import UploadedMedia++logger = structlog.get_logger(__name__)++# Takedowns cover a handful of images. The cap stops a "select all" from changing every row in the+# table in one request.+MAX_IMAGES_PER_ACTION = 50++[email protected](UploadedMedia)+class UploadedMediaAdmin(admin.ModelAdmin):+ list_display = (+ "id",+ "file_name",+ "team_link",+ "purpose",+ "created_at",+ "archived_at",+ "serving_disabled_at",+ "has_stored_file",+ )+ # The table holds every dashboard image and toolbar screenshot, so look rows up by exact id+ # (the UUID in the public URL) or team id, and never count or sort the whole table.+ search_fields = ("id__exact", "team__id__exact")+ show_full_result_count = False+ paginator = NoCountPaginator+ # UUIDT ids sort by creation time, so this ordering uses the primary key index. created_at has none.+ ordering = ("-id",)+ actions = ["disable_serving", "enable_serving", "delete_stored_file"]+ fields = (+ "id",+ "file_name",+ "public_url",+ "team_link",+ "created_by_link",+ "purpose",+ "content_type",+ "size_bytes",+ "media_location",+ "created_at",+ "archived_at",+ "serving_disabled_at",+ )+ readonly_fields = fields++ def has_add_permission(self, request: HttpRequest) -> bool:+ return False++ def has_delete_permission(self, request: HttpRequest, obj: UploadedMedia | None = None) -> bool:+ return False++ def _bounded(self, request: HttpRequest, queryset: QuerySet[UploadedMedia]) -> list[UploadedMedia] | None:+ media = list(queryset[: MAX_IMAGES_PER_ACTION + 1])+ if len(media) > MAX_IMAGES_PER_ACTION:+ self.message_user(+ request,+ f"Select at most {MAX_IMAGES_PER_ACTION} images at a time. Nothing was changed.",+ messages.ERROR,+ )+ return None+ return media++ @admin.display(description="Team")+ def team_link(self, obj: UploadedMedia) -> str:+ url = reverse("admin:posthog_team_change", args=[obj.team_id])+ return format_html('<a href="{}">{}</a>', url, obj.team_id)++ @admin.display(description="Created by")+ def created_by_link(self, obj: UploadedMedia) -> str:+ if not obj.created_by_id:+ return "-"+ url = reverse("admin:posthog_user_change", args=[obj.created_by_id])+ return format_html('<a href="{}">{}</a>', url, obj.created_by_id)++ @admin.display(description="Public URL")+ def public_url(self, obj: UploadedMedia) -> str:+ url = obj.get_absolute_url()+ return format_html('<a href="{}" target="_blank" rel="noopener noreferrer">{}</a>', url, url)++ @admin.display(description="Stored file", boolean=True)+ def has_stored_file(self, obj: UploadedMedia) -> bool:+ return obj.media_location is not None++ def _report_urls_to_purge(self, request: HttpRequest, media: list[UploadedMedia]) -> None:+ # Earlier successful responses carry a years-long immutable cache header, so a CDN in front+ # of the media host keeps serving them until someone purges these URLs there.+ if not media:+ return+ urls = ", ".join(item.get_absolute_url() for item in media)+ self.message_user(+ request,+ f"Purge these URLs in the CDN so cached copies stop loading: {urls}. "+ "Copies already saved by browsers or email clients can't be recalled.",+ messages.WARNING,+ )++ @admin.action(description="Stop serving the selected images at their public URL")+ def disable_serving(self, request: HttpRequest, queryset: QuerySet[UploadedMedia]) -> None:+ media = self._bounded(request, queryset)+ if media is None:+ return+ for item in media:+ if item.stop_serving():+ self.log_change(request, item, "Stopped serving at the public URL.")+ logger.info("uploaded_media.serving_disabled", media_id=str(item.id), team_id=item.team_id)+ self.message_user(request, f"Stopped serving {len(media)} image(s).", messages.SUCCESS)+ self._report_urls_to_purge(request, media)++ @admin.action(description="Serve the selected images at their public URL again")+ def enable_serving(self, request: HttpRequest, queryset: QuerySet[UploadedMedia]) -> None:+ media = self._bounded(request, queryset)+ if media is None:+ return+ changed = [item for item in media if item.serving_disabled_at is not None and item.media_location is not None]+ for item in changed:+ item.serving_disabled_at = None+ item.save(update_fields=["serving_disabled_at"])+ self.log_change(request, item, "Resumed serving at the public URL.")+ logger.info("uploaded_media.serving_enabled", media_id=str(item.id), team_id=item.team_id)+ self.message_user(+ request,+ f"Resumed serving {len(changed)} image(s). Images whose stored file was deleted stay unavailable.",+ messages.SUCCESS if changed else messages.WARNING,+ )++ @admin.action(description="Delete the stored file of the selected images permanently")+ def delete_stored_file(self, request: HttpRequest, queryset: QuerySet[UploadedMedia]) -> None:+ media = self._bounded(request, queryset)+ if media is None:+ return+ # Stopping serving first is the confirmation step, because this delete can't be undone.+ stopped = [item for item in media if item.serving_disabled_at is not None]+ skipped = len(media) - len(stopped)+ deleted = UploadedMedia.delete_stored_files(stopped)+ failed = len(stopped) - len(deleted)+ for item in deleted:+ self.log_change(request, item, "Deleted the stored file permanently.")+ logger.info("uploaded_media.stored_file_deleted", media_id=str(item.id), team_id=item.team_id)++ if deleted:+ self.message_user(request, f"Deleted the stored file of {len(deleted)} image(s).", messages.SUCCESS)+ if skipped:+ self.message_user(+ request,+ f"Skipped {skipped} image(s) that are still served. Stop serving them first, then delete.",+ messages.WARNING,+ )+ if failed:+ self.message_user(+ request,+ f"Could not delete the stored file of {failed} image(s). Their public URL stays off. Try again.",+ messages.ERROR,+ )+ self._report_urls_to_purge(request, deleted)diff --git a/posthog/admin/test_uploaded_media_admin.py b/posthog/admin/test_uploaded_media_admin.pynew file mode 100644index 000000000000..9ed37552eaee--- /dev/null+++ b/posthog/admin/test_uploaded_media_admin.py@@ -0,0 +1,82 @@+from datetime import UTC, datetime++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.contrib.admin.models import CHANGE, LogEntry+from django.urls import reverse++from posthog.models import UploadedMedia++_STOPPED_AT = datetime(2026, 1, 1, tzinfo=UTC)+++class TestUploadedMediaAdminServingActions(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ self.client.force_login(self.user)+ self.changelist = reverse("admin:posthog_uploadedmedia_changelist")+ self.target = UploadedMedia.objects.create(+ team=self.team, file_name="mistake.png", purpose="email", media_location="media_uploads/target"+ )+ self.bystander = UploadedMedia.objects.create(+ team=self.team, file_name="keep.png", purpose="email", media_location="media_uploads/bystander"+ )++ def _run_action(self, action: str, *media: UploadedMedia) -> None:+ response = self.client.post(+ self.changelist, {"action": action, "_selected_action": [str(item.id) for item in media or [self.target]]}+ )+ self.assertEqual(response.status_code, 302)++ def _log_messages(self, media: UploadedMedia) -> list[str]:+ return list(+ LogEntry.objects.filter(object_id=str(media.id), action_flag=CHANGE)+ .order_by("action_time")+ .values_list("change_message", flat=True)+ )++ def test_staff_can_stop_and_resume_serving_one_image_with_an_audit_entry(self) -> None:+ self._run_action("disable_serving")++ assert UploadedMedia.objects.get(id=self.target.id).serving_disabled_at is not None+ assert UploadedMedia.objects.get(id=self.bystander.id).serving_disabled_at is None++ self._run_action("enable_serving")++ assert UploadedMedia.objects.get(id=self.target.id).serving_disabled_at is None+ assert self._log_messages(self.target) == [+ "Stopped serving at the public URL.",+ "Resumed serving at the public URL.",+ ]++ @patch("posthog.admin.admins.uploaded_media_admin.MAX_IMAGES_PER_ACTION", 1)+ def test_action_over_the_selection_cap_changes_nothing(self) -> None:+ self._run_action("disable_serving", self.target, self.bystander)++ assert not UploadedMedia.objects.filter(serving_disabled_at__isnull=False).exists()++ @patch("posthog.models.uploaded_media.object_storage.delete_objects", return_value=[])+ def test_delete_removes_the_bytes_of_stopped_images_only(self, delete_objects) -> None:+ UploadedMedia.objects.filter(id=self.target.id).update(serving_disabled_at=_STOPPED_AT)++ self._run_action("delete_stored_file", self.target, self.bystander)++ self.target.refresh_from_db()+ self.bystander.refresh_from_db()+ delete_objects.assert_called_once_with(["media_uploads/target"])+ assert self.target.media_location is None+ assert self.bystander.media_location == "media_uploads/bystander"+ assert self._log_messages(self.target) == ["Deleted the stored file permanently."]++ @patch("posthog.models.uploaded_media.object_storage.delete_objects", return_value=["media_uploads/target"])+ def test_failed_delete_keeps_the_location_so_staff_can_retry(self, _delete_objects) -> None:+ UploadedMedia.objects.filter(id=self.target.id).update(serving_disabled_at=_STOPPED_AT)++ self._run_action("delete_stored_file")++ self.target.refresh_from_db()+ assert self.target.media_location == "media_uploads/target"+ assert self._log_messages(self.target) == []diff --git a/posthog/api/test/test_uploaded_media.py b/posthog/api/test/test_uploaded_media.pyindex c1ab220f0dd6..b2af210e80d3 100644--- a/posthog/api/test/test_uploaded_media.py+++ b/posthog/api/test/test_uploaded_media.py@@ -470,6 +470,29 @@ class TestMediaLibraryAPI(APIBaseTest):download_response = self.client.get(f"/uploaded_media/{media_id}")assert download_response.status_code == status.HTTP_200_OK+ def test_disabled_serving_stops_the_public_url_and_hides_the_image_from_the_library(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:+ upload_response = self.client.post(+ f"/api/projects/{self.team.id}/uploaded_media",+ {"image": image, "purpose": "email"},+ format="multipart",+ )+ media_id = upload_response.json()["id"]+ UploadedMedia.objects.filter(id=media_id).update(serving_disabled_at=now())++ list_response = self.client.get(f"/api/projects/{self.team.id}/uploaded_media/?purpose=email")+ assert list_response.json()["results"] == []++ self.client.logout()+ blocked_response = self.client.get(f"/uploaded_media/{media_id}")+ assert blocked_response.status_code == status.HTTP_404_NOT_FOUND+ assert blocked_response.headers["Cache-Control"] == "no-store"++ UploadedMedia.objects.filter(id=media_id).update(serving_disabled_at=None)+ restored_response = self.client.get(f"/uploaded_media/{media_id}")+ assert restored_response.status_code == status.HTTP_200_OK+def test_removing_refuses_an_upload_that_is_not_in_a_library(self) -> None:dashboard_image = self._create_media(purpose=None)diff --git a/posthog/api/uploaded_media.py b/posthog/api/uploaded_media.pyindex d84f30a9d872..6431a9ea2618 100644--- a/posthog/api/uploaded_media.py+++ b/posthog/api/uploaded_media.py@@ -146,6 +146,11 @@ def download(request, *args, **kwargs) -> HttpResponse:if instance.purpose in PRIVATE_MEDIA_PURPOSES:return HttpResponse(status=404)+ if instance.serving_disabled_at is not None:+ statsd.incr("uploaded_media.serving_disabled_blocked", tags={"team_id": instance.team_id})+ # The success response is cached for years, so tell caches not to keep this one.+ return HttpResponse(status=404, headers={"Cache-Control": "no-store"})+if instance.media_location is None:return HttpResponse(status=404)file_bytes = object_storage.read_bytes(instance.media_location, missing_ok=True)@@ -277,7 +282,9 @@ class MediaViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# Only library images can be removed. An upload with no purpose (a dashboard text card# image, say) was never listed, so there is nothing for this to take it out of.return queryset.filter(pending=False, purpose__in=MEDIA_PURPOSES, archived_at__isnull=True)- return queryset.filter(pending=False, archived_at__isnull=True).order_by("-created_at", "-id")+ return queryset.filter(pending=False, archived_at__isnull=True, serving_disabled_at__isnull=True).order_by(+ "-created_at", "-id"+ )@extend_schema(description="List images in the media library. Requires a `purpose` filter — the library is scoped per "diff --git a/posthog/migrations/1416_uploadedmedia_serving_disabled_at.py b/posthog/migrations/1416_uploadedmedia_serving_disabled_at.pynew file mode 100644index 000000000000..9f7e773d7e95--- /dev/null+++ b/posthog/migrations/1416_uploadedmedia_serving_disabled_at.py@@ -0,0 +1,17 @@+# Generated by Django 6.1.2 on 2026-10-30 08:57++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1415_organizationaiterms"),+ ]++ operations = [+ migrations.AddField(+ model_name="uploadedmedia",+ name="serving_disabled_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 8168d5266ba4..365e76401264 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1415_organizationaiterms+1416_uploadedmedia_serving_disabled_atdiff --git a/posthog/models/uploaded_media.py b/posthog/models/uploaded_media.pyindex 1a00be574de0..e4227bf85d50 100644--- a/posthog/models/uploaded_media.py+++ b/posthog/models/uploaded_media.py@@ -5,6 +5,7 @@ from typing import Optionalfrom django.conf import settingsfrom django.db import modelsfrom django.db.models import Q+from django.utils import timezoneimport structlogfrom PIL import ExifTags, Image@@ -147,6 +148,9 @@ class UploadedMedia(UUIDTModel, RootTeamMixin):# Set when a user removes the image from its library. The row and its bytes stay, because# content that already embeds the URL (a sent email, a live template) must keep loading it.archived_at = models.DateTimeField(null=True, blank=True)+ # Set by staff to take an image down. Unlike archived_at, the public URL stops serving it.+ # The row and its bytes stay, so the takedown can be audited and reversed.+ serving_disabled_at = models.DateTimeField(null=True, blank=True)class Meta:indexes = [@@ -166,6 +170,29 @@ class UploadedMedia(UUIDTModel, RootTeamMixin):return f"{settings.UPLOADED_MEDIA_PUBLIC_URL}{path}"return absolute_uri(path)+ def stop_serving(self) -> bool:+ """Make the public URL return 404. Returns False when serving was already stopped."""+ if self.serving_disabled_at is not None:+ return False+ self.serving_disabled_at = timezone.now()+ self.save(update_fields=["serving_disabled_at"])+ return True++ @classmethod+ def delete_stored_files(cls, media: list["UploadedMedia"]) -> list["UploadedMedia"]:+ """Delete the image bytes from object storage and keep the rows as a record of the takedown.++ Returns the images whose bytes are gone. An image whose delete failed keeps its location, so+ the delete can be retried. One batched call keeps a slow storage backend from blocking the+ caller once per image.+ """+ failed = set(object_storage.delete_objects([item.media_location for item in media if item.media_location]))+ deleted = [item for item in media if item.media_location not in failed]+ cls.objects.filter(pk__in=[item.pk for item in deleted]).update(media_location=None)+ for item in deleted:+ item.media_location = None+ return deleted+@staticmethoddef build_media_location(team_id: int, media_id) -> str:return "/".join(