: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(sharing): gate session recording sharing on editor access (#63476)
Paul D'Ambrad6569ecee7dc
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 15d82e737b29..b53dd000cba1 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -1,10 +1,12 @@import json+from collections.abc import Callablefrom datetime import timedeltafrom typing import Any, Optional, castfrom urllib.parse import urlparse, urlunparse+from django.core.exceptions import ImproperlyConfiguredfrom django.core.serializers.json import DjangoJSONEncoder-from django.db.models import Q+from django.db.models import Model, Qfrom django.shortcuts import renderfrom django.utils.timezone import nowfrom django.views.decorators.clickjacking import xframe_options_exempt@@ -38,6 +40,7 @@ from posthog.models.activity_logging.activity_log import Change, Detail, log_actfrom 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+from posthog.scopes import APIScopeObjectfrom posthog.security.url_validation import is_url_allowedfrom posthog.session_recordings.session_recording_api import SessionRecordingSerializerfrom posthog.user_permissions import UserPermissions@@ -143,6 +146,66 @@ 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]+++def _require_resource_editor(resource: APIScopeObject, denied_message: str) -> SharingResourceEditCheck:+ def check(_view: "SharingConfigurationViewSet", user_access_control: UserAccessControl, target: Model) -> 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)++ return check+++def _require_dashboard_editor(+ view: "SharingConfigurationViewSet", user_access_control: UserAccessControl, dashboard: Model+) -> 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:+ 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.")+++# 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+# 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."),+ # Materialized by the user-interviews link-generation flow, never via SharingConfigurationViewSet.+ "interviewee_context": None,+}+++def _assert_every_shareable_resource_is_gated() -> None:+ model_fields = SharingConfiguration.shareable_resource_fields()+ registered = set(SHARING_RESOURCE_EDIT_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)."+ )+++_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 routedef check_can_edit_sharing_configuration(view: "SharingConfigurationViewSet", request: Request, sharing: SharingConfiguration@@ -160,25 +223,13 @@ def check_can_edit_sharing_configuration(user_access_control = UserAccessControl(cast(User, request.user), team=view.team)- if sharing.dashboard:- # Legacy check: remove once all users are on the new access control- if sharing.dashboard.restriction_level > Dashboard.RestrictionLevel.EVERYONE_IN_PROJECT_CAN_EDIT:- if not view.user_permissions.dashboard(sharing.dashboard).can_edit:- raise PermissionDenied("You don't have edit permissions for this dashboard.")- else:- access_level = user_access_control.get_user_access_level(sharing.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 sharing.insight:- access_level = user_access_control.get_user_access_level(sharing.insight)- if not access_level or not access_level_satisfied_for_resource("insight", access_level, "editor"):- raise PermissionDenied("You don't have edit permissions for this insight.")-- if sharing.notebook:- access_level = user_access_control.get_user_access_level(sharing.notebook)- if not access_level or not access_level_satisfied_for_resource("notebook", access_level, "editor"):- raise PermissionDenied("You don't have edit permissions for this notebook.")+ for field_name, edit_check in SHARING_RESOURCE_EDIT_CHECKS.items():+ target = getattr(sharing, field_name)+ if target is None:+ continue+ if edit_check is None:+ raise PermissionDenied("This resource cannot be shared through this endpoint.")+ edit_check(view, user_access_control, target)return Truediff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 7b34b972c6c6..05732c449dd9 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -7,14 +7,22 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, Mock, patch+from django.core.exceptions import ImproperlyConfiguredfrom django.http import HttpResponsefrom django.utils import timezonefrom django.utils.timezone import nowfrom parameterized import parameterizedfrom rest_framework import status--from posthog.api.sharing import _log_share_password_attempt, shared_url_as_png+from rest_framework.exceptions import PermissionDenied++from posthog.api.sharing import (+ SHARING_RESOURCE_EDIT_CHECKS,+ _assert_every_shareable_resource_is_gated,+ _log_share_password_attempt,+ check_can_edit_sharing_configuration,+ shared_url_as_png,+)from posthog.constants import AvailableFeaturefrom posthog.models import ActivityLogfrom posthog.models.filters.filter import Filter@@ -1587,3 +1595,42 @@ class TestSharedCohortInlining(APIBaseTest):assert widget_data["widget_type"] == "error_tracking_list"assert widget_data["config"]["limit"] == 10assert "created_by" not in widget_data+++class TestSharingResourceEditChecks(APIBaseTest):+ def test_every_shareable_resource_has_an_edit_check(self):+ assert set(SHARING_RESOURCE_EDIT_CHECKS) == SharingConfiguration.shareable_resource_fields()++ @parameterized.expand(+ [+ ("a shareable resource has no registered edit check", "recording", None),+ ("the registry references a non-existent field", None, "made_up_resource"),+ ]+ )+ def test_assertion_rejects_a_registry_out_of_sync_with_the_model(self, _name, drop_key, add_key):+ mutated = dict(SHARING_RESOURCE_EDIT_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 self.assertRaises(ImproperlyConfigured):+ _assert_every_shareable_resource_is_gated()++ @patch("posthog.api.sharing.UserAccessControl")+ def test_gate_fails_closed_for_a_resource_with_no_edit_check(self, _mock_user_access_control):+ sharing = Mock(spec=SharingConfiguration)+ for field_name in SharingConfiguration.shareable_resource_fields():+ setattr(sharing, field_name, None)+ sharing.interviewee_context = Mock()+ sharing.team = self.team++ request = Mock(method="PATCH", data={})+ request.user = self.user+ view = Mock(team=self.team)++ with self.assertRaises(PermissionDenied) as caught:+ check_can_edit_sharing_configuration(view, request, sharing)++ assert "cannot be shared through this endpoint" in str(caught.exception)diff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.pyindex 09110a231a2d..bd2925309ce4 100644--- a/posthog/models/sharing_configuration.py+++ b/posthog/models/sharing_configuration.py@@ -69,6 +69,17 @@ class SharingConfiguration(models.Model):password_required = models.BooleanField(default=False)+ @classmethod+ def shareable_resource_fields(cls) -> frozenset[str]:+ """The FK fields that point at a shareable resource - every relation except the team tenant FK.++ The sharing API cross-checks this against its per-resource edit-permission registry at import+ time, so a newly added shareable resource cannot ship without an explicit access-control decision.+ """+ return frozenset(+ field.name for field in cls._meta.fields if field.is_relation and field.many_to_one and field.name != "team"+ )+@classmethoddef _resource_lookup(cls,diff --git a/posthog/session_recordings/test/test_session_recordings_sharing.py b/posthog/session_recordings/test/test_session_recordings_sharing.pyindex fb9d8b8e1f1f..cdce75930817 100644--- a/posthog/session_recordings/test/test_session_recordings_sharing.py+++ b/posthog/session_recordings/test/test_session_recordings_sharing.py@@ -1,3 +1,4 @@+import pytestfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest@@ -9,11 +10,19 @@ from rest_framework import statusfrom posthog.api.test.test_team import create_teamfrom posthog.clickhouse.client import sync_execute+from posthog.constants import AvailableFeaturefrom posthog.models import Person, SessionRecording+from posthog.models.organization import OrganizationMembership+from posthog.models.user import Userfrom posthog.models.utils import uuid7from posthog.session_recordings.models.session_recording_event import SessionRecordingViewedfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary+try:+ from ee.models.rbac.access_control import AccessControl+except ImportError:+ pass+class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest):def setUp(self):@@ -130,3 +139,59 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchif"/api/projects/{self.team.id}/session_recordings/{self.session_id}/snapshots?sharing_access_token={token}")assert response.status_code == status.HTTP_200_OK, response.json()+++class TestSessionRecordingsSharingAccessControl(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest):+ def setUp(self):+ super().setUp()++ sync_execute("TRUNCATE TABLE sharded_session_replay_events")+ SessionRecording.objects.all().delete()++ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ self.member_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")++ with freeze_time("2023-01-01T12:00:00Z"):+ self.session_id = str(uuid7())+ produce_replay_summary(+ team_id=self.team.pk,+ session_id=self.session_id,+ distinct_id="user",+ first_timestamp=now() - relativedelta(days=1),+ last_timestamp=now() - relativedelta(days=1),+ ensure_analytics_event_in_session=False,+ )++ def _grant_recording_access(self, access_level: str) -> None:+ membership = OrganizationMembership.objects.get(user=self.member_user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="session_recording",+ resource_id=None,+ access_level=access_level,+ organization_member=membership,+ )++ @parameterized.expand(+ [+ ("viewer", status.HTTP_403_FORBIDDEN),+ ("editor", status.HTTP_200_OK),+ ]+ )+ @freeze_time("2023-01-01T12:00:00Z")+ def test_enable_sharing_requires_editor_access(self, access_level: str, expected_status: int) -> None:+ self._grant_recording_access(access_level)+ self.client.force_login(self.member_user)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/session_recordings/{self.session_id}/sharing",+ {"enabled": True},+ )++ assert response.status_code == expected_status, response.json()diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.pyindex adafe20e6948..ca3151e3be0a 100644--- a/products/user_interviews/backend/test_interview_sharing.py+++ b/products/user_interviews/backend/test_interview_sharing.py@@ -9,7 +9,7 @@ from typing import Anyimport unittestfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import Mock, patchfrom django.template.loader import get_templatefrom django.test import override_settings@@ -17,7 +17,9 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.exceptions import PermissionDenied+from posthog.api.sharing import check_can_edit_sharing_configurationfrom posthog.api.test.test_sharing import mock_exporter_templatefrom posthog.models.sharing_configuration import SharingConfiguration@@ -1384,3 +1386,28 @@ class TestSharingConfigurationCanAccess(APIBaseTest):)share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)self.assertTrue(share.can_access_object(ic))++ def test_interviewee_context_config_fails_closed_through_sharing_gate(self):+ topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="t",+ )+ ic = IntervieweeContext.objects.create(+ team=self.team,+ topic=topic,+ interviewee_identifier="[email protected]",+ agent_context="",+ created_by=self.user,+ )+ share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)++ request = Mock(method="PATCH", data={"enabled": True})+ request.user = self.user+ view = Mock(team=self.team)++ with self.assertRaises(PermissionDenied) as caught:+ check_can_edit_sharing_configuration(view, request, share)++ assert "cannot be shared through this endpoint" in str(caught.exception)