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(conversations): make signing secret rotation atomic (#106743)

Patricio91588bcff078
diff --git a/posthog/models/signals.py b/posthog/models/signals.py
index 8b8cc6261f34..d6641ea437ba 100644
--- a/posthog/models/signals.py
+++ b/posthog/models/signals.py
@@ -13,9 +13,10 @@ is_muted = False
# See FeatureFlag for an example.
model_activity_signal = Signal()
-# Sent by Team.rotate_secret_token_and_save after the new token is persisted, so
-# dependent stores (e.g. the conversations signing secret) can stay in sync without
-# core importing product models. Receives `team` with the new token already saved.
+# Sent by Team.rotate_secret_token_and_save inside the rotation's transaction, after
+# save() and before commit, so dependent stores (e.g. the conversations signing secret)
+# can stay in sync without core importing product models. An exception from any
+# receiver rolls the rotation back. Work outside the database belongs in on_commit.
secret_api_token_rotated = Signal()
diff --git a/posthog/models/team/team.py b/posthog/models/team/team.py
index 7f8ffa4b30ff..013ad95ef2e7 100644
--- a/posthog/models/team/team.py
+++ b/posthog/models/team/team.py
@@ -983,9 +983,20 @@ class Team(UUIDTClassicModel):
old_primary_token = self.secret_api_token
new_token = generate_random_token_secret()
expired_token = self.secret_api_token_backup
- self.secret_api_token = new_token
- self.secret_api_token_backup = old_primary_token
- self.save()
+ # One transaction with the signal receivers: the conversations signing secret must
+ # never diverge from the column, so a failed copy rolls the rotation back whole.
+ try:
+ with transaction.atomic():
+ self.secret_api_token = new_token
+ self.secret_api_token_backup = old_primary_token
+ self.save()
+ secret_api_token_rotated.send(sender=self.__class__, team=self)
+ except Exception:
+ # save() already cached this team (post_save) with the new tokens, which the
+ # rollback discarded. Rewrite that entry from the committed row.
+ self.refresh_from_db(fields=["secret_api_token", "secret_api_token_backup"])
+ set_team_in_cache(self.api_token, self)
+ raise
set_team_in_cache(new_token, self)
# Old token needs to continue to work until it's deleted.
@@ -995,8 +1006,6 @@ class Team(UUIDTClassicModel):
# Clear the previous backup token from cache since it's being replaced
set_team_in_cache(expired_token, None)
- secret_api_token_rotated.send(sender=self.__class__, team=self)
-
# Build up the changes.
masked_old_primary_token = mask_key_value(old_primary_token) if old_primary_token else None
diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.py
index 21b73d07bb43..16f7a67761ee 100644
--- a/products/conversations/backend/signals.py
+++ b/products/conversations/backend/signals.py
@@ -605,11 +605,7 @@ def post_github_reply_on_team_message(sender, instance: Comment, created: bool,
def sync_signing_secret_on_rotation(sender, team, **kwargs):
"""Mirror the rotated legacy token into the conversations signing secret.
- Never breaks rotation: while both stores exist, widget identity verification
- falls back to the legacy token, so a failed sync degrades to current behavior.
+ Runs inside the rotation's transaction (Team.rotate_secret_token_and_save), so a
+ failure here rolls the whole rotation back: the two stores can never diverge.
"""
- try:
- SigningSecret.objects.for_team(team.id).update_or_create(team=team, defaults={"secret": team.secret_api_token})
- except Exception as e:
- logger.exception("conversations_signing_secret_sync_failed", team_id=team.id)
- capture_exception(e)
+ SigningSecret.objects.for_team(team.id).update_or_create(team=team, defaults={"secret": team.secret_api_token})
diff --git a/products/conversations/backend/tests/test_signing_secret.py b/products/conversations/backend/tests/test_signing_secret.py
index c4923d9fa8b7..2b522916f4b6 100644
--- a/products/conversations/backend/tests/test_signing_secret.py
+++ b/products/conversations/backend/tests/test_signing_secret.py
@@ -1,8 +1,12 @@
from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.db import OperationalError
from parameterized import parameterized
from posthog.models.team import Team
+from posthog.models.team.team_caching import get_team_in_cache
from products.conversations.backend.models import SigningSecret
@@ -30,6 +34,31 @@ class TestSigningSecret(BaseTest):
self.assertEqual(row.secret, self.team.secret_api_token)
self.assertEqual(SigningSecret.objects.for_team(self.team.id).count(), 1)
+ def test_failed_signing_secret_write_rolls_the_rotation_back(self):
+ # The two stores must never diverge: if the signing-secret copy fails, the
+ # legacy column must keep its old value instead of rotating alone.
+ self.team.secret_api_token = "phs_previous_secret"
+ self.team.secret_api_token_backup = "phs_expired_backup"
+ self.team.save()
+ SigningSecret.objects.for_team(self.team.id).update_or_create(
+ team=self.team, defaults={"secret": "phs_previous_secret"}
+ )
+
+ with patch.object(SigningSecret.objects, "for_team", side_effect=OperationalError("connection lost")):
+ with self.assertRaises(OperationalError):
+ self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)
+
+ self.team.refresh_from_db()
+ self.assertEqual(self.team.secret_api_token, "phs_previous_secret")
+ self.assertEqual(self.team.secret_api_token_backup, "phs_expired_backup")
+ self.assertEqual(SigningSecret.objects.for_team(self.team.id).get().secret, "phs_previous_secret")
+ # The post_save hook cached the team mid-transaction; the failure path must
+ # rewrite that entry so the cache never holds the rolled-back tokens.
+ cached = get_team_in_cache(self.team.api_token)
+ assert cached is not None
+ self.assertEqual(cached.secret_api_token, "phs_previous_secret")
+ self.assertEqual(cached.secret_api_token_backup, "phs_expired_backup")
+
def test_child_environment_keeps_its_own_team_on_save(self):
# Environment-scoped by design: a canonicalizing save() (RootTeamMixin) would rewrite
# the child's row to the parent team, sharing one secret across sibling environments