: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: attach group properties in all channels (#60870)
Alex V1aa6d34a7f5e
diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.pyindex 0e3dabe91ff0..49a16eefff32 100644--- a/products/conversations/backend/api/tests/test_events.py+++ b/products/conversations/backend/api/tests/test_events.py@@ -309,3 +309,155 @@ class TestConversationEvents(BaseTest):call_kwargs = mock_capture.call_args.kwargsassert call_kwargs["process_person_profile"] is Falseassert "$groups" not in call_kwargs["properties"]++ @parameterized.expand(+ [+ # name, channel, traits_email, email_from -- exercises both the traits.email and the email_from source+ ("slack_traits_email", "slack", "[email protected]", None),+ ("teams_traits_email", "teams", "[email protected]", None),+ ("email_traits_email", "email", "[email protected]", None),+ ("email_from_only", "email", None, "[email protected]"),+ ]+ )+ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_email_fallback_groups(+ self, _name, channel, traits_email, email_from, mock_get_persons, mock_get_by_email, mock_capture+ ):+ """Non-web channels stuff the email into distinct_id; org is resolved via the email->ClickHouse fallback."""+ from posthog.models.person.person import Person++ customer_email = traits_email or email_from+ person_org = Organization.objects.create(name="Acme")+ person_user = User.objects.create(email="[email protected]", distinct_id="real-did-1")+ OrganizationMembership.objects.create(user=person_user, organization=person_org)++ # distinct_id (the email) resolves no identified person...+ mock_get_persons.return_value = []+ # ...but the ClickHouse email lookup returns the person with their real distinct_id+ person = Person(team_id=self.team.id, is_identified=True)+ person._distinct_ids = ["real-did-1"]+ mock_get_by_email.return_value = {customer_email: person}++ traits = {"name": "Biz"}+ if traits_email:+ traits["email"] = traits_email++ ticket = Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id="",+ distinct_id=customer_email,+ channel_source=channel,+ anonymous_traits=traits,+ email_from=email_from,+ )++ capture_ticket_created(ticket)++ mock_get_by_email.assert_called_once_with(self.team, [customer_email])+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is True+ groups = call_kwargs["properties"]["$groups"]+ assert groups["organization"] == str(person_org.id)+ assert groups["project"] == str(self.team.uuid)++ @parameterized.expand(+ [+ ("no_person_for_email", False),+ ("person_without_membership", True),+ ]+ )+ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_email_fallback_no_groups(+ self, _name, person_found, mock_get_persons, mock_get_by_email, mock_capture+ ):+ from posthog.models.person.person import Person++ customer_email = "[email protected]"+ mock_get_persons.return_value = []++ if person_found:+ person = Person(team_id=self.team.id, is_identified=True)+ person._distinct_ids = ["real-did-1"]+ mock_get_by_email.return_value = {customer_email: person}+ # User exists but has no organization membership+ User.objects.create(email="[email protected]", distinct_id="real-did-1")+ else:+ mock_get_by_email.return_value = {}++ ticket = Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id="",+ distinct_id=customer_email,+ channel_source="email",+ anonymous_traits={"name": "Biz", "email": customer_email},+ )++ capture_ticket_created(ticket)++ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is False+ assert "$groups" not in call_kwargs["properties"]++ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_identified_person_without_membership_skips_email_fallback(+ self, mock_get_persons, mock_get_by_email, mock_capture+ ):+ """An identified person resolved via distinct_id is authoritative: no email fallback even if traits.email could match another org."""+ from posthog.models.person.person import Person++ # The widget distinct_id resolves to an identified person, but they have no org membership.+ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]++ capture_ticket_created(self.ticket)++ mock_get_by_email.assert_not_called()+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is False+ assert "$groups" not in call_kwargs["properties"]++ @parameterized.expand(+ [+ # Channels NOT in the email-fallback allowlist must never run the email lookup.+ ("widget_anonymous_spoofed_email", "widget"),+ ("github_no_email", "github"),+ ]+ )+ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_non_verified_channels_skip_email_fallback(+ self, _name, channel, mock_get_persons, mock_get_by_email, mock_capture+ ):+ """anonymous_traits.email is attacker-controlled on the public widget, so it must never resolve an org.++ Even when an anonymous distinct_id resolves to no identified person and a victim org exists for the+ supplied email, non-allowlisted channels (widget, github) skip the email lookup entirely.+ """+ # A victim org/person that the spoofed email would resolve to if the lookup ran.+ victim_org = Organization.objects.create(name="Victim Corp")+ victim_user = User.objects.create(email="[email protected]", distinct_id="victim-did")+ OrganizationMembership.objects.create(user=victim_user, organization=victim_org)++ # Anonymous distinct_id resolves to no identified person -> step 1 does not early-return.+ mock_get_persons.return_value = []++ ticket = Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id="",+ distinct_id="anon-attacker",+ channel_source=channel,+ anonymous_traits={"name": "Attacker", "email": "[email protected]"},+ )++ capture_ticket_created(ticket)++ mock_get_by_email.assert_not_called()+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is False+ assert "$groups" not in call_kwargs["properties"]diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 4a953333e07f..d69d518e593b 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -27,9 +27,9 @@ from posthog.models import ActivityLog, Comment, Organization, Userfrom posthog.models.person import Personfrom posthog.personhog_client.test_helpers import PersonhogTestMixin-from products.conversations.backend.api.tickets import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_emailfrom products.conversations.backend.models import Ticket, TicketAssignmentfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Status+from products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_emailfrom ee.clickhouse.materialized_columns.columns import get_bloom_filter_lower_index_namefrom ee.models.rbac.role import Rolediff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex ca5525d30524..6d8376985373 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -25,23 +25,16 @@ from rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.response import Response-from posthog.schema import HogQLQueryModifiers--from posthog.hogql import ast-from posthog.hogql.query import execute_hogql_query-from posthog.api.person import get_person_namefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin-from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import OrganizationMembershipfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.comment import Commentfrom posthog.models.person.person import Person-from posthog.models.person.util import get_person_by_distinct_id, get_persons_by_distinct_ids, get_persons_by_uuids-from posthog.models.team import Team+from posthog.models.person.util import get_person_by_distinct_id, get_persons_by_distinct_idsfrom posthog.permissions import APIScopePermission, PostHogFeatureFlagPermissionfrom posthog.rate_limit import (AIBurstRateThrottle,@@ -65,64 +58,12 @@ from products.conversations.backend.events import ()from products.conversations.backend.models import EmailChannel, Ticket, TicketAssignmentfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Status+from products.conversations.backend.person_lookup import _get_persons_by_emailfrom ee.models.rbac.role import Rolelogger = structlog.get_logger(__name__)-# Case-insensitive batch email lookup. Exposed so tests can EXPLAIN the exact query that runs.-PERSON_EMAIL_LOOKUP_QUERY = """-SELECT id, properties.email-FROM persons-WHERE lower(properties.email) IN {emails}-"""---def _get_persons_by_email(- team: Team,- emails: list[str],- modifiers: HogQLQueryModifiers | None = None,-) -> dict[str, Person]:- """Batch look up persons by their properties.email value via ClickHouse.-- Returns a dict mapping lowercase email -> Person for the first match.- Only checks ``properties.email`` (the canonical, materialized key with- a skip index). Uses the HogQL ``persons`` virtual table (argMax dedup- handled automatically).- """- if not emails:- return {}-- emails_lower = [e.lower() for e in emails]- with tags_context(product=Product.CONVERSATIONS, feature=Feature.QUERY):- response = execute_hogql_query(- PERSON_EMAIL_LOOKUP_QUERY,- placeholders={"emails": ast.Constant(value=emails_lower)},- team=team,- query_type="conversations_person_email_lookup",- modifiers=modifiers,- )-- if not response.results:- return {}-- email_to_uuid: dict[str, str] = {}- for person_uuid, prop_email in response.results:- if prop_email:- lower = prop_email.lower()- if lower not in email_to_uuid:- email_to_uuid[lower] = str(person_uuid)-- persons = get_persons_by_uuids(team.pk, list(email_to_uuid.values()))- uuid_to_person: dict[str, Person] = {str(p.uuid): p for p in persons}-- result: dict[str, Person] = {}- for email_lower, person_uuid in email_to_uuid.items():- person = uuid_to_person.get(person_uuid)- if person is not None:- result[email_lower] = person- return result-class SuggestReplyResponseSerializer(serializers.Serializer):suggestion = serializers.CharField()diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.pyindex b9a401870836..d6db08ddc3b1 100644--- a/products/conversations/backend/events.py+++ b/products/conversations/backend/events.py@@ -12,13 +12,67 @@ from posthog.api.capture import capture_internalfrom posthog.event_usage import groups as build_groupsfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.person.util import get_persons_by_distinct_ids+from posthog.models.team import Teamfrom products.conversations.backend.models import Ticket+from products.conversations.backend.models.constants import Channel+from products.conversations.backend.person_lookup import _get_persons_by_emaillogger = structlog.get_logger(__name__)EVENT_SOURCE = "conversations_events"+# Channels whose customer email is tied to a provider-verified identity and is therefore safe+# to use for organization attribution.+_EMAIL_FALLBACK_CHANNELS = frozenset({Channel.EMAIL.value, Channel.SLACK.value, Channel.TEAMS.value})+++def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:+ """Resolve the customer organization's ``$groups`` for a ticket.++ Returns ``(process_person, groups)``. ``groups`` is ``None`` when the+ customer can't be tied to a PostHog organization.++ The web widget sets ``ticket.distinct_id`` to a real PostHog distinct_id,+ so the membership is found directly. Other channels (Slack, Email, MS+ Teams) set ``distinct_id`` to the customer email (or empty), so we fall+ back to looking the person up by ``properties.email`` in ClickHouse and+ resolving the membership through that person's real distinct_ids.+ """+ # 1. Real distinct_id (web widget). An identified person is authoritative: if they+ # have no org membership, don't guess via email (a shared email could resolve to a+ # different person's org), so return early instead of falling through.+ if ticket.distinct_id:+ persons = get_persons_by_distinct_ids(team.id, [ticket.distinct_id])+ if any(p.is_identified for p in persons):+ membership = (+ OrganizationMembership.objects.select_related("organization")+ .filter(user__distinct_id=ticket.distinct_id)+ .first()+ )+ if membership:+ return True, build_groups(membership.organization, team)+ return False, None++ # 2. Email fallback, restricted to channels with a provider-verified email identity.+ # Never trust the public widget's attacker-controlled anonymous_traits.email here.+ if ticket.channel_source not in _EMAIL_FALLBACK_CHANNELS:+ return False, None++ email = (ticket.anonymous_traits or {}).get("email") or ticket.email_from+ if email:+ person = _get_persons_by_email(team, [email]).get(email.lower())+ if person is not None and person.distinct_ids:+ membership = (+ OrganizationMembership.objects.select_related("organization")+ .filter(user__distinct_id__in=person.distinct_ids)+ .first()+ )+ if membership:+ return True, build_groups(membership.organization, team)++ return False, None+def _get_ticket_base_properties(ticket: Ticket) -> dict:return {@@ -40,20 +94,12 @@ def capture_ticket_created(ticket: Ticket) -> None:team = ticket.teamteam_id = team.idprocess_person = False- if ticket.distinct_id:- try:- persons = get_persons_by_distinct_ids(team_id, [ticket.distinct_id])- if any(p.is_identified for p in persons):- membership = (- OrganizationMembership.objects.select_related("organization")- .filter(user__distinct_id=ticket.distinct_id)- .first()- )- if membership:- process_person = True- properties["$groups"] = build_groups(membership.organization, team)- except Exception:- logger.exception("ticket_created_person_lookup_failed", team_id=team_id, ticket_id=str(ticket.id))+ try:+ process_person, groups = _resolve_org_groups(ticket, team)+ if groups is not None:+ properties["$groups"] = groups+ except Exception:+ logger.exception("ticket_created_person_lookup_failed", team_id=team_id, ticket_id=str(ticket.id))capture_internal(token=team.api_token,diff --git a/products/conversations/backend/person_lookup.py b/products/conversations/backend/person_lookup.pynew file mode 100644index 000000000000..30fd83d5ad9d--- /dev/null+++ b/products/conversations/backend/person_lookup.py@@ -0,0 +1,62 @@+from posthog.schema import HogQLQueryModifiers++from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.person.person import Person+from posthog.models.person.util import get_persons_by_uuids+from posthog.models.team import Team++# Case-insensitive batch email lookup. Exposed so tests can EXPLAIN the exact query that runs.+PERSON_EMAIL_LOOKUP_QUERY = """+SELECT id, properties.email+FROM persons+WHERE lower(properties.email) IN {emails}+"""+++def _get_persons_by_email(+ team: Team,+ emails: list[str],+ modifiers: HogQLQueryModifiers | None = None,+) -> dict[str, Person]:+ """Batch look up persons by their properties.email value via ClickHouse.++ Returns a dict mapping lowercase email -> Person for the first match.+ Only checks ``properties.email`` (the canonical, materialized key with+ a skip index). Uses the HogQL ``persons`` virtual table (argMax dedup+ handled automatically).+ """+ if not emails:+ return {}++ emails_lower = [e.lower() for e in emails]+ with tags_context(product=Product.CONVERSATIONS, feature=Feature.QUERY):+ response = execute_hogql_query(+ PERSON_EMAIL_LOOKUP_QUERY,+ placeholders={"emails": ast.Constant(value=emails_lower)},+ team=team,+ query_type="conversations_person_email_lookup",+ modifiers=modifiers,+ )++ if not response.results:+ return {}++ email_to_uuid: dict[str, str] = {}+ for person_uuid, prop_email in response.results:+ if prop_email:+ lower = prop_email.lower()+ if lower not in email_to_uuid:+ email_to_uuid[lower] = str(person_uuid)++ persons = get_persons_by_uuids(team.pk, list(email_to_uuid.values()))+ uuid_to_person: dict[str, Person] = {str(p.uuid): p for p in persons}++ result: dict[str, Person] = {}+ for email_lower, person_uuid in email_to_uuid.items():+ person = uuid_to_person.get(person_uuid)+ if person is not None:+ result[email_lower] = person+ return result