: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
feat(conversations): verify identity against signing secret (#76821)
Patricio02ce77b9c64a
diff --git a/products/conversations/backend/api/serializers.py b/products/conversations/backend/api/serializers.pyindex a047c79b44af..75a5834de649 100644--- a/products/conversations/backend/api/serializers.py+++ b/products/conversations/backend/api/serializers.py@@ -54,11 +54,12 @@ class WidgetAuthSerializer(serializers.Serializer):identity_distinct_id = serializers.CharField(required=False, max_length=400, help_text="Verified distinct_id (requires identity_hash)")- identity_hash = serializers.CharField(+ # Hex charset enforced here, not just the length: hmac.compare_digest raises TypeError+ # on non-ASCII str, which would surface as a 500 instead of a rejected request.+ identity_hash = serializers.RegexField(+ r"^[0-9a-f]{64}$",required=False,- min_length=64,- max_length=64,- help_text="HMAC-SHA256 of identity_distinct_id using team secret_api_token",+ help_text="HMAC-SHA256 of identity_distinct_id using the team's signing secret",)def validate(self, data):diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.pyindex 18c656654775..4f2697d13d1d 100644--- a/products/conversations/backend/api/tests/test_widget.py+++ b/products/conversations/backend/api/tests/test_widget.py@@ -12,11 +12,21 @@ from rest_framework.test import APIClientfrom posthog.models.comment import Commentfrom products.conversations.backend.api.serializers import WidgetMessageSerializer-from products.conversations.backend.models import Ticket+from products.conversations.backend.models import SigningSecret, Ticketfrom products.conversations.backend.models.constants import ChannelDetail, Statusfrom products.conversations.backend.services.identity import compute_identity_hash+def _verification_counter(outcome: str, source: str) -> float:+ # Process-global, so callers compare deltas rather than absolute values.+ from prometheus_client import REGISTRY++ return (+ REGISTRY.get_sample_value("conversations_identity_verification_total", {"outcome": outcome, "source": source})+ or 0.0+ )++class TestWidgetAPI(BaseTest):def setUp(self):super().setUp()@@ -662,6 +672,95 @@ class TestWidgetIdentityVerification(BaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["count"], 1)+ @parameterized.expand(+ [+ # Post-cutover state: with the legacy column gone, the signing secret alone has+ # to verify. Not reachable in production yet, so this locks in the end state.+ ("signing_secret_only", True, False),+ # A stale row (rotation sync missed) must fall back to the legacy token rather+ # than locking the team out.+ ("stale_signing_secret_falls_back_to_legacy", False, True),+ ]+ )+ def test_list_tickets_verifies_against_signing_secret(self, _name, row_matches_hash, has_legacy_token):+ SigningSecret.objects.for_team(self.team.id).create(+ team=self.team,+ secret=self.secret if row_matches_hash else "a_stale_secret",+ )+ self.team.secret_api_token = self.secret if has_legacy_token else None+ self.team.save()+ self._create_ticket()++ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ },+ **self._get_headers(),+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 1)++ def test_list_tickets_post_backfill_reports_the_signing_secret_as_the_source(self):+ # After the backfill both stores hold the same value, so the response is 200 either+ # way and only the counter shows which one matched. Without this, reordering the+ # candidates to put legacy first keeps the suite green while the drift metric —+ # what gates dropping the plaintext column — silently reports legacy forever.+ SigningSecret.objects.for_team(self.team.id).create(team=self.team, secret=self.secret)+ self._create_ticket()+ before_signing = _verification_counter("verified", "signing_secret")+ before_legacy = _verification_counter("verified", "legacy_token")++ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ },+ **self._get_headers(),+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(_verification_counter("verified", "signing_secret") - before_signing, 1.0)+ self.assertEqual(_verification_counter("verified", "legacy_token") - before_legacy, 0.0)++ def test_list_tickets_non_hex_identity_hash_is_rejected_not_a_server_error(self):+ # hmac.compare_digest raises TypeError on non-ASCII str, so a 64-character non-hex+ # hash used to reach it and surface as a 500 on a publicly reachable endpoint.+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": "é" * 64,+ },+ **self._get_headers(),+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_list_tickets_stale_signing_secret_cannot_resurrect_revoked_key(self):+ # Rotating and then deleting the backup revokes the old key. If a rotation sync+ # didn't land, the signing secret row still holds that key — accepting it would+ # keep a revoked key signing identities indefinitely.+ SigningSecret.objects.for_team(self.team.id).create(team=self.team, secret=self.secret)+ self.team.secret_api_token = "rotated_new_secret"+ self.team.secret_api_token_backup = None+ self.team.save()+ self._create_ticket()++ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ },+ **self._get_headers(),+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+def test_list_tickets_invalid_hash_returns_forbidden(self):self._create_ticket()response = self.client.get(diff --git a/products/conversations/backend/api/widget.py b/products/conversations/backend/api/widget.pyindex 93729d7c7f87..6721d1abc43a 100644--- a/products/conversations/backend/api/widget.py+++ b/products/conversations/backend/api/widget.py@@ -16,6 +16,7 @@ import loggingfrom django.db.models import F, Q+from prometheus_client import Counterfrom rest_framework import serializers, statusfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.permissions import AllowAny@@ -47,12 +48,23 @@ from products.conversations.backend.cache import (set_cached_messages,set_cached_tickets,)-from products.conversations.backend.models import Ticket+from products.conversations.backend.models import SigningSecret, Ticketfrom products.conversations.backend.models.constants import ChannelDetailfrom products.conversations.backend.services.identity import verify_identity_hashlogger = logging.getLogger(__name__)+IDENTITY_VERIFICATION_COUNTER = Counter(+ "conversations_identity_verification_total",+ "Widget identity verification attempts by outcome and which stored secret matched",+ labelnames=["outcome", "source"],+)++SIGNING_SECRET_STALE_COUNTER = Counter(+ "conversations_signing_secret_stale_total",+ "Signing secret rows skipped because they do not match the team's current secret API token",+)+class IdentityVerificationFailed(Exception):"""Raised when identity fields are present but HMAC verification fails."""@@ -69,9 +81,42 @@ class IdentityVerificationNotConfigured(IdentityVerificationFailed):# the specific reason is logged server-side for the team's own admins to see.+def _identity_secrets(team: Team) -> list[tuple[str, str]]:+ """(source, secret) pairs to verify a hash against, preferred store first.++ The conversations signing secret is where this credential is moving; the legacy+ Team.secret_api_token stays a fallback so teams that predate the backfill keep+ verifying. The rotation backup is accepted too, so hashes signed with the previous+ secret survive a rotation.++ While the legacy column exists it remains the revocation authority: rotating and then+ deleting the backup has to actually revoke the old key. The row is compared against the+ current secret API token only — a row still holding the previous key matches the rotation+ backup, so counting that as agreement would report a team whose sync failed as fully+ migrated. Verification is unaffected: such a row still verifies via `legacy_backup`.+ """+ legacy_secrets: list[tuple[str, str]] = []+ if team.secret_api_token:+ legacy_secrets.append(("legacy_token", team.secret_api_token))+ if team.secret_api_token_backup:+ legacy_secrets.append(("legacy_backup", team.secret_api_token_backup))++ secrets: list[tuple[str, str]] = []+ signing_secret = SigningSecret.objects.for_team(team.id).first()+ if signing_secret and signing_secret.secret:+ if not legacy_secrets or signing_secret.secret == team.secret_api_token:+ secrets.append(("signing_secret", signing_secret.secret))+ else:+ SIGNING_SECRET_STALE_COUNTER.inc()+ logger.warning("Conversations signing secret is stale, skipping it", extra={"team_id": team.id})++ return secrets + legacy_secrets++def _verify_identity(data: dict, team: Team) -> str | None:"""- Verify HMAC identity fields against the team's secret API token.+ Verify HMAC identity fields against the team's signing secret, falling back to the+ legacy secret API token and its rotation backup.Returns the verified distinct_id, or None if identity fields not present.Raises IdentityVerificationFailed if identity was attempted but failed."""@@ -80,20 +125,22 @@ def _verify_identity(data: dict, team: Team) -> str | None:if not distinct_id or not hash_value:return None- if not team.secret_api_token:- logger.warning("Identity verification attempted but team has no secret_api_token")- raise IdentityVerificationNotConfigured("Team has no secret_api_token")-- # Accept the backup token during rotation so in-flight verified sessions keep working,- # matching the external API's grace period (external.py checks both tokens too).- tokens = [team.secret_api_token]- if team.secret_api_token_backup:- tokens.append(team.secret_api_token_backup)+ secrets = _identity_secrets(team)+ if not secrets:+ logger.warning(+ "Identity verification attempted but team has no signing secret or legacy token",+ extra={"team_id": team.id},+ )+ IDENTITY_VERIFICATION_COUNTER.labels(outcome="not_configured", source="none").inc()+ raise IdentityVerificationNotConfigured("Team has no signing secret")- if not any(verify_identity_hash(distinct_id, hash_value, token) for token in tokens):- raise IdentityVerificationFailed("Invalid identity hash")+ for source, secret in secrets:+ if verify_identity_hash(distinct_id, hash_value, secret):+ IDENTITY_VERIFICATION_COUNTER.labels(outcome="verified", source=source).inc()+ return distinct_id- return distinct_id+ IDENTITY_VERIFICATION_COUNTER.labels(outcome="invalid_hash", source="none").inc()+ raise IdentityVerificationFailed("Invalid identity hash")class WidgetMessageView(APIView):