: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): sign identity claims to bridge email tickets (#93138)
Alex V9fa97000ace3
diff --git a/frontend/src/globals.d.ts b/frontend/src/globals.d.tsindex b54c652fdbb0..0680e6dea357 100644--- a/frontend/src/globals.d.ts+++ b/frontend/src/globals.d.ts@@ -35,6 +35,7 @@ declare global {JS_POSTHOG_SELF_CAPTURE?: booleanJS_POSTHOG_IDENTITY_DISTINCT_ID?: stringJS_POSTHOG_IDENTITY_HASH?: string+ JS_POSTHOG_IDENTITY_CLAIMS?: Record<string, { value: string; hash: string; expires_at: number }>JS_CAPTURE_TIME_TO_SEE_DATA?: booleanposthog?: posthogESBUILD_LOAD_SCRIPT: (name) => voiddiff --git a/posthog/templates/head.html b/posthog/templates/head.htmlindex 41cb1d084b1e..09295ad64d1d 100644--- a/posthog/templates/head.html+++ b/posthog/templates/head.html@@ -39,6 +39,9 @@{% if js_posthog_identity_distinct_id %}window.JS_POSTHOG_IDENTITY_DISTINCT_ID = "{{ js_posthog_identity_distinct_id|escapejs }}";window.JS_POSTHOG_IDENTITY_HASH = "{{ js_posthog_identity_hash|escapejs }}";+ {% if js_posthog_identity_claims %}+ window.JS_POSTHOG_IDENTITY_CLAIMS = JSON.parse("{{ js_posthog_identity_claims|escapejs }}");+ {% endif %}{% endif %}</script>{% endif %}diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.pyindex 45d8c2d5a7ab..92d6a9648a95 100644--- a/posthog/test/test_get_context_for_template.py+++ b/posthog/test/test_get_context_for_template.py@@ -1,4 +1,5 @@import json+import timefrom posthog.test.base import APIBaseTestfrom unittest import mock@@ -14,6 +15,8 @@ from parameterized import parameterizedfrom posthog.models import UserHomeSettingsfrom posthog.utils import get_context_for_template+from products.conversations.backend.services.identity import IDENTITY_CLAIM_MAX_AGE_SECONDS+class TestGetContextForTemplate(APIBaseTest):def test_get_context_for_template(self):@@ -90,3 +93,30 @@ class TestGetContextForTemplate(APIBaseTest):actual = get_context_for_template("index.html", request)assert actual["boot_theme"] == expected++ @parameterized.expand(+ [+ ("verified", True, True),+ ("unverified", False, False),+ ("legacy_unknown", None, False),+ ]+ )+ def test_only_verified_email_is_signed_as_identity_claim(self, _name, verification_state, expects_claim):+ self.user.is_email_verified = verification_state+ self.user.save(update_fields=["is_email_verified"])+ request = RequestFactory().get("/")+ SessionMiddleware(lambda _request: HttpResponse()).process_request(request)+ request.user = self.user++ with mock.patch(+ "posthog.models.instance_setting.get_instance_setting",+ return_value="test-conversations-secret",+ ):+ context = get_context_for_template("index.html", request)++ assert ("js_posthog_identity_claims" in context) is expects_claim+ if expects_claim:+ claims = json.loads(context["js_posthog_identity_claims"])+ assert claims["email"]["value"] == self.user.email.lower()+ current_time = int(time.time())+ assert current_time < claims["email"]["expires_at"] <= current_time + IDENTITY_CLAIM_MAX_AGE_SECONDSdiff --git a/posthog/utils.py b/posthog/utils.pyindex 24e2377dbb0e..cf428d4d426c 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -749,7 +749,12 @@ def _build_template_context(support_secret = get_instance_setting("CONVERSATIONS_HMAC_SIGNING_SECRET")if support_secret:- from products.conversations.backend.services.identity import compute_identity_hash+ from products.conversations.backend.services.identity import (+ IDENTITY_CLAIM_MAX_AGE_SECONDS,+ canonicalize_claim_value,+ compute_identity_claim_hash,+ compute_identity_hash,+ )context["js_posthog_identity_distinct_id"] = posthog_distinct_idcontext["js_posthog_identity_hash"] = compute_identity_hash(@@ -757,6 +762,33 @@ def _build_template_context(support_secret,)+ # Sign the logged-in user's verified email as a claim bound to their distinct_id.+ # The widget backend trusts this attested email to bridge tickets keyed on an email+ # string (Slack, email, Zendesk), instead of the mutable person.properties.email.+ user_email = None+ if request.user and request.user.is_authenticated:+ identity_user = cast("User", request.user)+ if identity_user.is_email_verified is True:+ user_email = identity_user.email+ if user_email:+ canonical_email = canonicalize_claim_value("email", user_email)+ expires_at = int(time.time()) + IDENTITY_CLAIM_MAX_AGE_SECONDS+ context["js_posthog_identity_claims"] = json.dumps(+ {+ "email": {+ "value": canonical_email,+ "expires_at": expires_at,+ "hash": compute_identity_claim_hash(+ posthog_distinct_id,+ "email",+ canonical_email,+ support_secret,+ expires_at=expires_at,+ ),+ }+ }+ )+return contextdiff --git a/products/conversations/backend/api/serializers.py b/products/conversations/backend/api/serializers.pyindex 35a4dbf7b858..f0620da604de 100644--- a/products/conversations/backend/api/serializers.py+++ b/products/conversations/backend/api/serializers.py@@ -61,6 +61,22 @@ class WidgetAuthSerializer(serializers.Serializer):required=False,help_text="HMAC-SHA256 of identity_distinct_id using the team's signing secret",)+ # EmailField bounds the value before SQL matching. The hash binds its identity and expiry.+ identity_email = serializers.EmailField(+ required=False,+ max_length=254,+ help_text="Verified email claim (requires identity_hash_email)",+ )+ identity_hash_email = serializers.RegexField(+ r"^[0-9a-f]{64}$",+ required=False,+ help_text="HMAC-SHA256 email claim bound to identity_distinct_id and identity_exp_email",+ )+ identity_exp_email = serializers.IntegerField(+ required=False,+ min_value=1,+ help_text="Unix timestamp when the signed email claim expires",+ )def validate(self, data):has_session = "widget_session_id" in data@@ -69,6 +85,13 @@ class WidgetAuthSerializer(serializers.Serializer):raise serializers.ValidationError("Either widget_session_id or both identity_distinct_id and identity_hash are required")+ has_email = "identity_email" in data+ has_email_hash = "identity_hash_email" in data+ has_email_expiry = "identity_exp_email" in data+ if has_email != has_email_hash:+ raise serializers.ValidationError("Send identity_email and identity_hash_email together.")+ if has_email_expiry and (not has_email or not has_identity):+ raise serializers.ValidationError("Send identity_exp_email with the email claim and base identity fields.")return datadiff --git a/products/conversations/backend/api/tests/test_cache.py b/products/conversations/backend/api/tests/test_cache.pyindex 6849f5e891e1..2185609f8bc2 100644--- a/products/conversations/backend/api/tests/test_cache.py+++ b/products/conversations/backend/api/tests/test_cache.py@@ -1,6 +1,7 @@from unittest.mock import patch-from django.test import TestCase+from django.core.cache import cache+from django.test import SimpleTestCase, TestCasefrom products.conversations.backend.cache import (MESSAGES_CACHE_TTL,@@ -9,9 +10,11 @@ from products.conversations.backend.cache import (get_cached_messages,get_cached_tickets,get_cached_unread_count,+ get_identity_tickets_cache_namespace,get_messages_cache_key,get_tickets_cache_key,get_unread_count_cache_key,+ invalidate_identity_tickets_cache,invalidate_messages_cache,invalidate_tickets_cache,invalidate_unread_count_cache,@@ -21,6 +24,22 @@ from products.conversations.backend.cache import ()+class TestIdentityTicketsCacheNamespace(SimpleTestCase):+ def setUp(self):+ cache.clear()++ def test_invalidation_rotates_namespace(self):+ initial_namespace = get_identity_tickets_cache_namespace(team_id=1)++ invalidate_identity_tickets_cache(team_id=1)++ assert get_identity_tickets_cache_namespace(team_id=1) != initial_namespace++ @patch("products.conversations.backend.cache.cache.get", side_effect=Exception("Redis error"))+ def test_lookup_failure_disables_cache(self, _mock_get):+ assert get_identity_tickets_cache_namespace(team_id=1) is None++class TestCacheKeyGeneration(TestCase):def test_messages_cache_key_without_after(self):key = get_messages_cache_key(team_id=1, ticket_id="abc-123")diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.pyindex 79af5e6cae19..98ca950a0363 100644--- a/products/conversations/backend/api/tests/test_widget.py+++ b/products/conversations/backend/api/tests/test_widget.py@@ -1,3 +1,4 @@+import timeimport uuidfrom posthog.test.base import BaseTest@@ -13,10 +14,14 @@ from rest_framework.test import APIClientfrom posthog.models.comment import Commentfrom posthog.rate_limit import WidgetTeamPollThrottle-from products.conversations.backend.api.serializers import WidgetMessageSerializer+from products.conversations.backend.api.serializers import WidgetMessageSerializer, WidgetTicketsQuerySerializerfrom products.conversations.backend.models import SigningSecret, Ticket-from products.conversations.backend.models.constants import ChannelDetail, Status-from products.conversations.backend.services.identity import compute_identity_hash+from products.conversations.backend.models.constants import Channel, ChannelDetail, Status+from products.conversations.backend.services.identity import (+ IDENTITY_CLAIM_MAX_AGE_SECONDS,+ compute_identity_claim_hash,+ compute_identity_hash,+)def _verification_counter(outcome: str, source: str) -> float:@@ -668,6 +673,7 @@ class TestWidgetIdentityVerification(BaseTest):self.identity_hash = compute_identity_hash(self.distinct_id, self.secret)self.widget_session_id = str(uuid.uuid4())+ cache.clear()self.client = APIClient()def _get_headers(self):@@ -844,6 +850,354 @@ class TestWidgetIdentityVerification(BaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["count"], 1)+ # --- Email claim bridge ---++ def _email_claim(self, email, *, expires_at=None):+ if expires_at is None:+ expires_at = int(time.time()) + IDENTITY_CLAIM_MAX_AGE_SECONDS+ return {+ "identity_email": email,+ "identity_hash_email": compute_identity_claim_hash(+ self.distinct_id,+ "email",+ email,+ self.secret,+ expires_at=expires_at,+ ),+ "identity_exp_email": expires_at,+ }++ def _create_email_ticket(+ self,+ email,+ identity_verified,+ *,+ channel_source=Channel.SLACK,+ zendesk_ticket_id=None,+ unread_customer_count=0,+ ):+ return Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id=str(uuid.uuid4()),+ distinct_id=email,+ channel_source=channel_source,+ identity_verified=identity_verified,+ zendesk_ticket_id=zendesk_ticket_id,+ unread_customer_count=unread_customer_count,+ )++ def test_list_tickets_email_bridge_includes_verified_ticket(self):+ email = "[email protected]"+ self._create_email_ticket("[email protected]", identity_verified=True)+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 1)++ def test_list_tickets_email_bridge_includes_imported_ticket(self):+ email = "[email protected]"+ self._create_email_ticket(+ email,+ identity_verified=None,+ channel_source=Channel.EMAIL,+ zendesk_ticket_id=123,+ )+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 1)++ def test_list_tickets_email_bridge_ignores_unknown_legacy_widget_ticket(self):+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=None, channel_source=Channel.WIDGET)+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 0)++ def test_list_tickets_email_bridge_ignores_unverified_ticket(self):+ # identity_verified=False is attacker-controllable, so email must never bridge to it.+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=False)+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 0)++ def test_list_tickets_email_bridge_off_without_claim(self):+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=True)+ 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"], 0)++ def test_list_tickets_tampered_email_claim_is_ignored(self):+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=True)+ email_claim = self._email_claim(email)+ email_claim["identity_hash_email"] = "0" * 64+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ **email_claim,+ },+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 0)++ def test_list_tickets_expired_email_claim_is_ignored(self):+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=True)+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ **self._email_claim(email, expires_at=int(time.time()) - 1),+ },+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 0)++ def test_list_tickets_legacy_email_claim_without_expiry_is_ignored(self):+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=True)+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ "identity_email": email,+ "identity_hash_email": "0" * 64,+ },+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 0)++ def test_list_tickets_modified_email_claim_expiry_is_ignored(self):+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=True)+ email_claim = self._email_claim(email)+ email_claim["identity_exp_email"] += 1+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ **email_claim,+ },+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 0)++ def test_list_tickets_email_claim_bound_to_other_distinct_id_is_ignored(self):+ # A claim signed for a different base identity must not bridge under this viewer.+ email = "[email protected]"+ self._create_email_ticket(email, identity_verified=True)+ email_claim = self._email_claim(email)+ email_claim["identity_hash_email"] = compute_identity_claim_hash(+ "someone_else",+ "email",+ email,+ self.secret,+ expires_at=email_claim["identity_exp_email"],+ )+ response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ **email_claim,+ },+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 0)++ def test_list_tickets_cache_does_not_leak_bridged_tickets_without_claim(self):+ email = "[email protected]"+ self._create_ticket()+ self._create_email_ticket(email, identity_verified=True)++ claimed_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ unclaimed_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(claimed_response.json()["count"], 2)+ self.assertEqual(unclaimed_response.json()["count"], 1)++ def test_list_tickets_cache_does_not_hide_bridge_after_unclaimed_request(self):+ email = "[email protected]"+ self._create_ticket()+ self._create_email_ticket(email, identity_verified=True)++ unclaimed_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash},+ **self._get_headers(),+ )+ claimed_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )++ self.assertEqual(unclaimed_response.json()["count"], 1)+ self.assertEqual(claimed_response.json()["count"], 2)++ @parameterized.expand([("direct_identity", False), ("email_claim", True)])+ def test_new_message_invalidates_identity_ticket_cache(self, _name, use_email_claim):+ email = "[email protected]"+ ticket = self._create_email_ticket(email, identity_verified=True) if use_email_claim else self._create_ticket()+ query = {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ }+ if use_email_claim:+ query.update(self._email_claim(email))++ initial_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ query,+ **self._get_headers(),+ )+ self.assertEqual(initial_response.status_code, status.HTTP_200_OK)+ self.assertEqual(initial_response.json()["results"][0]["unread_count"], 0)++ with self.captureOnCommitCallbacks(execute=True):+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Agent reply",+ created_by=self.user,+ item_context={"author_type": "team", "is_private": False},+ )++ updated_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ query,+ **self._get_headers(),+ )+ self.assertEqual(updated_response.status_code, status.HTTP_200_OK)+ self.assertEqual(updated_response.json()["results"][0]["unread_count"], 1)+ self.assertEqual(updated_response.json()["results"][0]["last_message"], "Agent reply")++ def test_get_messages_email_bridge_allows_verified_ticket(self):+ email = "[email protected]"+ ticket = self._create_email_ticket("[email protected]", identity_verified=True)+ response = self.client.get(+ f"/api/conversations/v1/widget/messages/{ticket.id}",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ def test_get_messages_email_bridge_denies_unverified_ticket(self):+ email = "[email protected]"+ ticket = self._create_email_ticket(email, identity_verified=False)+ response = self.client.get(+ f"/api/conversations/v1/widget/messages/{ticket.id}",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_email_bridge_list_and_detail_reject_whitespace_padded_ticket_identity(self):+ email = "[email protected]"+ ticket = self._create_email_ticket(f" {email} ", identity_verified=True)++ list_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )+ detail_response = self.client.get(+ f"/api/conversations/v1/widget/messages/{ticket.id}",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ **self._get_headers(),+ )++ self.assertEqual(list_response.json()["count"], 0)+ self.assertEqual(detail_response.status_code, status.HTTP_403_FORBIDDEN)++ @parameterized.expand(+ [+ ("zendesk", None, Channel.EMAIL, 123),+ ("slack", True, Channel.SLACK, None),+ ]+ )+ def test_send_message_to_bridged_ticket_preserves_channel_identity(+ self, _name, identity_verified, channel_source, zendesk_ticket_id+ ):+ email = "[email protected]"+ ticket = self._create_email_ticket(+ email,+ identity_verified=identity_verified,+ channel_source=channel_source,+ zendesk_ticket_id=zendesk_ticket_id,+ )+ response = self.client.post(+ "/api/conversations/v1/widget/message",+ {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ **self._email_claim(email),+ "message": "Follow-up",+ "ticket_id": str(ticket.id),+ },+ **self._get_headers(),+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ ticket.refresh_from_db()+ self.assertEqual(ticket.distinct_id, email)+ self.assertEqual(ticket.identity_verified, identity_verified)++ def test_mark_read_email_bridge_allows_verified_ticket(self):+ email = "[email protected]"+ ticket = self._create_email_ticket(email, identity_verified=True, unread_customer_count=1)++ response = self.client.post(+ f"/api/conversations/v1/widget/messages/{ticket.id}/read",+ {"identity_distinct_id": self.distinct_id, "identity_hash": self.identity_hash, **self._email_claim(email)},+ format="json",+ **self._get_headers(),+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ ticket.refresh_from_db()+ self.assertEqual(ticket.unread_customer_count, 0)+def test_cross_browser_same_tickets(self):other_session = str(uuid.uuid4())self._create_ticket(widget_session_id=other_session)@@ -1018,18 +1372,32 @@ class TestWidgetIdentityVerification(BaseTest):ticket = self._create_ticket()ticket.unread_customer_count = 3ticket.save()+ identity = {+ "identity_distinct_id": self.distinct_id,+ "identity_hash": self.identity_hash,+ }++ cached_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ identity,+ **self._get_headers(),+ )+ self.assertEqual(cached_response.json()["results"][0]["unread_count"], 3)response = self.client.post(f"/api/conversations/v1/widget/messages/{ticket.id}/read",- {- "identity_distinct_id": self.distinct_id,- "identity_hash": self.identity_hash,- },+ identity,**self._get_headers(),)self.assertEqual(response.status_code, status.HTTP_200_OK)ticket.refresh_from_db()self.assertEqual(ticket.unread_customer_count, 0)+ updated_response = self.client.get(+ "/api/conversations/v1/widget/tickets",+ identity,+ **self._get_headers(),+ )+ self.assertEqual(updated_response.json()["results"][0]["unread_count"], 0)def test_mark_read_invalid_hash_no_session_returns_forbidden(self):ticket = self._create_ticket()@@ -1059,6 +1427,57 @@ class TestWidgetIdentityVerification(BaseTest):self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+class TestWidgetAuthSerializer(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "email_without_hash",+ {+ "identity_distinct_id": "user_123",+ "identity_hash": "a" * 64,+ "identity_email": "[email protected]",+ "identity_exp_email": int(time.time()) + IDENTITY_CLAIM_MAX_AGE_SECONDS,+ },+ ),+ (+ "hash_without_email",+ {+ "identity_distinct_id": "user_123",+ "identity_hash": "a" * 64,+ "identity_hash_email": "b" * 64,+ "identity_exp_email": int(time.time()) + IDENTITY_CLAIM_MAX_AGE_SECONDS,+ },+ ),+ (+ "claim_without_base_identity",+ {+ "widget_session_id": str(uuid.uuid4()),+ "identity_email": "[email protected]",+ "identity_hash_email": "b" * 64,+ "identity_exp_email": int(time.time()) + IDENTITY_CLAIM_MAX_AGE_SECONDS,+ },+ ),+ ]+ )+ def test_email_claim_requires_complete_base_and_claim_triplet(self, _name, payload):+ serializer = WidgetTicketsQuerySerializer(data=payload)++ self.assertFalse(serializer.is_valid())+ self.assertIn("non_field_errors", serializer.errors)++ def test_legacy_email_claim_pair_is_accepted(self):+ serializer = WidgetTicketsQuerySerializer(+ data={+ "identity_distinct_id": "user_123",+ "identity_hash": "a" * 64,+ "identity_email": "[email protected]",+ "identity_hash_email": "b" * 64,+ }+ )++ self.assertTrue(serializer.is_valid(), serializer.errors)++class TestWidgetContextSanitization(SimpleTestCase):def _serializer(self, **overrides):return WidgetMessageSerializer(diff --git a/products/conversations/backend/api/widget.py b/products/conversations/backend/api/widget.pyindex 01c61e8e1011..a213b55c8abd 100644--- a/products/conversations/backend/api/widget.py+++ b/products/conversations/backend/api/widget.py@@ -12,7 +12,10 @@ Anonymous users are controlled by widget_session_id. Verified users are controll"""import uuid+import hashlibimport logging+from dataclasses import field as dataclass_field+from typing import Literalfrom django.db.models import F, Q@@ -25,6 +28,7 @@ from rest_framework.response import Responsefrom rest_framework.views import APIViewfrom posthog.auth import WidgetAuthentication+from posthog.dataclasses import frozenfrom posthog.event_usage import report_team_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team@@ -42,7 +46,9 @@ from products.conversations.backend.api.serializers import (from products.conversations.backend.cache import (get_cached_messages,get_cached_tickets,+ get_identity_tickets_cache_namespace,get_person_distinct_ids,+ invalidate_identity_tickets_cache,invalidate_tickets_cache,invalidate_unread_count_cache,set_cached_messages,@@ -50,10 +56,25 @@ from products.conversations.backend.cache import ()from products.conversations.backend.models import SigningSecret, Ticketfrom products.conversations.backend.models.constants import ChannelDetail-from products.conversations.backend.services.identity import verify_identity_hash+from products.conversations.backend.services.identity import (+ canonicalize_claim_value,+ identity_claim_has_expired,+ verify_identity_claim_hash,+ verify_identity_hash,+)logger = logging.getLogger(__name__)+IdentityClaimField = Literal["email"]+TicketOwnershipMatch = Literal["distinct_id", "email"]+++@frozen+class _IdentitySecret:+ source: Literal["signing_secret", "legacy_token", "legacy_backup"]+ secret: str = dataclass_field(repr=False)++IDENTITY_VERIFICATION_COUNTER = Counter("conversations_identity_verification_total","Widget identity verification attempts by outcome and which stored secret matched",@@ -81,8 +102,8 @@ 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.+def _identity_secrets(team: Team) -> list[_IdentitySecret]:+ """Credentials to verify a hash against, preferred store first.The conversations signing secret is where this credential is moving; the legacyTeam.secret_api_token stays a fallback so teams that predate the backfill keep@@ -95,17 +116,17 @@ def _identity_secrets(team: Team) -> list[tuple[str, str]]:backup, so counting that as agreement would report a team whose sync failed as fullymigrated. Verification is unaffected: such a row still verifies via `legacy_backup`."""- legacy_secrets: list[tuple[str, str]] = []+ legacy_secrets: list[_IdentitySecret] = []if team.secret_api_token:- legacy_secrets.append(("legacy_token", team.secret_api_token))+ legacy_secrets.append(_IdentitySecret(source="legacy_token", secret=team.secret_api_token))if team.secret_api_token_backup:- legacy_secrets.append(("legacy_backup", team.secret_api_token_backup))+ legacy_secrets.append(_IdentitySecret(source="legacy_backup", secret=team.secret_api_token_backup))- secrets: list[tuple[str, str]] = []+ secrets: list[_IdentitySecret] = []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))+ secrets.append(_IdentitySecret(source="signing_secret", secret=signing_secret.secret))else:SIGNING_SECRET_STALE_COUNTER.inc()logger.warning("Conversations signing secret is stale, skipping it", extra={"team_id": team.id})@@ -113,20 +134,31 @@ def _identity_secrets(team: Team) -> list[tuple[str, str]]:return secrets + legacy_secrets-def _verify_identity(data: dict, team: Team) -> str | None:+def _request_identity_secrets(data: dict, team: Team) -> list[_IdentitySecret] | None:+ if not data.get("identity_distinct_id") or not data.get("identity_hash"):+ return None+ return _identity_secrets(team)+++def _verify_identity(+ data: dict,+ team: Team,+ secrets: list[_IdentitySecret] | None = None,+) -> str | None:"""Verify HMAC identity fields against the team's signing secret, falling back to thelegacy 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.+ An explicit empty secrets list means no credential is configured; None resolves it here."""distinct_id = data.get("identity_distinct_id")hash_value = data.get("identity_hash")if not distinct_id or not hash_value:return None- secrets = _identity_secrets(team)- if not secrets:+ resolved_secrets = secrets if secrets is not None else _identity_secrets(team)+ if not resolved_secrets:logger.warning("Identity verification attempted but team has no signing secret or legacy token",extra={"team_id": team.id},@@ -134,15 +166,115 @@ def _verify_identity(data: dict, team: Team) -> str | None:IDENTITY_VERIFICATION_COUNTER.labels(outcome="not_configured", source="none").inc()raise IdentityVerificationNotConfigured("Team has no signing secret")- for source, secret in secrets:- if verify_identity_hash(distinct_id, hash_value, secret):- IDENTITY_VERIFICATION_COUNTER.labels(outcome="verified", source=source).inc()+ for identity_secret in resolved_secrets:+ if verify_identity_hash(distinct_id, hash_value, identity_secret.secret):+ IDENTITY_VERIFICATION_COUNTER.labels(outcome="verified", source=identity_secret.source).inc()return distinct_idIDENTITY_VERIFICATION_COUNTER.labels(outcome="invalid_hash", source="none").inc()raise IdentityVerificationFailed("Invalid identity hash")+def _verify_identity_claim(+ data: dict,+ team: Team,+ verified_distinct_id: str,+ *,+ field: IdentityClaimField = "email",+ secrets: list[_IdentitySecret] | None = None,+) -> str | None:+ """Verify a signed identity claim for one named field, returning its canonical value.++ The claim wire format is `identity_<field>` + `identity_hash_<field>` ++ `identity_exp_<field>`. The hash uses the same secrets as the base identity and binds the+ claim to its verified distinct ID and expiry. A missing, expired, or invalid claim returns+ None so the caller falls back to distinct ID access.+ """+ value = data.get(f"identity_{field}")+ hash_value = data.get(f"identity_hash_{field}")+ expires_at = data.get(f"identity_exp_{field}")+ if not value or not hash_value or not expires_at:+ return None+ if identity_claim_has_expired(expires_at):+ IDENTITY_VERIFICATION_COUNTER.labels(outcome="claim_expired", source="none").inc()+ return None++ resolved_secrets = secrets if secrets is not None else _identity_secrets(team)+ if not resolved_secrets:+ return None++ try:+ canonical = canonicalize_claim_value(field, value)+ except ValueError:+ IDENTITY_VERIFICATION_COUNTER.labels(outcome="claim_invalid", source="none").inc()+ return None++ for identity_secret in resolved_secrets:+ if verify_identity_claim_hash(+ verified_distinct_id,+ field,+ canonical,+ hash_value,+ identity_secret.secret,+ expires_at=expires_at,+ ):+ IDENTITY_VERIFICATION_COUNTER.labels(outcome="claim_verified", source=identity_secret.source).inc()+ return canonical++ IDENTITY_VERIFICATION_COUNTER.labels(outcome="claim_invalid", source="none").inc()+ return None+++# PostHog treats Zendesk as the source of record for imported requester emails. Other NULL+# identities can be client-supplied legacy widget data and must never bridge by email.+_EMAIL_BRIDGE_TRUSTED = Q(identity_verified=True) | (+ Q(identity_verified__isnull=True) & Q(zendesk_ticket_id__isnull=False)+)+++def _identity_ticket_filter(team: Team, verified_distinct_id: str, verified_email: str | None) -> Q:+ """Q matching every ticket the verified viewer owns, across channels.++ The viewer's own person distinct_ids cover widget tickets. Other channels key the+ requester by email in distinct_id (Slack, email, Zendesk), so also match the viewer's+ attested email against server-attested tickets only. The email is a signed claim verified+ upstream, never a mutable analytics property.+ """+ all_ids = get_person_distinct_ids(team.id, verified_distinct_id)+ match = Q(distinct_id__in=all_ids)+ if verified_email:+ match |= _EMAIL_BRIDGE_TRUSTED & Q(distinct_id__iexact=verified_email)+ return match+++def _viewer_ticket_match(+ team: Team, verified_distinct_id: str, ticket: Ticket, verified_email: str | None+) -> TicketOwnershipMatch | None:+ """Return how the verified viewer owns this ticket, mirroring _identity_ticket_filter."""+ allowed_ids = get_person_distinct_ids(team.id, verified_distinct_id)+ if ticket.distinct_id in allowed_ids:+ return "distinct_id"+ if not verified_email or not ticket.distinct_id:+ return None+ is_trusted_email = ticket.identity_verified is True or (+ ticket.identity_verified is None and ticket.zendesk_ticket_id is not None+ )+ if not is_trusted_email:+ return None+ # Keep this no wider than _identity_ticket_filter's iexact lookup, which does not trim.+ if ticket.distinct_id.lower() == verified_email:+ return "email"+ return None+++def _identity_tickets_cache_key(cache_namespace: str, verified_distinct_id: str, verified_email: str | None) -> str:+ base_key = f"iv:{cache_namespace}:{verified_distinct_id}"+ if not verified_email:+ return base_key+ email_digest = hashlib.sha256(verified_email.encode()).hexdigest()+ return f"{base_key}:email:{email_digest}"++class WidgetMessageView(APIView):"""POST /api/conversations/v1/widget/message@@ -207,7 +339,8 @@ class WidgetMessageView(APIView):)try:- verified_distinct_id = _verify_identity(serializer.validated_data, team)+ identity_secrets = _request_identity_secrets(serializer.validated_data, team)+ verified_distinct_id = _verify_identity(serializer.validated_data, team, identity_secrets)except IdentityVerificationFailed as e:return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)@@ -241,9 +374,13 @@ class WidgetMessageView(APIView):try:ticket = Ticket.objects.get(id=ticket_id, team=team)+ ownership_match: TicketOwnershipMatch | None = Noneif verified_distinct_id is not None:- allowed_ids = get_person_distinct_ids(team.id, verified_distinct_id)- if ticket.distinct_id not in allowed_ids:+ verified_email = _verify_identity_claim(+ serializer.validated_data, team, verified_distinct_id, secrets=identity_secrets+ )+ ownership_match = _viewer_ticket_match(team, verified_distinct_id, ticket, verified_email)+ if ownership_match is None:return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)else:# CRITICAL: Verify ticket belongs to this widget_session_id (NOT distinct_id)@@ -252,7 +389,7 @@ class WidgetMessageView(APIView):# Only HMAC-verified requests may (re)bind a ticket's distinct_id.# Anonymous → identified continuity is still handled by person merging.- if verified_distinct_id is not None and ticket.distinct_id != distinct_id:+ if ownership_match == "distinct_id" and ticket.distinct_id != distinct_id:ticket.distinct_id = distinct_id# Update traits if provided@@ -266,7 +403,7 @@ class WidgetMessageView(APIView):ticket.session_context.update(session_context)# HMAC-verified requests are server-attested — mark the identity trusted.- if verified_distinct_id is not None:+ if ownership_match == "distinct_id":ticket.identity_verified = True# Increment unread count for team (customer sent a message)@@ -383,13 +520,16 @@ class WidgetMessagesView(APIView):# Verify ownership: identity mode uses distinct_id, legacy uses widget_session_idtry:- verified_distinct_id = _verify_identity(query_serializer.validated_data, team)+ identity_secrets = _request_identity_secrets(query_serializer.validated_data, team)+ verified_distinct_id = _verify_identity(query_serializer.validated_data, team, identity_secrets)except IdentityVerificationFailed as e:return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)if verified_distinct_id is not None:- allowed_ids = get_person_distinct_ids(team.id, verified_distinct_id)- if ticket.distinct_id not in allowed_ids:+ verified_email = _verify_identity_claim(+ query_serializer.validated_data, team, verified_distinct_id, secrets=identity_secrets+ )+ if _viewer_ticket_match(team, verified_distinct_id, ticket, verified_email) is None:return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)elif "widget_session_id" in query_serializer.validated_data:widget_session_id = str(query_serializer.validated_data["widget_session_id"])@@ -497,12 +637,22 @@ class WidgetTicketsView(APIView):)try:- verified_distinct_id = _verify_identity(query_serializer.validated_data, team)+ identity_secrets = _request_identity_secrets(query_serializer.validated_data, team)+ verified_distinct_id = _verify_identity(query_serializer.validated_data, team, identity_secrets)except IdentityVerificationFailed as e:return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)+ verified_email: str | None = Noneif verified_distinct_id is not None:- cache_key_id = f"iv:{verified_distinct_id}"+ verified_email = _verify_identity_claim(+ query_serializer.validated_data, team, verified_distinct_id, secrets=identity_secrets+ )+ cache_namespace = get_identity_tickets_cache_namespace(team.id)+ cache_key_id = (+ _identity_tickets_cache_key(cache_namespace, verified_distinct_id, verified_email)+ if cache_namespace+ else None+ )elif "widget_session_id" in query_serializer.validated_data:cache_key_id = str(query_serializer.validated_data["widget_session_id"])else:@@ -516,16 +666,17 @@ class WidgetTicketsView(APIView):# used by widget polling. Custom limit/offset must bypass the cache — its# key doesn't include limit/offset, so serving it for other page sizes# returns the wrong slice (e.g. ?limit=2 getting the full cached page back).- use_cache = offset == 0 and limit == WIDGET_TICKETS_DEFAULT_LIMIT- if use_cache:- cached = get_cached_tickets(team.id, cache_key_id, status_filter)+ cacheable_key = cache_key_id if offset == 0 and limit == WIDGET_TICKETS_DEFAULT_LIMIT else None+ if cacheable_key is not None:+ cached = get_cached_tickets(team.id, cacheable_key, status_filter)if cached is not None:return Response(cached)# Build queryif verified_distinct_id is not None:- all_ids = get_person_distinct_ids(team.id, verified_distinct_id)- tickets_query = Ticket.objects.filter(team=team, distinct_id__in=all_ids)+ tickets_query = Ticket.objects.filter(team=team).filter(+ _identity_ticket_filter(team, verified_distinct_id, verified_email)+ )else:tickets_query = Ticket.objects.filter(team=team, widget_session_id=cache_key_id)@@ -557,8 +708,8 @@ class WidgetTicketsView(APIView):response_data = {"count": total_count, "results": ticket_list}# Cache first page (skip empty results to avoid stale cache after restore/migration)- if use_cache and total_count > 0:- set_cached_tickets(team.id, cache_key_id, response_data, status_filter)+ if cacheable_key is not None and total_count > 0:+ set_cached_tickets(team.id, cacheable_key, response_data, status_filter)return Response(response_data)@@ -603,20 +754,36 @@ class WidgetMarkReadView(APIView):# Verify ownership: identity mode uses distinct_id, legacy uses widget_session_idtry:- verified_distinct_id = _verify_identity(body_serializer.validated_data, team)+ identity_secrets = _request_identity_secrets(body_serializer.validated_data, team)+ verified_distinct_id = _verify_identity(body_serializer.validated_data, team, identity_secrets)except IdentityVerificationFailed as e:return Response({"error": e.public_error}, status=status.HTTP_403_FORBIDDEN)if verified_distinct_id is not None:- allowed_ids = get_person_distinct_ids(team.id, verified_distinct_id)- if ticket.distinct_id not in allowed_ids:+ verified_email = _verify_identity_claim(+ body_serializer.validated_data, team, verified_distinct_id, secrets=identity_secrets+ )+ if _viewer_ticket_match(team, verified_distinct_id, ticket, verified_email) is None:return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)- cache_invalidation_key = f"iv:{verified_distinct_id}"+ cache_namespace = get_identity_tickets_cache_namespace(team.id)+ if cache_namespace:+ cache_invalidation_keys = [+ _identity_tickets_cache_key(cache_namespace, verified_distinct_id, verified_email)+ ]+ if verified_email:+ cache_invalidation_keys.append(+ _identity_tickets_cache_key(cache_namespace, verified_distinct_id, None)+ )+ rotate_identity_cache = False+ else:+ cache_invalidation_keys = []+ rotate_identity_cache = Trueelif "widget_session_id" in body_serializer.validated_data:widget_session_id = str(body_serializer.validated_data["widget_session_id"])if ticket.widget_session_id != widget_session_id:return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)- cache_invalidation_key = widget_session_id+ cache_invalidation_keys = [widget_session_id]+ rotate_identity_cache = Falseelse:return Response({"error": "Forbidden"}, status=status.HTTP_403_FORBIDDEN)@@ -624,6 +791,9 @@ class WidgetMarkReadView(APIView):if ticket.unread_customer_count > 0:ticket.unread_customer_count = 0ticket.save(update_fields=["unread_customer_count", "updated_at"])- invalidate_tickets_cache(team.id, cache_invalidation_key)+ if rotate_identity_cache:+ invalidate_identity_tickets_cache(team.id)+ for cache_invalidation_key in cache_invalidation_keys:+ invalidate_tickets_cache(team.id, cache_invalidation_key)return Response({"success": True, "unread_count": 0})diff --git a/products/conversations/backend/cache.py b/products/conversations/backend/cache.pyindex 3a7690066ee5..a6d171b9f8a4 100644--- a/products/conversations/backend/cache.py+++ b/products/conversations/backend/cache.py@@ -6,6 +6,7 @@ Short TTLs ensure stale data expires quickly without explicit invalidation."""import json+import uuidimport hashlibfrom collections.abc import Generatorfrom contextlib import contextmanager@@ -93,6 +94,36 @@ def set_cached_tickets(team_id: int, widget_session_id: str, response_data: dictlogger.warning("conversations_cache_set_error", key=key)+def _identity_tickets_cache_namespace_key(team_id: int) -> str:+ return _make_cache_key("identity_tickets_namespace", str(team_id))+++def get_identity_tickets_cache_namespace(team_id: int) -> str | None:+ """Return the namespace shared by identity-authenticated ticket list keys."""+ key = _identity_tickets_cache_namespace_key(team_id)+ new_namespace = uuid.uuid4().hex+ try:+ namespace = cache.get(key)+ if namespace:+ return str(namespace)+ if cache.add(key, new_namespace, timeout=None):+ return new_namespace+ namespace = cache.get(key)+ return str(namespace) if namespace else new_namespace+ except Exception:+ logger.warning("conversations_cache_get_error", key=key)+ return None+++def invalidate_identity_tickets_cache(team_id: int) -> None:+ """Rotate the namespace so all identity-authenticated ticket lists miss."""+ key = _identity_tickets_cache_namespace_key(team_id)+ try:+ cache.set(key, uuid.uuid4().hex, timeout=None)+ except Exception:+ logger.warning("conversations_cache_invalidate_error", keys=[key])++# Unread Count Cache (for dashboard nav badge)# Caches the total unread ticket count for a team.# Invalidated when: customer sends message, ticket resolved, ticket marked as read.diff --git a/products/conversations/backend/services/identity.py b/products/conversations/backend/services/identity.pyindex ca5690d0e839..50e94b59e96b 100644--- a/products/conversations/backend/services/identity.py+++ b/products/conversations/backend/services/identity.py@@ -1,5 +1,12 @@import hmac+import timeimport hashlib+from collections.abc import Callable++# NUL separates claim fields so adjacent values cannot form an ambiguous signed input.+_CLAIM_SEP = "\x00"+IDENTITY_CLAIM_MAX_AGE_SECONDS = 24 * 60 * 60+_IDENTITY_CLAIM_CLOCK_SKEW_SECONDS = 5 * 60def compute_identity_hash(distinct_id: str, secret: str) -> str:@@ -15,3 +22,87 @@ def verify_identity_hash(distinct_id: str, hash_value: str, secret: str) -> bool"""Verify an HMAC identity hash. Timing-safe."""expected = compute_identity_hash(distinct_id, secret)return hmac.compare_digest(expected, hash_value)+++def _canonicalize_email(value: str) -> str:+ return value.strip().lower()+++# Per-field rule to canonicalize a claim value before it is signed or verified. The rule runs+# identically at sign time and verify time, so the signature never depends on formatting the+# client happened to send. Keep this an explicit map: a field with no rule here cannot be+# signed or verified, which stops an unaudited claim from slipping through the generic path.+_CLAIM_CANONICALIZERS: dict[str, Callable[[str], str]] = {+ "email": _canonicalize_email,+}+++def canonicalize_claim_value(field: str, value: str) -> str:+ """Return the canonical form of a claim value for the given field.++ Raises ValueError for a field with no registered rule, so an unknown claim can never be+ signed or verified by accident.+ """+ try:+ canonicalize = _CLAIM_CANONICALIZERS[field]+ except KeyError:+ raise ValueError(f"No canonicalizer registered for identity claim field {field!r}")+ return canonicalize(value)+++def compute_identity_claim_hash(+ distinct_id: str,+ field: str,+ value: str,+ secret: str,+ *,+ expires_at: int,+ version: str = "v1",+) -> str:+ """HMAC-SHA256 over a signed identity claim.++ The signed input binds the base identity, field name, expiry, and version. This prevents+ cross-identity replay, field confusion, and indefinite reuse of a leaked claim.+ """+ canonical = canonicalize_claim_value(field, value)+ parts = [version, distinct_id, field, canonical, str(expires_at)]+ if any(_CLAIM_SEP in part for part in parts):+ raise ValueError("Identity claim parts must not contain NUL characters")+ message = _CLAIM_SEP.join(parts)+ return hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()+++def identity_claim_has_expired(expires_at: int, *, now: int | None = None) -> bool:+ current_time = int(time.time()) if now is None else now+ return expires_at <= current_time+++def verify_identity_claim_hash(+ distinct_id: str,+ field: str,+ value: str,+ hash_value: str,+ secret: str,+ *,+ expires_at: int,+ version: str = "v1",+ now: int | None = None,+) -> bool:+ """Verify a signed identity claim hash. Timing-safe."""+ current_time = int(time.time()) if now is None else now+ if identity_claim_has_expired(expires_at, now=current_time):+ return False+ if expires_at > current_time + IDENTITY_CLAIM_MAX_AGE_SECONDS + _IDENTITY_CLAIM_CLOCK_SKEW_SECONDS:+ return False+ try:+ expected = compute_identity_claim_hash(+ distinct_id,+ field,+ value,+ secret,+ expires_at=expires_at,+ version=version,+ )+ except ValueError:+ return False+ return hmac.compare_digest(expected, hash_value)diff --git a/products/conversations/backend/services/test_identity.py b/products/conversations/backend/services/test_identity.pyindex 5907356a2ae0..d9329adb0c86 100644--- a/products/conversations/backend/services/test_identity.py+++ b/products/conversations/backend/services/test_identity.py@@ -1,9 +1,16 @@-from posthog.test.base import BaseTest+from django.test import SimpleTestCase-from products.conversations.backend.services.identity import compute_identity_hash, verify_identity_hash+from products.conversations.backend.services.identity import (+ IDENTITY_CLAIM_MAX_AGE_SECONDS,+ canonicalize_claim_value,+ compute_identity_claim_hash,+ compute_identity_hash,+ verify_identity_claim_hash,+ verify_identity_hash,+)-class TestIdentityService(BaseTest):+class TestIdentityService(SimpleTestCase):def test_compute_identity_hash_deterministic(self):h1 = compute_identity_hash("user_123", "secret")h2 = compute_identity_hash("user_123", "secret")@@ -40,3 +47,109 @@ class TestIdentityService(BaseTest):h = compute_identity_hash("user_123", "secret")self.assertEqual(len(h), 64)int(h, 16) # should not raise+++class TestIdentityClaimHash(SimpleTestCase):+ def test_claim_hash_verifies(self):+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=2000)+ self.assertTrue(+ verify_identity_claim_hash("user_123", "email", "[email protected]", h, "secret", expires_at=2000, now=1000)+ )++ def test_claim_hash_bound_to_distinct_id(self):+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=2000)+ self.assertFalse(+ verify_identity_claim_hash("user_456", "email", "[email protected]", h, "secret", expires_at=2000, now=1000)+ )++ def test_claim_hash_bound_to_field(self):+ # A hash minted for email must not verify when presented as another field.+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=2000)+ self.assertFalse(+ verify_identity_claim_hash("user_123", "phone", "[email protected]", h, "secret", expires_at=2000, now=1000)+ )++ def test_claim_hash_bound_to_version(self):+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=2000, version="v1")+ self.assertFalse(+ verify_identity_claim_hash(+ "user_123",+ "email",+ "[email protected]",+ h,+ "secret",+ expires_at=2000,+ version="v2",+ now=1000,+ )+ )++ def test_email_canonicalized_before_signing(self):+ # Different-cased / padded input signs to the same hash as the canonical form.+ h_raw = compute_identity_claim_hash("user_123", "email", " [email protected] ", "secret", expires_at=2000)+ h_canonical = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=2000)+ self.assertEqual(h_raw, h_canonical)+ self.assertTrue(+ verify_identity_claim_hash(+ "user_123",+ "email",+ " [email protected] ",+ h_canonical,+ "secret",+ expires_at=2000,+ now=1000,+ )+ )++ def test_expired_claim_is_rejected(self):+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=1000)+ self.assertFalse(+ verify_identity_claim_hash("user_123", "email", "[email protected]", h, "secret", expires_at=1000, now=1000)+ )++ def test_expiry_is_bound_to_hash(self):+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=2000)+ self.assertFalse(+ verify_identity_claim_hash("user_123", "email", "[email protected]", h, "secret", expires_at=3000, now=1000)+ )++ def test_claim_with_excessive_lifetime_is_rejected(self):+ expires_at = 1000 + 2 * IDENTITY_CLAIM_MAX_AGE_SECONDS+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=expires_at)+ self.assertFalse(+ verify_identity_claim_hash(+ "user_123",+ "email",+ "[email protected]",+ h,+ "secret",+ expires_at=expires_at,+ now=1000,+ )+ )++ def test_claim_at_maximum_lifetime_is_accepted(self):+ expires_at = 1000 + IDENTITY_CLAIM_MAX_AGE_SECONDS+ h = compute_identity_claim_hash("user_123", "email", "[email protected]", "secret", expires_at=expires_at)+ self.assertTrue(+ verify_identity_claim_hash(+ "user_123",+ "email",+ "[email protected]",+ h,+ "secret",+ expires_at=expires_at,+ now=1000,+ )+ )++ def test_unknown_field_cannot_be_signed(self):+ with self.assertRaises(ValueError):+ compute_identity_claim_hash("user_123", "org", "acme", "secret", expires_at=2000)++ def test_nul_in_claim_part_cannot_be_signed(self):+ with self.assertRaises(ValueError):+ compute_identity_claim_hash("user_123\x00admin", "email", "[email protected]", "secret", expires_at=2000)++ def test_canonicalize_email(self):+ self.assertEqual(canonicalize_claim_value("email", " [email protected] "), "[email protected]")diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.pyindex 7944bb3cc048..7414d9ae53a1 100644--- a/products/conversations/backend/signals.py+++ b/products/conversations/backend/signals.py@@ -16,7 +16,7 @@ from posthog.models.comment import Commentfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.signals import secret_api_token_rotated-from .cache import invalidate_messages_cache, invalidate_tickets_cache+from .cache import invalidate_identity_tickets_cache, invalidate_messages_cache, invalidate_tickets_cachefrom .events import capture_message_received, capture_message_sent, capture_private_message_sent, capture_ticket_createdfrom .models import EmailOutboxMessage, SigningSecret, Ticketfrom .models.constants import Channel@@ -167,6 +167,7 @@ def update_ticket_on_message(sender, instance: Comment, created: bool, **kwargs)try:ticket = Ticket.objects.select_related("team").get(id=item_id, team_id=team_id)# Invalidate widget caches so list and messages reflect the new message+ invalidate_identity_tickets_cache(team_id)if ticket.widget_session_id:invalidate_tickets_cache(team_id, ticket.widget_session_id)invalidate_messages_cache(team_id, item_id)