: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
fix: support email dmarc issue (#57461)
Alex Veaf0a6320c04
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.pyindex 8ebc92bba657..8e7e8dd22261 100644--- a/products/conversations/backend/api/email_events.py+++ b/products/conversations/backend/api/email_events.py@@ -24,6 +24,8 @@ from products.conversations.backend.services.region_routing import is_primary_relogger = structlog.get_logger(__name__)INBOUND_TOKEN_PATTERN = re.compile(r"^team-([a-f0-9]+)@")+_VIA_SUFFIX_RE = re.compile(r"\s+via\s+.+$", re.IGNORECASE)+_BASIC_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")MAX_EMAIL_BODY_LENGTH = 50_000MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 # 10 MB per fileMAX_ATTACHMENTS = 20@@ -156,6 +158,77 @@ def _build_content_with_attachments(text: str, attachments: list[dict[str, Any]]return content, rich_content+def _is_plausible_email(addr: str) -> bool:+ """Reject obviously malformed addresses before trusting a recovery header."""+ return bool(_BASIC_EMAIL_RE.match(addr))+++def _recover_dmarc_rewritten_sender(+ request: HttpRequest,+ config: EmailChannel,+ sender_email: str,+ sender_name: str,+) -> tuple[str, str]:+ """Recover the original sender when DMARC-compliant forwarding rewrote From.++ Google Groups / Workspace and other forwarders rewrite the From header to+ the group address when the original sender's domain has a strict DMARC+ policy (p=quarantine or p=reject). The rewritten From looks like:++ "'Real Name' via GroupName" <[email protected]>++ The original sender is preserved in X-Original-From or Reply-To.++ We gate recovery on two signals to reduce spoofing risk:+ 1. sender_email matches the channel's own from_email+ 2. the display name contains " via " (the fingerprint left by forwarders)++ An attacker who forges From to config.from_email but omits the " via "+ pattern will not trigger recovery.++ Known limitation: if a team member sends from config.from_email with+ " via " in their display name, recovery would fire. In practice this+ is vanishingly unlikely — the "via" pattern is injected by mail+ forwarders, not by human MUAs.+ """+ if sender_email.lower() != config.from_email.lower():+ return sender_email, sender_name++ if " via " not in sender_name.lower():+ return sender_email, sender_name++ logger.info(+ "email_inbound_dmarc_rewrite_detected",+ team_id=config.team_id,+ from_header=request.POST.get("from", ""),+ )++ # 1. Try X-Original-From (set by Google Groups/Workspace)+ x_original = request.POST.get("X-Original-From", "") or request.POST.get("X-Original-Sender", "")+ if x_original:+ orig_name, orig_email = parseaddr(x_original)+ if orig_email and _is_plausible_email(orig_email):+ return orig_email, orig_name or orig_email.split("@")[0]++ # 2. Try Reply-To (most forwarding services preserve this)+ reply_to = request.POST.get("Reply-To", "")+ if reply_to:+ rt_name, rt_email = parseaddr(reply_to)+ if rt_email and rt_email.lower() != config.from_email.lower() and _is_plausible_email(rt_email):+ return rt_email, rt_name or rt_email.split("@")[0]++ # 3. Neither header yielded a usable address. Strip " via <GroupName>"+ # from the display name as a cosmetic fix.+ logger.warning(+ "email_inbound_dmarc_rewrite_unrecoverable",+ team_id=config.team_id,+ from_header=request.POST.get("from", ""),+ )+ sender_name = _VIA_SUFFIX_RE.sub("", sender_name).strip("'\"").strip()++ return sender_email, sender_name++@csrf_exemptdef email_inbound_handler(request: HttpRequest) -> HttpResponse:if request.method != "POST":@@ -217,6 +290,11 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:if not sender_name:sender_name = sender_email.split("@")[0] if sender_email else "Unknown"+ # 6a. Recover original sender when From was rewritten by DMARC-compliant+ # forwarding (e.g. Google Groups rewrites From to the group address for+ # senders whose domain has p=quarantine or p=reject).+ sender_email, sender_name = _recover_dmarc_rewritten_sender(request, config, sender_email, sender_name)+# 6b. Parse CC recipientscc_header = request.POST.get("Cc", "")cc_list: list[str] = []diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex 6bc31b9d9ea8..05ff5e9eacba 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -797,6 +797,133 @@ class TestSendEmailReplyMultiConfig(BaseTest):)+class TestEmailInboundDmarcRewrite(BaseTest):+ def setUp(self):+ super().setUp()+ self.client = Client()+ self.team.conversations_settings = {"email_enabled": True}+ self.team.save()+ self.config = EmailChannel.objects.create(+ team=self.team,+ inbound_token="dd00aa11cc2233ee",+ from_email="[email protected]",+ from_name="Merch",+ domain="posthog.com",+ domain_verified=True,+ )++ def _base_data(self, msg_id: str) -> dict[str, str]:+ return {+ "recipient": "[email protected]",+ "Message-Id": msg_id,+ "subject": "Order question",+ "stripped-text": "Where is my order?",+ }++ @parameterized.expand(+ [+ (+ "x_original_from",+ {+ "from": "'Alex Smith' via Merch <[email protected]>",+ "X-Original-From": "Alex Smith <[email protected]>",+ },+ "[email protected]",+ "Alex Smith",+ ),+ (+ "x_original_sender",+ {"from": "'Bob' via Merch <[email protected]>", "X-Original-Sender": "[email protected]"},+ "[email protected]",+ "bob",+ ),+ (+ "reply_to_with_name",+ {"from": "'Jane Doe' via Merch <[email protected]>", "Reply-To": "Jane Doe <[email protected]>"},+ "[email protected]",+ "Jane Doe",+ ),+ (+ "reply_to_bare_email",+ {"from": "'Someone' via Merch <[email protected]>", "Reply-To": "[email protected]"},+ "[email protected]",+ "someone",+ ),+ (+ "x_original_from_over_reply_to",+ {+ "from": "'Charlie' via Merch <[email protected]>",+ "X-Original-From": "Charlie <[email protected]>",+ "Reply-To": "[email protected]",+ },+ "[email protected]",+ "Charlie",+ ),+ (+ "no_recovery_headers_strips_via",+ {"from": "'Alex Smith' via Merch <[email protected]>"},+ "[email protected]",+ "Alex Smith",+ ),+ (+ "reply_to_matching_config_falls_through",+ {"from": "'Alice' via Merch <[email protected]>", "Reply-To": "[email protected]"},+ "[email protected]",+ "Alice",+ ),+ (+ "non_rewritten_from_unchanged",+ {"from": "Regular User <[email protected]>"},+ "[email protected]",+ "Regular User",+ ),+ (+ "forged_from_no_via_skips_recovery",+ {"from": "Attacker <[email protected]>", "X-Original-From": "[email protected]"},+ "[email protected]",+ "Attacker",+ ),+ (+ "malformed_x_original_from_rejected",+ {"from": "'Eve' via Merch <[email protected]>", "X-Original-From": "not-an-email"},+ "[email protected]",+ "Eve",+ ),+ (+ "malformed_reply_to_rejected",+ {"from": "'Eve' via Merch <[email protected]>", "Reply-To": "bad@"},+ "[email protected]",+ "Eve",+ ),+ ]+ )+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_dmarc_sender_recovery(self, _name, extra_headers, expected_email, expected_name, _mock_sig):+ data = self._base_data(f"<dmarc-{_name}@test.com>")+ data.update(extra_headers)+ self.client.post("/api/conversations/v1/email/inbound", data)++ ticket = Ticket.objects.get(team=self.team)+ assert ticket.email_from == expected_email+ assert ticket.anonymous_traits["email"] == expected_email+ assert ticket.anonymous_traits["name"] == expected_name++ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_recovered_sender_flows_to_comment_context(self, _mock_sig: MagicMock):+ data = self._base_data("<[email protected]>")+ data["from"] = "'Alex Smith' via Merch <[email protected]>"+ data["X-Original-From"] = "Alex Smith <[email protected]>"+ self.client.post("/api/conversations/v1/email/inbound", data)++ ticket = Ticket.objects.get(team=self.team)+ assert ticket.distinct_id == "[email protected]"++ comment = Comment.objects.get(team=self.team, scope="conversations_ticket")+ assert comment.item_context is not None+ assert comment.item_context["email_from"] == "[email protected]"+ assert comment.item_context["email_from_name"] == "Alex Smith"++class TestEmailInboundCcParticipants(BaseTest):def setUp(self):super().setUp()