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): dedupe active sharing configs and lock token rotation (#61878)

Matt Pua83652f6f0c69
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 8e6cd141c7ca..15d82e737b29 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -343,9 +343,14 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
return context
- def _get_sharing_configuration(self, context: dict[str, Any]):
+ def _get_sharing_configuration(self, context: dict[str, Any], dedupe: bool = False):
"""
- Gets but does not create a SharingConfiguration. Only once enabled do we actually store it
+ 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``.
+ The read path (``list``) must leave it ``False`` so that merely viewing the sharing config
+ never invalidates public share tokens.
"""
context = context or self.get_serializer_context()
dashboard = context.get("dashboard")
@@ -362,17 +367,36 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
"expires_at": None,
}
- try:
- instance = SharingConfiguration.objects.get(**config_kwargs)
- except SharingConfiguration.DoesNotExist:
+ instance = SharingConfiguration.get_active_for_resource(
+ dedupe=dedupe,
+ team_id=self.team_id,
+ insight=insight,
+ dashboard=dashboard,
+ recording=recording,
+ notebook=notebook,
+ )
+ if instance is None:
instance = SharingConfiguration(**config_kwargs)
if dashboard:
# Ensure the legacy dashboard fields are in sync with the sharing configuration
if dashboard.share_token and dashboard.share_token != instance.access_token:
- instance.enabled = dashboard.is_shared
- instance.access_token = dashboard.share_token
- instance.save()
+ if (
+ SharingConfiguration.objects.filter(access_token=dashboard.share_token)
+ .exclude(pk=instance.pk)
+ .exists()
+ ):
+ if instance.pk:
+ dashboard.share_token = instance.access_token
+ dashboard.is_shared = instance.enabled
+ else:
+ dashboard.share_token = None
+ dashboard.is_shared = False
+ dashboard.save(update_fields=["share_token", "is_shared"])
+ else:
+ instance.enabled = dashboard.is_shared
+ instance.access_token = dashboard.share_token
+ instance.save()
return instance
@@ -391,6 +415,9 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
check_can_edit_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)
+
if request.data.get("password_required", False):
if not self.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
return response.Response(
@@ -550,6 +577,8 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
check_can_edit_sharing_configuration(self, request, sharing_config)
+ sharing_config = self._get_sharing_configuration(context, dedupe=True)
+
if not sharing_config.password_required:
return response.Response(
{"error": "Password protection must be enabled before creating passwords"},
@@ -596,6 +625,8 @@ class SharingConfigurationViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin,
check_can_edit_sharing_configuration(self, request, sharing_config)
+ sharing_config = self._get_sharing_configuration(context, dedupe=True)
+
if not self.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
return response.Response(
{"error": "Password management requires the Access Control feature"},
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index aac2bbf4378a..7b34b972c6c6 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -598,6 +598,77 @@ class TestSharing(APIBaseTest):
assert original_config.expires_at is not None
assert original_config.expires_at > timezone.now() # Should be in the future
+ @parameterized.expand(
+ [
+ # action, expected active configs after the call: reads leave duplicates alone,
+ # authorized writes (patch/refresh) collapse them to one.
+ ("get", 2),
+ ("patch", 1),
+ ("refresh", 1),
+ ]
+ )
+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
+ def test_sharing_endpoints_succeed_with_duplicate_active_configs(
+ self, action: str, expected_active_configs: int, _patched_exporter_task: Mock
+ ) -> None:
+ share_settings = {"whitelabel": True, "hideExtraDetails": True}
+ dashboard = Dashboard.objects.create(team=self.team, name="duplicate sharing dashboard", created_by=self.user)
+ for token in ("duplicate_token_one", "duplicate_token_two"):
+ SharingConfiguration.objects.create(
+ team=self.team,
+ dashboard=dashboard,
+ enabled=True,
+ access_token=token,
+ settings=share_settings,
+ )
+
+ base_url = f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/sharing"
+ if action == "get":
+ response = self.client.get(base_url)
+ elif action == "patch":
+ response = self.client.patch(base_url, {"enabled": True})
+ else:
+ response = self.client.post(f"{base_url}/refresh/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert (
+ SharingConfiguration.objects.filter(dashboard=dashboard, expires_at__isnull=True).count()
+ == expected_active_configs
+ )
+ body = response.json()
+ assert body["enabled"] is True
+ assert body["settings"] == share_settings
+
+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
+ def test_legacy_dashboard_share_token_does_not_500_when_token_already_used(
+ self, _patched_exporter_task: Mock
+ ) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="legacy token dashboard", created_by=self.user)
+ SharingConfiguration.objects.create(
+ team=self.team,
+ dashboard=dashboard,
+ enabled=True,
+ access_token="active_token",
+ )
+ expired_config = SharingConfiguration.objects.create(
+ team=self.team,
+ dashboard=dashboard,
+ enabled=True,
+ access_token="legacy_token",
+ expires_at=timezone.now() - timedelta(minutes=1),
+ )
+ dashboard.share_token = expired_config.access_token
+ dashboard.is_shared = True
+ dashboard.save(update_fields=["share_token", "is_shared"])
+
+ response = self.client.get(f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/sharing")
+
+ assert response.status_code == status.HTTP_200_OK
+ dashboard.refresh_from_db()
+ assert dashboard.share_token == "active_token"
+ assert dashboard.is_shared is True
+ assert response.json()["access_token"] == "active_token"
+
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
def test_sharing_configuration_settings_field_defaults(self, patched_exporter_task: Mock):
"""Test that settings field defaults to empty dict"""
diff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.py
index 3c0dce6e8da5..09110a231a2d 100644
--- a/posthog/models/sharing_configuration.py
+++ b/posthog/models/sharing_configuration.py
@@ -1,12 +1,12 @@
import secrets
from datetime import timedelta
-from typing import TYPE_CHECKING, cast
+from typing import TYPE_CHECKING, Any, cast
if TYPE_CHECKING:
from posthog.models.share_password import SharePassword
from django.conf import settings
-from django.db import models
+from django.db import models, transaction
from django.utils import timezone
import structlog
@@ -69,41 +69,158 @@ class SharingConfiguration(models.Model):
password_required = models.BooleanField(default=False)
- def rotate_access_token(self) -> "SharingConfiguration":
- """Create a new sharing configuration and expire the current one"""
+ @classmethod
+ def _resource_lookup(
+ cls,
+ *,
+ team_id: int,
+ dashboard: models.Model | None = None,
+ insight: models.Model | None = None,
+ recording: models.Model | None = None,
+ notebook: models.Model | None = None,
+ interviewee_context: models.Model | None = None,
+ ) -> dict[str, Any]:
+ return {
+ "team_id": team_id,
+ "dashboard": dashboard,
+ "insight": insight,
+ "recording": recording,
+ "notebook": notebook,
+ "interviewee_context": interviewee_context,
+ }
+
+ @classmethod
+ def queryset_active_for_resource(cls, **resource_lookup: Any) -> models.QuerySet["SharingConfiguration"]:
+ return cls.objects.filter(**resource_lookup, expires_at__isnull=True).order_by("-created_at")
+
+ @classmethod
+ def expire_duplicate_active_configs(
+ cls,
+ *,
+ keep: "SharingConfiguration",
+ duplicate_pks: list[int] | None = None,
+ **resource_lookup: Any,
+ ) -> int:
+ duplicate_ids = duplicate_pks
+ if duplicate_ids is None:
+ duplicate_ids = list(
+ cls.queryset_active_for_resource(**resource_lookup).exclude(pk=keep.pk).values_list("pk", flat=True)
+ )
+ if not duplicate_ids:
+ return 0
+
+ updated = cls.objects.filter(pk__in=duplicate_ids).update(expires_at=timezone.now())
+ logger.warning(
+ "sharing_configuration_duplicates_expired",
+ kept_config_id=keep.pk,
+ expired_config_ids=duplicate_ids,
+ team_id=resource_lookup.get("team_id"),
+ )
+ return updated
- new_config = SharingConfiguration.objects.create(
- team=self.team,
+ @classmethod
+ def get_active_for_resource(cls, *, dedupe: bool = False, **resource_lookup: Any) -> "SharingConfiguration | None":
+ if not dedupe:
+ return cls.queryset_active_for_resource(**resource_lookup).first()
+
+ with transaction.atomic():
+ active_configs = list(cls.queryset_active_for_resource(**resource_lookup).select_for_update())
+ if not active_configs:
+ return None
+
+ keep = active_configs[0]
+ duplicate_pks = [config.pk for config in active_configs[1:]]
+ if duplicate_pks:
+ cls.expire_duplicate_active_configs(keep=keep, duplicate_pks=duplicate_pks, **resource_lookup)
+
+ return keep
+
+ def _lock_resource_for_rotation(self) -> None:
+ # Resolve each parent model from its own FK instead of importing it. This keeps the module
+ # free of product imports (``user_interviews`` only exposes its webhooks via tach's
+ # ``[[interfaces]]``) and avoids cycling through ``posthog.models.team`` during ``Team``
+ # initialization, since this module is loaded mid-init via product_analytics'
+ # insight_caching_state.
+ for field_name in ("dashboard", "insight", "notebook", "recording", "interviewee_context"):
+ fk_value = getattr(self, f"{field_name}_id")
+ if not fk_value:
+ continue
+
+ field = cast("models.ForeignKey", self._meta.get_field(field_name))
+ related_model = cast("type[models.Model]", field.related_model)
+ target_field_name = field.target_field.name
+ related_model._default_manager.select_for_update().get(
+ **{target_field_name: fk_value, "team_id": self.team_id}
+ )
+ return
+
+ def _resource_lookup_for_instance(self) -> dict[str, Any]:
+ return self._resource_lookup(
+ team_id=self.team_id,
dashboard=self.dashboard,
insight=self.insight,
recording=self.recording,
notebook=self.notebook,
interviewee_context=self.interviewee_context,
- enabled=self.enabled,
- settings=self.settings,
- password_required=self.password_required,
)
- # Clone active passwords to the new config
- if self.password_required:
- from posthog.models.share_password import SharePassword
-
- for pw in self.share_passwords.filter(is_active=True):
- SharePassword.objects.create(
- sharing_configuration=new_config,
- password_hash=pw.password_hash,
- created_by=pw.created_by,
- note=pw.note,
- is_active=True,
+ def rotate_access_token(self) -> "SharingConfiguration":
+ """Create a new sharing configuration and expire the current one"""
+ resource_lookup = self._resource_lookup_for_instance()
+
+ with transaction.atomic():
+ self._lock_resource_for_rotation()
+
+ active_configs = list(
+ SharingConfiguration.objects.select_for_update()
+ .filter(**resource_lookup, expires_at__isnull=True)
+ .order_by("-created_at")
+ )
+
+ if not active_configs:
+ source = self
+ else:
+ source = active_configs[0]
+ expire_at = timezone.now() + timedelta(seconds=settings.SHARING_TOKEN_GRACE_PERIOD_SECONDS)
+ SharingConfiguration.objects.filter(pk__in=[config.pk for config in active_configs]).update(
+ expires_at=expire_at
)
- # Expire current configuration
- self.expires_at = timezone.now() + timedelta(seconds=settings.SHARING_TOKEN_GRACE_PERIOD_SECONDS)
- self.save()
+ if len(active_configs) > 1:
+ logger.warning(
+ "sharing_configuration_duplicates_expired_during_rotation",
+ kept_config_id=source.pk,
+ expired_config_ids=[config.pk for config in active_configs[1:]],
+ team_id=self.team_id,
+ )
+
+ new_config = SharingConfiguration.objects.create(
+ team=source.team,
+ dashboard=source.dashboard,
+ insight=source.insight,
+ recording=source.recording,
+ notebook=source.notebook,
+ interviewee_context=source.interviewee_context,
+ enabled=source.enabled,
+ settings=source.settings,
+ password_required=source.password_required,
+ )
+
+ if source.password_required:
+ from posthog.models.share_password import SharePassword
+
+ for pw in source.share_passwords.filter(is_active=True):
+ SharePassword.objects.create(
+ sharing_configuration=new_config,
+ password_hash=pw.password_hash,
+ created_by=pw.created_by,
+ note=pw.note,
+ is_active=True,
+ )
logger.info(
"sharing_token_rotated",
- old_config_id=self.pk,
+ old_config_id=source.pk,
new_config_id=new_config.pk,
team_id=self.team_id,
)
diff --git a/posthog/models/test/test_sharing_configuration_model.py b/posthog/models/test/test_sharing_configuration_model.py
index e3311bc50673..d99bf82ef6d1 100644
--- a/posthog/models/test/test_sharing_configuration_model.py
+++ b/posthog/models/test/test_sharing_configuration_model.py
@@ -5,6 +5,8 @@ from posthog.schema import SharingConfigurationSettings
from posthog.models.share_password import SharePassword
from posthog.models.sharing_configuration import SharingConfiguration
+from products.dashboards.backend.models.dashboard import Dashboard
+
class TestSharingConfigurationSettings(BaseTest):
"""Test the SharingConfigurationSettings Pydantic model"""
@@ -208,3 +210,28 @@ class TestSharingConfigurationModel(BaseTest):
assert new_passwords[0].check_password("password-one")
assert new_passwords[1].note == "second"
assert new_passwords[1].check_password("password-two")
+
+ def test_rotate_access_token_expires_duplicate_active_configs(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="rotate duplicate dashboard", created_by=self.user)
+ original_config = SharingConfiguration.objects.create(
+ team=self.team,
+ dashboard=dashboard,
+ enabled=True,
+ access_token="rotate_duplicate_one",
+ )
+ duplicate_config = SharingConfiguration.objects.create(
+ team=self.team,
+ dashboard=dashboard,
+ enabled=True,
+ access_token="rotate_duplicate_two",
+ )
+
+ new_config = original_config.rotate_access_token()
+
+ original_config.refresh_from_db()
+ duplicate_config.refresh_from_db()
+ assert SharingConfiguration.objects.filter(dashboard=dashboard, expires_at__isnull=True).count() == 1
+ assert new_config.expires_at is None
+ assert original_config.expires_at is not None
+ assert duplicate_config.expires_at is not None
+ assert new_config.access_token not in {original_config.access_token, duplicate_config.access_token}