: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(conversations): stop a support inbox looping on its own autoreply (#92017)
Steven Shults048b4647999f
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex 6558d844f3a1..ab567bbb2bdb 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -1415,6 +1415,22 @@ describe('EmailService', () => {expect(headerNames).toContain('X-PostHog-Tracking-Code')})+ it.each(['transactional', 'marketing'])(+ 'marks a %s send as auto-generated so autoresponders do not answer it',+ async (categoryType) => {+ // Without this an autoresponder answers the workflow, and when the address it+ // answers is a support inbox the reply re-enters the same workflow as a new ticket.+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ invocation.hogFunction.metadata = { message_category_type: categoryType }+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }+ expect(sentCommand.input.Content.Simple.Headers).toEqual(+ expect.arrayContaining([{ Name: 'Auto-Submitted', Value: 'auto-generated' }])+ )+ }+ )+it('attaches the X-PostHog-Tracking-Code header carrying the full signed code', async () => {// The header is the authoritative tracking-code carrier (the EmailTag is the// bounded backwards-compat fallback). It rides on every outbound message,diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 99d9e523c53b..1e95f8cf2a34 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -39,6 +39,20 @@ const sesThrottleResponsesTotal = new Counter({labelNames: ['error_code'],})+/**+ * Every send on this path is generated by a workflow rather than typed by a person, so it+ * carries the RFC 3834 marker that says so. A well-behaved autoresponder does not answer a+ * message marked this way, which stops the loop that starts when a workflow emails an address+ * that answers automatically, such as a support inbox whose reply lands back in the same+ * workflow as a new ticket.+ *+ * `auto-generated` rather than `auto-replied`: the value covers the whole path, campaigns+ * included, not only the sends that answer an incoming message.+ */+const AUTO_SUBMITTED_HEADER_NAME = 'Auto-Submitted'+const AUTO_SUBMITTED_HEADER_VALUE = 'auto-generated'+const AUTO_SUBMITTED_HEADER: MessageHeader = { Name: AUTO_SUBMITTED_HEADER_NAME, Value: AUTO_SUBMITTED_HEADER_VALUE }+/*** SES error codes that signal a transient rate-limit shape — safe to retry* shortly after. `TooManyRequestsException` is the SES-v2-specific class;@@ -949,6 +963,7 @@ export class EmailService {to: params.to.name ? `"${params.to.name}" <${params.to.email}>` : params.to.email,subject: sanitizeEmailSubject(params.subject),text: params.text,+ headers: { [AUTO_SUBMITTED_HEADER.Name!]: AUTO_SUBMITTED_HEADER.Value! },...(params.html? {html: trackingEnabled@@ -1071,7 +1086,7 @@ export class EmailService {identifier: params.to.email,}): []- sendEmailParams.Content.Simple.Headers = [...unsubscribeHeaders, trackingHeader]+ sendEmailParams.Content.Simple.Headers = [...unsubscribeHeaders, trackingHeader, AUTO_SUBMITTED_HEADER]}const replyToAddresses = parseAddressList(params.replyTo)diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.pyindex e613fa7bb06c..592edabbb7f3 100644--- a/products/conversations/backend/api/email_events.py+++ b/products/conversations/backend/api/email_events.py@@ -73,6 +73,14 @@ MAX_ATTACHMENTS = 20# an unbounded batch of queries under the held thread lock.MAX_RECIPIENTS = 100MAX_FORWARDING_CHALLENGE_TOKENS = 10+# Every value here has to mean "a machine wrote this", not "do not auto-reply to this". The two+# claims look alike and only the first one identifies a loop. RFC 3834 marks any Auto-Submitted+# value but "no" as machine-generated. Of the pre-RFC Precedence values only "auto_reply" makes+# the same claim: "bulk", "junk" and "list" all ride on a person's message when a mailing list+# relays it, so treating them as machine-generated would drop real mail a customer sent.+AUTO_SUBMITTED_HUMAN_VALUE = "no"+AUTORESPONDER_PRECEDENCE_VALUES = frozenset({"auto_reply"})+AUTORESPONDER_HEADERS = ("X-Autoreply", "X-Autorespond")# The sender controls the Date header, so a far-future value would latch a thread's last_message_at# and freeze its preview. Reject dates beyond a small clock-skew allowance and fall back to the# authenticated webhook timestamp (or now) instead.@@ -382,6 +390,20 @@ def _dkim_signing_domains(request: HttpRequest) -> tuple[str, ...]:return tuple(dict.fromkeys(domains))+def _is_auto_generated(request: HttpRequest) -> bool:+ """Report whether the message announces itself as machine-generated."""+ for value in _message_header_values(request, "Auto-Submitted"):+ # The header carries optional parameters, e.g. "auto-replied; owner-token=...".+ if value.partition(";")[0].strip().lower() not in ("", AUTO_SUBMITTED_HUMAN_VALUE):+ return True++ for value in _message_header_values(request, "Precedence"):+ if value.strip().lower() in AUTORESPONDER_PRECEDENCE_VALUES:+ return True++ return any(_message_header_values(request, header_name) for header_name in AUTORESPONDER_HEADERS)++def _parse_addresses(value: str) -> tuple[EmailAddress, ...]:addresses: list[EmailAddress] = []seen: set[str] = set()@@ -471,9 +493,16 @@ def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedEmcapture_address=request.POST.get("recipient", "").strip().lower(),attachments=tuple(attachments),forwarding_challenge_tokens=_forwarding_challenge_tokens(request),+ auto_generated=_is_auto_generated(request),)+def _is_self_addressed(*, config: EmailChannel, inbound_token: str, sender_email: str) -> bool:+ """Report whether the inbox received a message that claims to come from itself."""+ sender = sender_email.strip().lower()+ return bool(sender) and (sender == config.from_email.lower() or sender.startswith(f"team-{inbound_token}@"))++def _collect_participants(to_recipients: tuple[EmailAddress, ...],cc_recipients: tuple[EmailAddress, ...],@@ -812,6 +841,21 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:logger.warning("email_inbound_no_message_id", team_id=config.team_id)return HttpResponse(status=200)+ if email.auto_generated and _is_self_addressed(+ config=config, inbound_token=inbound_token, sender_email=email.sender.email+ ):+ # An autoresponder on the inbox address answers the inbox itself, and the answer arrives+ # back here as fresh mail. Accepting it starts a loop that runs until someone notices, so+ # drop it. Both conditions are required: a person whose mail was relayed with a rewritten+ # From still reaches us, and an external autoresponder still opens a ticket.+ logger.warning(+ "email_inbound_self_addressed_autoreply_dropped",+ team_id=config.team_id,+ config_id=str(config.id),+ message_id=email.message_id,+ )+ return HttpResponse(status=200)+if config.kind == EmailChannelKind.CUSTOMER_COMMUNICATION:challenge_result = process_forwarding_challenges(team_id=config.team_id,diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex f0fc6426c383..ed61e4f983ca 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -2267,6 +2267,97 @@ class TestEmailInboundDmarcRewrite(BaseTest):assert comment.item_context["email_from_name"] == "Alex Smith"+class TestEmailInboundSelfAddressedAutoreply(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="ab11cd22ef33ab44",+ from_email="[email protected]",+ from_name="Security",+ domain="posthog.com",+ domain_verified=True,+ )++ def _post(self, msg_id: str, extra: dict[str, str]) -> None:+ data = {+ "recipient": "[email protected]",+ "Message-Id": msg_id,+ "subject": "We've got your email",+ "stripped-text": "Our team is looking into your email.",+ "To": "[email protected]",+ **extra,+ }+ self.client.post("/api/conversations/v1/email/inbound", data)++ @parameterized.expand(+ [+ ("auto_submitted", {"Auto-Submitted": "auto-replied"}),+ ("auto_submitted_with_parameters", {"Auto-Submitted": "auto-generated; owner-token=abc"}),+ ("precedence_auto_reply", {"Precedence": "auto_reply"}),+ ("x_autoreply", {"X-Autoreply": "yes"}),+ ]+ )+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_autoreply_from_the_inbox_itself_is_dropped(self, name, headers, _mock_sig):+ self._post(f"<loop-{name}@posthog.com>", {"from": "PostHog Security <[email protected]>", **headers})++ assert Ticket.objects.filter(team=self.team).count() == 0++ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_autoreply_from_the_inbound_address_is_dropped(self, _mock_sig: MagicMock):+ self._post(+ "<[email protected]>",+ {"from": "[email protected]", "Auto-Submitted": "auto-replied"},+ )++ assert Ticket.objects.filter(team=self.team).count() == 0++ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_auto_submitted_header_is_read_from_the_message_headers_blob(self, _mock_sig: MagicMock):+ self._post(+ "<[email protected]>",+ {+ "from": "PostHog Security <[email protected]>",+ "message-headers": '[["Auto-Submitted", "auto-replied"]]',+ },+ )++ assert Ticket.objects.filter(team=self.team).count() == 0++ @parameterized.expand(+ [+ # A person's mail relayed by a list arrives From the list address, and the list marks it+ # with a Precedence that only asks receivers not to auto-reply. Reading any of those as+ # "a machine wrote this" would drop the customer's email.+ ("relayed_person_precedence_list", {"from": "Alex Smith <[email protected]>", "Precedence": "list"}),+ ("relayed_person_precedence_bulk", {"from": "Alex Smith <[email protected]>", "Precedence": "bulk"}),+ ("relayed_person_no_markers", {"from": "Alex Smith <[email protected]>"}),+ ("auto_submitted_no", {"from": "Alex Smith <[email protected]>", "Auto-Submitted": "no"}),+ ]+ )+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_self_addressed_human_mail_still_opens_a_ticket(self, name, headers, _mock_sig):+ self._post(f"<human-{name}@posthog.com>", headers)++ assert Ticket.objects.filter(team=self.team).count() == 1++ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_external_automated_mail_still_opens_a_ticket(self, _mock_sig: MagicMock):+ # Teams route infrastructure alerts to support on purpose, so being machine-generated is+ # only half the test: the message also has to claim to come from the inbox itself.+ self._post(+ "<[email protected]>",+ {"from": "Alerts <[email protected]>", "Auto-Submitted": "auto-replied"},+ )++ ticket = Ticket.objects.get(team=self.team)+ assert ticket.email_from == "[email protected]"++class TestEmailInboundTeamMemberDetection(BaseTest):def setUp(self):super().setUp()diff --git a/products/conversations/backend/services/email_thread_ingestion.py b/products/conversations/backend/services/email_thread_ingestion.pyindex dfe4d07765ed..5580108b4825 100644--- a/products/conversations/backend/services/email_thread_ingestion.py+++ b/products/conversations/backend/services/email_thread_ingestion.py@@ -60,6 +60,7 @@ class ParsedEmail:capture_address: strattachments: tuple[UploadedFile, ...]forwarding_challenge_tokens: tuple[str, ...] = ()+ auto_generated: bool = Falsedef body_with_matching_html(self, *, prefer_stripped: bool) -> "EmailBody":"""Return the body text we store paired with the HTML of the same scope.