: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
fix(subscriptions): restore exports with sharing disabled (#60276)
Vasco de Krijger771d0c9f635f
diff --git a/ee/tasks/subscriptions/email_subscriptions.py b/ee/tasks/subscriptions/email_subscriptions.pyindex 05d297dbdb6e..1f5d99d13dcf 100644--- a/ee/tasks/subscriptions/email_subscriptions.py+++ b/ee/tasks/subscriptions/email_subscriptions.py@@ -39,7 +39,7 @@ def _get_asset_data_for_email(asset: ExportedAsset) -> dict:return {"error": False,- "image_url": asset.get_public_content_url(),+ "image_url": asset.get_subscription_delivery_content_url(),}diff --git a/ee/tasks/subscriptions/slack_subscriptions.py b/ee/tasks/subscriptions/slack_subscriptions.pyindex 6b6a404e67a7..7027d02db442 100644--- a/ee/tasks/subscriptions/slack_subscriptions.py+++ b/ee/tasks/subscriptions/slack_subscriptions.py@@ -84,7 +84,7 @@ def _block_for_asset(asset: ExportedAsset, resource_url: str) -> dict:return {"type": "section", "text": {"type": "mrkdwn", "text": error_text}}# Normal image block for successful assets- image_url = asset.get_public_content_url()+ image_url = asset.get_subscription_delivery_content_url()alt_text = Noneif asset.insight:alt_text = asset.insight.name or asset.insight.derived_namediff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex e43b9cdc3c5d..173cf495e05d 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -9,6 +9,7 @@ from django.shortcuts import renderfrom django.utils.timezone import nowfrom django.views.decorators.clickjacking import xframe_options_exempt+import jwtimport structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field@@ -35,7 +36,13 @@ from posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_exfrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import Cohort, SessionRecording, SharePassword, SharingConfiguration, Teamfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity-from posthog.models.exported_asset import ExportedAsset, asset_for_token, get_content_response+from posthog.models.exported_asset import (+ EXPORTED_ASSET_PURPOSE_RENDER,+ EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY,+ ExportedAsset,+ asset_for_token,+ get_content_response,+)from posthog.models.resource_transfer.visitors.insight import InsightVisitorfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource@@ -697,6 +704,9 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSepermission_classes = []serializer_class = SharingConfigurationSerializer # Required by DRF but not used in practice+ # Set by get_object() when the resolved resource is an ExportedAsset whose token carried a purpose claim.+ _token_purpose: str | None = None+def initial(self, request, *args, **kwargs):"""Override to ensure we don't apply any session authentication."""# Save and clear any existing user to ensure we start fresh@@ -718,10 +728,10 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSetoken = self.request.query_params.get("token")if token:try:- asset = asset_for_token(token)+ asset, self._token_purpose = asset_for_token(token)if asset:return asset- except ExportedAsset.DoesNotExist:+ except (ExportedAsset.DoesNotExist, jwt.InvalidTokenError):raise NotFound()# Path based access (SharingConfiguration only)@@ -771,6 +781,35 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSedef post(self, request: Request, *args: Any, **kwargs: Any) -> Any:return self.retrieve(request, *args, **kwargs)+ def _is_blocked_by_exported_asset_token_surface(+ self, resource: SharingConfiguration | ExportedAsset, request: Request, token_purpose: str | None+ ) -> bool:+ if not isinstance(resource, ExportedAsset):+ return False++ if token_purpose == EXPORTED_ASSET_PURPOSE_RENDER:+ return request.path != "/exporter"+ if token_purpose == EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY:+ return not request.path.endswith(f".{resource.file_ext}")+ return False++ def _is_blocked_by_public_sharing_setting(+ self, resource: SharingConfiguration | ExportedAsset, request: Request, token_purpose: str | None+ ) -> bool:+ organization = resource.team.organization+ if not organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS):+ return False+ if organization.allow_publicly_shared_resources:+ return False++ if token_purpose in (+ EXPORTED_ASSET_PURPOSE_RENDER,+ EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY,+ ):+ return False++ return True+@xframe_options_exemptdef retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Any:try:@@ -781,10 +820,10 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSeif not resource:return custom_404_response(self.request)- if (- resource.team.organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS)- and not resource.team.organization.allow_publicly_shared_resources- ):+ if self._is_blocked_by_exported_asset_token_surface(resource, request, self._token_purpose):+ return custom_404_response(self.request)++ if self._is_blocked_by_public_sharing_setting(resource, request, self._token_purpose):return custom_404_response(self.request)embedded = "embedded" in request.GET or "/embedded/" in request.pathdiff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 602dace4999f..6e00798ec826 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -7,6 +7,7 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, Mock, patch+from django.http import HttpResponsefrom django.utils import timezonefrom django.utils.timezone import now@@ -16,6 +17,7 @@ from rest_framework import statusfrom posthog.api.sharing import _log_share_password_attempt, shared_url_as_pngfrom posthog.constants import AvailableFeaturefrom posthog.models import ActivityLog, ExportedAsset+from posthog.models.exported_asset import get_render_access_tokenfrom posthog.models.filters.filter import Filterfrom posthog.models.share_password import SharePasswordfrom posthog.models.sharing_configuration import SharingConfiguration@@ -325,7 +327,7 @@ class TestSharing(APIBaseTest):content=None,content_location="some object url",)- patched_asset_for_token.return_value = asset+ patched_asset_for_token.return_value = (asset, None)patched_get_presigned_url.return_value = "https://s3.example.com/presigned-url"@@ -1000,6 +1002,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):assert data["settings"] == expected_settings@patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @mock_exporter_templatedef test_shared_resource_blocked_when_organization_disallows_public_sharing(self, _patched_exporter_task: Mock):"""Test that shared resources return 404 when organization.allow_publicly_shared_resources is False and feature is enabled"""self.organization.available_product_features = [@@ -1023,6 +1026,73 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):response = self.client.get(f"/shared/{access_token}")assert response.status_code == 404+ @parameterized.expand(+ [+ # Org has public sharing DISABLED: only purpose-scoped tokens get through, and only at the matching surface.+ ("sharing_off_public_on_page", False, "public", "page", 404),+ ("sharing_off_public_on_file", False, "public", "file", 404),+ ("sharing_off_render_on_page", False, "render", "page", 200),+ ("sharing_off_render_on_file", False, "render", "file", 404),+ ("sharing_off_subscription_on_page", False, "subscription", "page", 404),+ ("sharing_off_subscription_on_file", False, "subscription", "file", 200),+ # Org has public sharing ENABLED: public tokens work on both surfaces; purpose tokens still pinned to their surface.+ ("sharing_on_public_on_page", True, "public", "page", 200),+ ("sharing_on_public_on_file", True, "public", "file", 200),+ ("sharing_on_render_on_page", True, "render", "page", 200),+ ("sharing_on_render_on_file", True, "render", "file", 404),+ ("sharing_on_subscription_on_page", True, "subscription", "page", 404),+ ("sharing_on_subscription_on_file", True, "subscription", "file", 200),+ ]+ )+ @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("posthog.api.sharing.render_template")+ def test_exported_asset_token_access_matrix(+ self,+ _name: str,+ sharing_enabled: bool,+ token_kind: str,+ url_kind: str,+ expected_status: int,+ mock_render_template: Mock,+ _patched_exporter_task: Mock,+ ) -> None:+ """+ Truth table for ExportedAsset token access. Two axes interact:+ - organization.allow_publicly_shared_resources (on/off)+ - JWT purpose claim (public / render / subscription_delivery) vs URL surface (page / file).++ Render and subscription_delivery tokens are internal-purpose and bypass the org-level public-sharing+ block, but each is pinned to a single URL surface so an intercepted token can't be repurposed.+ """+ mock_render_template.return_value = HttpResponse("<html><body>POSTHOG_EXPORTED_DATA</body></html>")++ self.organization.available_product_features = [+ {"key": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS, "name": "organization_security_settings"},+ ]+ self.organization.allow_publicly_shared_resources = sharing_enabled+ self.organization.save()++ asset = ExportedAsset.objects.create(+ team=self.team,+ dashboard=self.dashboard,+ export_format=ExportedAsset.ExportFormat.PNG,+ content=b"image",+ )++ token = {+ "public": lambda: asset.get_public_content_url().split("token=")[1],+ "render": lambda: get_render_access_token(asset),+ "subscription": lambda: asset.get_subscription_delivery_content_url().split("token=")[1],+ }[token_kind]()++ path = {+ "page": "/exporter",+ "file": f"/exporter/{asset.filename}",+ }[url_kind]++ response = self.client.get(f"{path}?token={token}")+ assert response.status_code == expected_status+@patch("posthog.models.exported_asset.object_storage.get_presigned_url")@patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")def test_exported_asset_public_url_blocked_when_organization_disallows_public_sharing(diff --git a/posthog/models/exported_asset.py b/posthog/models/exported_asset.pyindex 0c5223668b9f..0faa32dd10f9 100644--- a/posthog/models/exported_asset.py+++ b/posthog/models/exported_asset.py@@ -24,6 +24,8 @@ logger = structlog.get_logger(__name__)PUBLIC_ACCESS_TOKEN_EXP_DAYS = 365MAX_AGE_CONTENT = 86400 # 1 day+EXPORTED_ASSET_PURPOSE_RENDER = "render"+EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY = "subscription_delivery"SEVEN_DAYS = timedelta(days=7)SIX_MONTHS = timedelta(days=180)@@ -184,6 +186,10 @@ class ExportedAsset(models.Model):token = get_public_access_token(self, expiry_delta)return absolute_uri(f"/exporter/{self.filename}?token={token}")+ def get_subscription_delivery_content_url(self, expiry_delta: Optional[timedelta] = None):+ token = get_subscription_delivery_access_token(self, expiry_delta)+ return absolute_uri(f"/exporter/{self.filename}?token={token}")+@classmethoddef delete_expired_assets(cls):expired_assets = ExportedAsset.objects_including_ttl_deleted.filter(expires_after__lte=now())@@ -205,11 +211,30 @@ def get_public_access_token(asset: ExportedAsset, expiry_delta: Optional[timedel)-def asset_for_token(token: str) -> ExportedAsset:- info = decode_jwt(token, audience=PosthogJwtAudience.EXPORTED_ASSET)- asset = ExportedAsset.objects.select_related("dashboard", "insight").get(pk=info["id"])+def get_render_access_token(asset: ExportedAsset, expiry_delta: Optional[timedelta] = None) -> str:+ if not expiry_delta:+ expiry_delta = timedelta(minutes=15)+ return encode_jwt(+ {"id": asset.id, "purpose": EXPORTED_ASSET_PURPOSE_RENDER},+ expiry_delta=expiry_delta,+ audience=PosthogJwtAudience.EXPORTED_ASSET,+ )+- return asset+def get_subscription_delivery_access_token(asset: ExportedAsset, expiry_delta: Optional[timedelta] = None) -> str:+ if not expiry_delta:+ expiry_delta = timedelta(days=PUBLIC_ACCESS_TOKEN_EXP_DAYS)+ return encode_jwt(+ {"id": asset.id, "purpose": EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY},+ expiry_delta=expiry_delta,+ audience=PosthogJwtAudience.EXPORTED_ASSET,+ )+++def asset_for_token(token: str) -> tuple[ExportedAsset, str | None]:+ info = decode_jwt(token, audience=PosthogJwtAudience.EXPORTED_ASSET)+ asset = ExportedAsset.objects.select_related("dashboard", "insight", "team__organization").get(pk=info["id"])+ return asset, info.get("purpose")def get_content_response(asset: ExportedAsset, download: bool = False):diff --git a/posthog/tasks/exports/image_exporter.py b/posthog/tasks/exports/image_exporter.pyindex cbf3d9222cbb..88df9861ba1a 100644--- a/posthog/tasks/exports/image_exporter.py+++ b/posthog/tasks/exports/image_exporter.py@@ -26,7 +26,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.event_usage import AnalyticsProps, EventSourcefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models.exported_asset import ExportedAsset, get_public_access_token, save_content+from posthog.models.exported_asset import ExportedAsset, get_render_access_token, save_contentfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.security.url_validation import is_url_allowedfrom posthog.tasks.exporter import EXPORT_TIMER@@ -153,7 +153,7 @@ def _export_to_png(if not os.path.exists(TMP_DIR):os.makedirs(TMP_DIR)- access_token = get_public_access_token(exported_asset, timedelta(minutes=15))+ access_token = get_render_access_token(exported_asset, timedelta(minutes=15))screenshot_width: ScreenWidthwait_for_css_selector: CSSSelector