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(self-driving): let members enable session replay (#87089)

Tue Haulundaa07853fc35b
diff --git a/posthog/api/product_enablement.py b/posthog/api/product_enablement.py
index bcab9a6b6891..06b48998cdd5 100644
--- a/posthog/api/product_enablement.py
+++ b/posthog/api/product_enablement.py
@@ -14,6 +14,8 @@ import secrets
from collections.abc import Callable
from typing import cast
+from django.db import transaction
+
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.exceptions import PermissionDenied
@@ -69,6 +71,10 @@ def _enable_conversations(team: Team, touched: set[str]) -> str:
return "enabled"
+# Companion defaults the server writes only when the field is unset: they pin a conservative floor
+# rather than express a caller's choice, so they never require admin even where the Team API gates them.
+SERVER_DEFAULT_FIELDS: frozenset[str] = frozenset({"session_recording_masking_config", "conversations_settings"})
+
RECIPES: dict[str, Recipe] = {
"session_replay": _enable_session_replay,
"error_tracking": _enable_error_tracking,
@@ -106,43 +112,47 @@ class ProductEnablementViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
serializer = ProductEnablementSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
- team = self.team
- before = team.__dict__.copy()
- touched: set[str] = set()
- # dict.fromkeys dedupes while preserving the caller's order.
- results = {
- product: RECIPES[product](team, touched) for product in dict.fromkeys(serializer.validated_data["products"])
- }
-
- # conversations + replay masking are admin-only on the normal Team-update API; replicate that
- # gate so this endpoint can't be a bypass (error_tracking + the replay opt-in stay member-safe).
- admin_fields = touched & TEAM_CONFIG_ADMIN_FIELDS_SET
- if admin_fields:
- level = self.user_permissions.team(team).effective_membership_level
- if level is None or level < OrganizationMembership.Level.ADMIN:
- raise PermissionDenied(
- "Only project admins can enable products that change these settings: "
- + ", ".join(sorted(admin_fields))
+ # Lock the row for the read-modify-write: the recipes only write a companion default when the
+ # field is unset, so a stale read would let this clobber a concurrent admin's stricter config.
+ with transaction.atomic():
+ team = Team.objects.select_for_update().get(pk=self.team.pk)
+ before = team.__dict__.copy()
+ touched: set[str] = set()
+ # dict.fromkeys dedupes while preserving the caller's order.
+ results = {
+ product: RECIPES[product](team, touched)
+ for product in dict.fromkeys(serializer.validated_data["products"])
+ }
+
+ # conversations is admin-only on the normal Team-update API; replicate that gate so this endpoint
+ # can't be a bypass (error_tracking + the replay opt-in stay member-safe).
+ admin_fields = (touched - SERVER_DEFAULT_FIELDS) & TEAM_CONFIG_ADMIN_FIELDS_SET
+ if admin_fields:
+ level = self.user_permissions.team(team).effective_membership_level
+ if level is None or level < OrganizationMembership.Level.ADMIN:
+ raise PermissionDenied(
+ "Only project admins can enable products that change these settings: "
+ + ", ".join(sorted(admin_fields))
+ )
+
+ if touched:
+ team.save(update_fields=sorted(touched))
+ # Audit the enable like the Team-update API does; drop conversations_settings so the
+ # minted widget token never lands in the activity log.
+ changes = [
+ change
+ for change in dict_changes_between("Team", before, team.__dict__, use_field_exclusions=True)
+ if change.field != "conversations_settings"
+ ]
+ log_activity(
+ organization_id=team.organization_id,
+ team_id=team.pk,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ scope="Team",
+ item_id=team.pk,
+ activity="updated",
+ detail=Detail(name=str(team.name), changes=changes),
)
- if touched:
- team.save(update_fields=sorted(touched))
- # Audit the enable like the Team-update API does; drop conversations_settings so the
- # minted widget token never lands in the activity log.
- changes = [
- change
- for change in dict_changes_between("Team", before, team.__dict__, use_field_exclusions=True)
- if change.field != "conversations_settings"
- ]
- log_activity(
- organization_id=team.organization_id,
- team_id=team.pk,
- user=cast(User, request.user),
- was_impersonated=is_impersonated(request),
- scope="Team",
- item_id=team.pk,
- activity="updated",
- detail=Detail(name=str(team.name), changes=changes),
- )
-
return Response({"results": results}, status=status.HTTP_200_OK)
diff --git a/posthog/api/test/test_product_enablement.py b/posthog/api/test/test_product_enablement.py
index 356e8beb9545..a805141e229e 100644
--- a/posthog/api/test/test_product_enablement.py
+++ b/posthog/api/test/test_product_enablement.py
@@ -9,8 +9,8 @@ from posthog.models.activity_logging.activity_log import ActivityLog
class TestProductEnablementAPI(APIBaseTest):
def setUp(self) -> None:
super().setUp()
- # The endpoint's admin-gated recipes (conversations, replay masking) need an admin caller;
- # the member-denial path is covered by test_admin_gated_products_require_project_admin.
+ # The endpoint's admin-gated recipe (conversations) needs an admin caller; the member-denial
+ # path is covered by test_admin_gated_products_require_project_admin.
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
@@ -88,8 +88,8 @@ class TestProductEnablementAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_admin_gated_products_require_project_admin(self):
- # A non-admin member can enable member-safe products but not the admin-gated ones
- # (conversations / replay masking), matching the team-update API's gate.
+ # A non-admin member can enable member-safe products but not conversations, matching the
+ # team-update API's gate.
self.organization_membership.level = OrganizationMembership.Level.MEMBER
self.organization_membership.save()
@@ -97,6 +97,12 @@ class TestProductEnablementAPI(APIBaseTest):
self.team.refresh_from_db()
self.assertTrue(self.team.autocapture_exceptions_opt_in)
+ # The server's own masking floor must not gate the member-safe replay opt-in.
+ self.assertEqual(self._enable(["session_replay"]).status_code, status.HTTP_200_OK)
+ self.team.refresh_from_db()
+ self.assertTrue(self.team.session_recording_opt_in)
+ self.assertEqual(self.team.session_recording_masking_config, {"maskAllInputs": True})
+
response = self._enable(["conversations"])
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.team.refresh_from_db()