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(sharing): tighten validation on the shared-link surface (#82228)

Tom Piccirellobf1733d8c5cd
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 79bb0cd65560..a7763adac9bc 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -49,6 +49,7 @@ from posthog.rate_limit import (
)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import (
+ AccessControlLevel,
UserAccessControl,
UserAccessControlSerializerMixin,
access_level_satisfied_for_resource,
@@ -161,43 +162,63 @@ def _log_share_password_attempt(
)
-# A check raises PermissionDenied when the requesting user may not edit sharing for the given target.
-SharingResourceEditCheck = Callable[["SharingConfigurationViewSet", UserAccessControl, Model], None]
+# A check raises PermissionDenied when the requesting user doesn't hold ``required_level`` on the target.
+SharingResourceAccessCheck = Callable[
+ ["SharingConfigurationViewSet", UserAccessControl, Model, AccessControlLevel], None
+]
-def _require_resource_editor(resource: APIScopeObject, denied_message: str) -> SharingResourceEditCheck:
- def check(_view: "SharingConfigurationViewSet", user_access_control: UserAccessControl, target: Model) -> None:
+def _denied_message(resource_label: str, required_level: AccessControlLevel) -> str:
+ if required_level == "editor":
+ return f"You don't have edit permissions for this {resource_label}."
+ return f"You don't have access to this {resource_label}."
+
+
+def _require_resource_access(resource: APIScopeObject, resource_label: str) -> SharingResourceAccessCheck:
+ def check(
+ _view: "SharingConfigurationViewSet",
+ user_access_control: UserAccessControl,
+ target: Model,
+ required_level: AccessControlLevel,
+ ) -> None:
access_level = user_access_control.get_user_access_level(target)
- if not access_level or not access_level_satisfied_for_resource(resource, access_level, "editor"):
- raise PermissionDenied(denied_message)
+ if not access_level or not access_level_satisfied_for_resource(resource, access_level, required_level):
+ raise PermissionDenied(_denied_message(resource_label, required_level))
return check
-def _require_dashboard_editor(
- view: "SharingConfigurationViewSet", user_access_control: UserAccessControl, dashboard: Model
+def _require_dashboard_access(
+ view: "SharingConfigurationViewSet",
+ user_access_control: UserAccessControl,
+ dashboard: Model,
+ required_level: AccessControlLevel,
) -> None:
dashboard = cast(Dashboard, dashboard)
- # Legacy check: remove once all users are on the new access control
- if dashboard.restriction_level > Dashboard.RestrictionLevel.EVERYONE_IN_PROJECT_CAN_EDIT:
+ # Legacy check: remove once all users are on the new access control. It restricts editing only, so
+ # it must not gate a read.
+ if (
+ required_level == "editor"
+ and dashboard.restriction_level > Dashboard.RestrictionLevel.EVERYONE_IN_PROJECT_CAN_EDIT
+ ):
if not view.user_permissions.dashboard(dashboard).can_edit:
raise PermissionDenied("You don't have edit permissions for this dashboard.")
return
access_level = user_access_control.get_user_access_level(dashboard)
- if not access_level or not access_level_satisfied_for_resource("dashboard", access_level, "editor"):
- raise PermissionDenied("You don't have edit permissions for this dashboard.")
+ if not access_level or not access_level_satisfied_for_resource("dashboard", access_level, required_level):
+ raise PermissionDenied(_denied_message("dashboard", required_level))
-# Maps every shareable FK on SharingConfiguration to the editor-permission check that gates writes for it.
-# A ``None`` value means the resource is created server-side and is not writable through this viewset; if such
+# Maps every shareable FK on SharingConfiguration to the permission check that gates access to it.
+# A ``None`` value means the resource is created server-side and is not reachable through this viewset; if such
# a config ever reaches the gate we fail closed rather than fall through to "allowed". The relationship is
# enforced against the model below, so a newly added shareable resource cannot ship without a decision here.
-SHARING_RESOURCE_EDIT_CHECKS: dict[str, SharingResourceEditCheck | None] = {
- "dashboard": _require_dashboard_editor,
- "insight": _require_resource_editor("insight", "You don't have edit permissions for this insight."),
- "recording": _require_resource_editor("session_recording", "You don't have edit permissions for this recording."),
- "notebook": _require_resource_editor("notebook", "You don't have edit permissions for this notebook."),
+SHARING_RESOURCE_ACCESS_CHECKS: dict[str, SharingResourceAccessCheck | None] = {
+ "dashboard": _require_dashboard_access,
+ "insight": _require_resource_access("insight", "insight"),
+ "recording": _require_resource_access("session_recording", "recording"),
+ "notebook": _require_resource_access("notebook", "notebook"),
# Materialized by the user-interviews link-generation flow, never via SharingConfigurationViewSet.
"interviewee_context": None,
}
@@ -205,16 +226,16 @@ SHARING_RESOURCE_EDIT_CHECKS: dict[str, SharingResourceEditCheck | None] = {
def _assert_every_shareable_resource_is_gated() -> None:
model_fields = SharingConfiguration.shareable_resource_fields()
- registered = set(SHARING_RESOURCE_EDIT_CHECKS)
+ registered = set(SHARING_RESOURCE_ACCESS_CHECKS)
missing = model_fields - registered
unexpected = registered - model_fields
if missing or unexpected:
raise ImproperlyConfigured(
- "SHARING_RESOURCE_EDIT_CHECKS is out of sync with SharingConfiguration's shareable FK fields. "
- f"Missing a sharing edit check for: {sorted(missing)}. "
- f"Edit check registered for a non-existent field: {sorted(unexpected)}. "
- "Every shareable resource needs an explicit editor-permission check (or None when it is not "
- "editable through SharingConfigurationViewSet)."
+ "SHARING_RESOURCE_ACCESS_CHECKS is out of sync with SharingConfiguration's shareable FK fields. "
+ f"Missing a sharing access check for: {sorted(missing)}. "
+ f"Access check registered for a non-existent field: {sorted(unexpected)}. "
+ "Every shareable resource needs an explicit permission check (or None when it is not "
+ "reachable through SharingConfigurationViewSet)."
)
@@ -222,15 +243,17 @@ _assert_every_shareable_resource_is_gated()
# NOTE: We can't use a standard permission system as we are using Detail view on a non-detail route
-def check_can_edit_sharing_configuration(
+def check_can_access_sharing_configuration(
view: "SharingConfigurationViewSet", request: Request, sharing: SharingConfiguration
) -> bool:
- if request.method in SAFE_METHODS:
- return True
+ """A share token grants anonymous access to the resource, so reading one needs at least the access
+ the token hands out, and changing one needs edit access."""
+ required_level: AccessControlLevel = "viewer" if request.method in SAFE_METHODS else "editor"
# Check if organization allows publicly shared resources
if (
- request.data.get("enabled")
+ required_level == "editor"
+ and request.data.get("enabled")
and sharing.team.organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS)
and not sharing.team.organization.allow_publicly_shared_resources
):
@@ -238,13 +261,13 @@ def check_can_edit_sharing_configuration(
user_access_control = UserAccessControl(cast(User, request.user), team=view.team)
- for field_name, edit_check in SHARING_RESOURCE_EDIT_CHECKS.items():
+ for field_name, access_check in SHARING_RESOURCE_ACCESS_CHECKS.items():
target = getattr(sharing, field_name)
if target is None:
continue
- if edit_check is None:
+ if access_check is None:
raise PermissionDenied("This resource cannot be shared through this endpoint.")
- edit_check(view, user_access_control, target)
+ access_check(view, user_access_control, target, required_level)
return True
@@ -425,7 +448,7 @@ class SharingConfigurationViewSet(
Gets but does not create a SharingConfiguration. Only once enabled do we actually store it.
``dedupe`` expires duplicate active rows, which is a mutation — only pass it from a write
- path that has already authorized the caller via ``check_can_edit_sharing_configuration``.
+ path that has already authorized the caller via ``check_can_access_sharing_configuration``.
The read path (``list``) must leave it ``False`` so that merely viewing the sharing config
never invalidates public share tokens.
"""
@@ -485,6 +508,9 @@ class SharingConfigurationViewSet(
context = self.get_serializer_context()
instance = self._get_sharing_configuration(context)
+ # The parent resource is resolved from the URL, so DRF never runs object permissions here.
+ check_can_access_sharing_configuration(self, request, instance)
+
serializer = self.get_serializer(instance, context)
serializer.is_valid(raise_exception=True)
@@ -494,7 +520,7 @@ class SharingConfigurationViewSet(
context = self.get_serializer_context()
instance = self._get_sharing_configuration(context)
- check_can_edit_sharing_configuration(self, request, instance)
+ check_can_access_sharing_configuration(self, request, instance)
# Now that the caller is authorized to edit, collapse any duplicate active rows.
instance = self._get_sharing_configuration(context, dedupe=True)
@@ -617,7 +643,7 @@ class SharingConfigurationViewSet(
# Special case where we need to save the instance for recordings so that the actual record gets created
recording.save()
- check_can_edit_sharing_configuration(self, request, instance)
+ check_can_access_sharing_configuration(self, request, instance)
# Create new sharing configuration and expire the old one
new_instance = instance.rotate_access_token()
@@ -674,7 +700,7 @@ class SharingConfigurationViewSet(
context = self.get_serializer_context()
sharing_config = self._get_sharing_configuration(context)
- check_can_edit_sharing_configuration(self, request, sharing_config)
+ check_can_access_sharing_configuration(self, request, sharing_config)
sharing_config = self._get_sharing_configuration(context, dedupe=True)
@@ -722,7 +748,7 @@ class SharingConfigurationViewSet(
context = self.get_serializer_context()
sharing_config = self._get_sharing_configuration(context)
- check_can_edit_sharing_configuration(self, request, sharing_config)
+ check_can_access_sharing_configuration(self, request, sharing_config)
sharing_config = self._get_sharing_configuration(context, dedupe=True)
@@ -968,9 +994,13 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
embedded = "embedded" in request.GET or "/embedded/" in request.path
- # Parse cache_keys parameter if present (used by image exporter to guarantee cache hits)
+ # Parse cache_keys parameter if present (used by image exporter to guarantee cache hits).
+ # Only the export worker's own render page may name a cache key: it warms the entry itself and
+ # reaches this view with a render-purpose asset token. On /shared/, /embedded/ and
+ # /shared_dashboard/ the caller is an anonymous viewer, so the parameter is ignored.
export_cache_keys: Optional[dict[int, str]] = None
- if cache_keys_param := request.GET.get("cache_keys"):
+ is_export_render = isinstance(resource, ExportedAsset) and self._token_purpose == EXPORTED_ASSET_PURPOSE_RENDER
+ if is_export_render and (cache_keys_param := request.GET.get("cache_keys")):
try:
raw_cache_keys = json.loads(cache_keys_param)
export_cache_keys = {int(k): v for k, v in raw_cache_keys.items()}
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index d685e1463e77..4487085f7261 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -17,10 +17,10 @@ from rest_framework import status
from rest_framework.exceptions import PermissionDenied
from posthog.api.sharing import (
- SHARING_RESOURCE_EDIT_CHECKS,
+ SHARING_RESOURCE_ACCESS_CHECKS,
_assert_every_shareable_resource_is_gated,
_log_share_password_attempt,
- check_can_edit_sharing_configuration,
+ check_can_access_sharing_configuration,
shared_url_as_png,
)
from posthog.constants import AvailableFeature
@@ -1437,6 +1437,7 @@ class TestExportCacheKeyFlow(APIBaseTest):
insight: Insight
sharing_config: SharingConfiguration
+ exported_asset: ExportedAsset
@classmethod
def setUpTestData(cls) -> None:
@@ -1451,31 +1452,56 @@ class TestExportCacheKeyFlow(APIBaseTest):
insight=cls.insight,
enabled=True,
)
+ cls.exported_asset = ExportedAsset.objects.create(
+ team=cls.team,
+ insight=cls.insight,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ )
+
+ def _render_url(self, cache_keys_param: str) -> str:
+ # The render-purpose token the image-export worker mints for browserless.
+ return f"/exporter?token={get_render_access_token(self.exported_asset)}&cache_keys={cache_keys_param}"
+
+ def _own_team_cache_key(self) -> str:
+ return f"cache_{self.team.pk}_abc123"
+
+ @staticmethod
+ def _cached_entry(mock_query_cache_cls: MagicMock, marker: str) -> None:
+ mock_entry = MagicMock()
+ mock_entry.as_full_response.return_value = {
+ "results": [{"count": 42, "note": marker}],
+ "last_refresh": "2024-01-01T00:00:00Z",
+ "timezone": "UTC",
+ }
+ mock_query_cache_cls.return_value.lookup.return_value.entry = mock_entry
+
+ @staticmethod
+ def _calculated_result(mock_calculate: MagicMock) -> None:
+ from posthog.caching.insight_result import InsightResult
+
+ mock_calculate.return_value = InsightResult(
+ result=[{"count": 50}],
+ cache_key="calculated_cache_key",
+ is_cached=False,
+ last_refresh=None,
+ timezone="UTC",
+ )
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
@patch("products.product_analytics.backend.api.insight.QueryCache")
@mock_exporter_template
def test_cache_keys_parameter_triggers_direct_cache_lookup(self, mock_query_cache_cls, mock_calculate):
"""Test that cache_keys param causes InsightSerializer to use direct cache lookup and skip calculation."""
- cached_response = {
- "results": [{"count": 42}],
- "cache_key": "expected_cache_key_abc123",
- "last_refresh": "2024-01-01T00:00:00Z",
- "timezone": "UTC",
- }
- mock_entry = MagicMock()
- mock_entry.as_full_response.return_value = cached_response
- mock_query_cache_cls.return_value.lookup.return_value.entry = mock_entry
+ self._cached_entry(mock_query_cache_cls, "warmed-by-the-exporter")
- cache_keys = {str(self.insight.id): "expected_cache_key_abc123"}
- cache_keys_param = quote(json.dumps(cache_keys))
+ cache_key = self._own_team_cache_key()
+ cache_keys_param = quote(json.dumps({str(self.insight.id): cache_key}))
- response = self.client.get(f"/shared/{self.sharing_config.access_token}?cache_keys={cache_keys_param}")
+ response = self.client.get(self._render_url(cache_keys_param))
assert response.status_code == 200
- mock_query_cache_cls.assert_called_once_with(
- team_id=self.insight.team_id, cache_key="expected_cache_key_abc123"
- )
+ assert b"warmed-by-the-exporter" in response.content
+ mock_query_cache_cls.assert_called_once_with(team_id=self.insight.team_id, cache_key=cache_key)
mock_calculate.assert_not_called()
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
@@ -1483,24 +1509,16 @@ class TestExportCacheKeyFlow(APIBaseTest):
@mock_exporter_template
def test_cache_miss_falls_back_to_normal_calculation(self, mock_query_cache_cls, mock_calculate):
"""Test that cache miss on expected key falls back to normal calculation."""
- from posthog.caching.insight_result import InsightResult
-
mock_query_cache_cls.return_value.lookup.return_value.entry = None # Cache miss
- mock_calculate.return_value = InsightResult(
- result=[{"count": 50}],
- cache_key="calculated_cache_key",
- is_cached=False,
- last_refresh=None,
- timezone="UTC",
- )
+ self._calculated_result(mock_calculate)
- cache_keys = {str(self.insight.id): "missing_cache_key"}
- cache_keys_param = quote(json.dumps(cache_keys))
+ cache_key = self._own_team_cache_key()
+ cache_keys_param = quote(json.dumps({str(self.insight.id): cache_key}))
- response = self.client.get(f"/shared/{self.sharing_config.access_token}?cache_keys={cache_keys_param}")
+ response = self.client.get(self._render_url(cache_keys_param))
assert response.status_code == 200
- mock_query_cache_cls.assert_called_once_with(team_id=self.insight.team_id, cache_key="missing_cache_key")
+ mock_query_cache_cls.assert_called_once_with(team_id=self.insight.team_id, cache_key=cache_key)
mock_calculate.assert_called_once()
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
@@ -1508,24 +1526,57 @@ class TestExportCacheKeyFlow(APIBaseTest):
@mock_exporter_template
def test_invalid_cache_keys_param_continues_without_it(self, mock_query_cache_cls, mock_calculate):
"""Test that invalid cache_keys parameter is ignored and normal flow continues."""
- from posthog.caching.insight_result import InsightResult
+ self._calculated_result(mock_calculate)
- mock_calculate.return_value = InsightResult(
- result=[{"count": 25}],
- cache_key="normal_cache_key",
- is_cached=False,
- last_refresh=None,
- timezone="UTC",
- )
-
- # Pass invalid JSON as cache_keys
- response = self.client.get(f"/shared/{self.sharing_config.access_token}?cache_keys=not_valid_json")
+ response = self.client.get(self._render_url("not_valid_json"))
assert response.status_code == 200
# QueryCache should not be constructed since cache_keys parsing failed
mock_query_cache_cls.assert_not_called()
mock_calculate.assert_called_once()
+ @parameterized.expand(
+ [
+ ("shared", "/shared/{token}"),
+ ("embedded", "/embedded/{token}"),
+ ]
+ )
+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
+ @patch("products.product_analytics.backend.api.insight.QueryCache")
+ @mock_exporter_template
+ def test_public_share_link_cannot_name_the_cache_key_to_read(
+ self, _name: str, path: str, mock_query_cache_cls, mock_calculate
+ ):
+ self._cached_entry(mock_query_cache_cls, "someone-elses-cached-rows")
+ self._calculated_result(mock_calculate)
+
+ cache_keys_param = quote(json.dumps({str(self.insight.id): self._own_team_cache_key()}))
+ url = path.format(token=self.sharing_config.access_token)
+
+ response = self.client.get(f"{url}?cache_keys={cache_keys_param}")
+
+ assert response.status_code == 200
+ assert b"someone-elses-cached-rows" not in response.content
+ mock_query_cache_cls.assert_not_called()
+ mock_calculate.assert_called_once()
+
+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
+ @patch("products.product_analytics.backend.api.insight.QueryCache")
+ @mock_exporter_template
+ def test_cache_key_from_another_team_is_not_served(self, mock_query_cache_cls, mock_calculate):
+ self._cached_entry(mock_query_cache_cls, "another-teams-cached-rows")
+ self._calculated_result(mock_calculate)
+
+ foreign_key = f"cache_{self.team.pk + 1}_abc123"
+ cache_keys_param = quote(json.dumps({str(self.insight.id): foreign_key}))
+
+ response = self.client.get(self._render_url(cache_keys_param))
+
+ assert response.status_code == 200
+ assert b"another-teams-cached-rows" not in response.content
+ mock_query_cache_cls.assert_not_called()
+ mock_calculate.assert_called_once()
+
class TestSharedAdhocQueryExport(APIBaseTest):
"""The /exporter page for an insight-less PNG asset (export_context.source) must inline the
@@ -1758,7 +1809,7 @@ class TestSharedCohortInlining(APIBaseTest):
class TestSharingResourceEditChecks(APIBaseTest):
def test_every_shareable_resource_has_an_edit_check(self):
- assert set(SHARING_RESOURCE_EDIT_CHECKS) == SharingConfiguration.shareable_resource_fields()
+ assert set(SHARING_RESOURCE_ACCESS_CHECKS) == SharingConfiguration.shareable_resource_fields()
@parameterized.expand(
[
@@ -1767,13 +1818,13 @@ class TestSharingResourceEditChecks(APIBaseTest):
]
)
def test_assertion_rejects_a_registry_out_of_sync_with_the_model(self, _name, drop_key, add_key):
- mutated = dict(SHARING_RESOURCE_EDIT_CHECKS)
+ mutated = dict(SHARING_RESOURCE_ACCESS_CHECKS)
if drop_key:
mutated.pop(drop_key)
if add_key:
mutated[add_key] = None
- with patch.dict("posthog.api.sharing.SHARING_RESOURCE_EDIT_CHECKS", mutated, clear=True):
+ with patch.dict("posthog.api.sharing.SHARING_RESOURCE_ACCESS_CHECKS", mutated, clear=True):
with self.assertRaises(ImproperlyConfigured):
_assert_every_shareable_resource_is_gated()
@@ -1790,11 +1841,60 @@ class TestSharingResourceEditChecks(APIBaseTest):
view = Mock(team=self.team)
with self.assertRaises(PermissionDenied) as caught:
- check_can_edit_sharing_configuration(view, request, sharing)
+ check_can_access_sharing_configuration(view, request, sharing)
assert "cannot be shared through this endpoint" in str(caught.exception)
+class TestSharingConfigurationReadAccess(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ owner = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.dashboard = Dashboard.objects.create(team=self.team, name="Private board", created_by=owner)
+ self.insight = Insight.objects.create(team=self.team, name="Private insight", created_by=owner)
+ SharingConfiguration.objects.create(
+ team=self.team, dashboard=self.dashboard, enabled=True, access_token="dashboard_share_secret"
+ )
+ SharingConfiguration.objects.create(
+ team=self.team, insight=self.insight, enabled=True, access_token="insight_share_secret"
+ )
+
+ @parameterized.expand(
+ [
+ ("dashboard_no_rule", "dashboard", None, status.HTTP_200_OK),
+ ("dashboard_viewer", "dashboard", "viewer", status.HTTP_200_OK),
+ ("dashboard_none", "dashboard", "none", status.HTTP_403_FORBIDDEN),
+ ("insight_no_rule", "insight", None, status.HTTP_200_OK),
+ ("insight_viewer", "insight", "viewer", status.HTTP_200_OK),
+ ("insight_none", "insight", "none", status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_reading_a_share_token_requires_access_to_the_shared_resource(
+ self, _name: str, resource: str, access_level: str | None, expected_status: int
+ ) -> None:
+ target = self.dashboard if resource == "dashboard" else self.insight
+ if access_level:
+ AccessControl.objects.create(
+ team=self.team,
+ resource=resource,
+ resource_id=str(target.id),
+ access_level=access_level,
+ organization_member=self.organization_membership,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/{resource}s/{target.id}/sharing")
+
+ assert response.status_code == expected_status, response.json()
+ assert (f"{resource}_share_secret" in response.content.decode()) == (expected_status == status.HTTP_200_OK)
+
+
def _warehouse_ac_flag(key: str, *args, **kwargs) -> bool:
return key == "hogql-warehouse-access-control"
diff --git a/posthog/utils.py b/posthog/utils.py
index 077761be0074..abca3968b3bf 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -1234,8 +1234,13 @@ def get_compare_period_dates(
return new_date_from, new_date_to
+def generate_cache_key_prefix(team_pk: int) -> str:
+ """The query cache is a single keyspace shared by every team, so each key carries its own team."""
+ return f"cache_{team_pk}_"
+
+
def generate_cache_key(team_pk: int, stringified: str) -> str:
- return f"cache_{team_pk}_{hashlib.sha256(stringified.encode('utf-8')).hexdigest()}"
+ return f"{generate_cache_key_prefix(team_pk)}{hashlib.sha256(stringified.encode('utf-8')).hexdigest()}"
def get_celery_heartbeat() -> Union[str, int]:
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 1cef5685ece9..4bd096899c09 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -134,6 +134,7 @@ from posthog.shared_link_user import SharedLinkUser
from posthog.user_permissions import UserPermissionsSerializerMixin
from posthog.utils import (
filters_override_requested_by_client,
+ generate_cache_key_prefix,
refresh_requested_by_client,
relative_date_parse,
str_to_bool,
@@ -1302,8 +1303,19 @@ class InsightSerializer(InsightBasicSerializer):
# Check if we have an expected cache key from the image exporter
export_cache_keys: dict[int, str] | None = self.context.get("export_cache_keys")
- if export_cache_keys and insight.id in export_cache_keys:
- expected_cache_key = export_cache_keys[insight.id]
+ expected_cache_key = (export_cache_keys or {}).get(insight.id)
+ # The cache key is unauthenticated input carried on the render URL, and the store it indexes is
+ # shared across teams. `generate_cache_key` prefixes every key with the team it was computed for,
+ # so a key that doesn't carry this insight's team can't be one the runner would produce for it.
+ if expected_cache_key and not expected_cache_key.startswith(generate_cache_key_prefix(insight.team_id)):
+ logger.error(
+ "export_cache_key_team_mismatch",
+ insight_id=insight.id,
+ expected_cache_key=expected_cache_key,
+ message="Cache key does not belong to the insight's team - falling back to normal calculation",
+ )
+ expected_cache_key = None
+ if expected_cache_key:
entry = QueryCache(team_id=insight.team_id, cache_key=expected_cache_key).lookup().entry
cached_response = entry.as_full_response() if entry else None
if cached_response:
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index d813a8360321..340714996c0f 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -19,7 +19,7 @@ from parameterized import parameterized
from rest_framework import status
from rest_framework.exceptions import PermissionDenied
-from posthog.api.sharing import check_can_edit_sharing_configuration
+from posthog.api.sharing import check_can_access_sharing_configuration
from posthog.api.test.test_sharing import mock_exporter_template
from posthog.models.sharing_configuration import SharingConfiguration
@@ -1453,6 +1453,6 @@ class TestSharingConfigurationCanAccess(APIBaseTest):
view = Mock(team=self.team)
with self.assertRaises(PermissionDenied) as caught:
- check_can_edit_sharing_configuration(view, request, share)
+ check_can_access_sharing_configuration(view, request, share)
assert "cannot be shared through this endpoint" in str(caught.exception)