: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
chore(conversations): verify Mailgun webhooks through ingress, minimal diff (#102246)
Julian Bez4915c559635c
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex 6da7b75dee26..ac40bd216305 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -117,5 +117,4 @@ rules:- /ee/api/vercel/vercel_webhooks.py- /ee/partners/stripe/api/provisioning/signature.py- /posthog/models/integration/slack.py- - /products/conversations/backend/mailgun.py- /products/workflows/backend/api/ses_events_webhook.pydiff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 8e33ccf7cfc8..2b8fce81fa8c 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -72,8 +72,9 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf| `teams` | `/api/conversations/v1/teams/events` | `supporthog` | `conversations_teams` | `products/conversations/backend/webhook_consumers.py` || `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` || `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |-| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/services/mailgun_events.py` |-| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/services/mailgun_events.py` |+| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | `conversations_email_inbound` | `products/conversations/backend/webhook_consumers.py` |+| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | `conversations_email_outbound` | `products/conversations/backend/webhook_consumers.py` |+| `mailgun` | `/api/conversations/v1/email/capture` | `capture` | `conversations_email_capture` | `products/conversations/backend/webhook_consumers.py` || `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` || `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |diff --git a/posthog/ingress/mailgun/README.md b/posthog/ingress/mailgun/README.mdindex 39b8562384ea..ad3a92c8c10f 100644--- a/posthog/ingress/mailgun/README.md+++ b/posthog/ingress/mailgun/README.md@@ -24,16 +24,17 @@ The delivery id is the `token` field.Mailgun mints a fresh token per delivery, so dedup is on.A route carries a message rather than an event, so there is no event field to read.-Each app has one fixed event type: `message_received` for `inbound`, and `message_sent` for `outbound`.+Each app has one fixed event type: `message_received` for `inbound` and `capture`, and `message_sent` for `outbound`.## Apps and secrets-Two apps, one per route:+Three apps, one per route:- `inbound` — mail a customer sent to a PostHog inbox address.- `outbound` — mail a customer's own agent sent, captured by a second route.+- `capture` — one catch-all route that carries both, where the recipient local part is the only thing that tells them apart. Its event type is the inbound one, because the app types the delivery and the split is the consumer's to make.-Both take a `signing_key_getter` from the builder.+All three take a `signing_key_getter` from the builder.The key is per Mailgun account rather than per route, so a caller that mounts both endpoints passes the same getter twice.The getter is injected because the setting that holds the key belongs to the product that registered the account, and nothing under `posthog/ingress/` imports a product.Keep the getter cheap or cached: the scheme calls it on every request, before it looks at the signature, so an unsigned probe reaches it too.@@ -47,7 +48,7 @@ A consumer must read a file inside the request.An `UploadedFile` is backed by the request stream or by a temporary file, so it does not survive the response and cannot be handed to a task as it is.A consumer that wants the attachment later stores it first, then passes the stored reference.-The file count is capped at 20, the cap the conversations inbound view already applies.+The file count is capped at 20, the cap the conversations inbound view applied before it moved here.The cap bounds what a consumer iterates, not what the request costs: the form parser reads and spools every part first, and Django's `DATA_UPLOAD_MAX_NUMBER_FILES` is what bounds that.The whole body is parsed before the signature is checked, because the signature lives in the form.@@ -61,7 +62,16 @@ They would be a third app, added when a product needs one.## Consumers-No product registers a Mailgun consumer yet.-The conversations email endpoints move to ingress in their own PR.-That product serves a third path, `/api/conversations/v1/email/capture`, which picks between the two routes by the recipient local part, so it mounts whichever app its consumer splits on.+Conversations registers one consumer per app, in `products/conversations/backend/webhook_consumers.py`:++- `conversations_email_inbound` — opens or continues a support ticket, or ingests a customer email thread.+- `conversations_email_outbound` — records mail a customer's own agent sent.+- `conversations_email_capture` — reads the recipient local part and runs whichever of the two the message is.++All three declare `ownership`, because a team's email channel lives in one region.+The inbound apps resolve the channel by the `team-<token>@` inbound address, the outbound app by the sending address on an active customer-communication channel.+An address this region does not hold answers `ELSEWHERE`, so the delivery reaches the region that does.+A lookup that does not finish raises on every app instead of answering `ELSEWHERE`, so ingress asks Mailgun for a redelivery rather than forward mail on a question it never answered.++`retry_status` is 502 on this provider, so a forward that never landed and a consumer that raised both cost the request its receipt and Mailgun redelivers.See the [Endpoints table](../README.md#endpoints).diff --git a/posthog/ingress/mailgun/provider.py b/posthog/ingress/mailgun/provider.pyindex 55b70d0acce3..0d91ba8a3898 100644--- a/posthog/ingress/mailgun/provider.py+++ b/posthog/ingress/mailgun/provider.py@@ -29,6 +29,9 @@ TOKEN_FIELD = "token"_APP_EVENT_TYPES: Mapping[str, str] = {"inbound": "message_received","outbound": "message_sent",+ # A catch-all route carries both directions, so the consumer reads the recipient address to+ # tell them apart.+ "capture": "message_received",}SPECS = tuple(@@ -53,6 +56,10 @@ def _files_in_request(request: HttpRequest) -> dict[str, UploadedFile]:class MailgunProvider(WebhookProvider):provider = "mailgun"+ # Mailgun retries a route delivery on any status but 2xx and 406, over several hours. So a+ # forward that never landed, or a consumer whose write raised, must not be receipted: the+ # message is only held by Mailgun's own queue, and nothing else can hand it back.+ retry_status = 502# A route delivery carries the whole mail message, including up to MAX_FILES attachments, and# the forward rebuilds and re-sends every part. Three seconds is not enough for that.forward_timeout_seconds = 10.0diff --git a/posthog/ingress/test/test_mailgun.py b/posthog/ingress/test/test_mailgun.pyindex 99e3c8826b58..4d206bb26292 100644--- a/posthog/ingress/test/test_mailgun.py+++ b/posthog/ingress/test/test_mailgun.py@@ -74,7 +74,9 @@ class TestMailgunProvider(SimpleTestCase):(delivery,) = provider.deliveries(request, payload, {})self.assertEqual(delivery.delivery_id, fields["token"])- @parameterized.expand([("inbound", "message_received"), ("outbound", "message_sent")])+ @parameterized.expand(+ [("inbound", "message_received"), ("outbound", "message_sent"), ("capture", "message_received")]+ )def test_each_app_types_its_delivery_by_the_route_it_serves(self, app: str, event_type: str) -> None:request = RequestFactory().post(URL, data=urlencode(_signed_fields()), content_type=FORM_CONTENT_TYPE)provider = _provider(app)diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.pynew file mode 100644index 000000000000..cf41845706c7--- /dev/null+++ b/products/conversations/backend/api/email_events.py@@ -0,0 +1,86 @@+"""Email webhook endpoints for Mailgun routes, plus the cross-region sender lookup they need.++Three routes on one Mailgun account: the inbox address a customer writes to, the address a+customer's own agent blind-copies, and the catch-all that serves both. Each is an ingress app,+so verification, the receipt and the forward to the owning region all happen there, and the work+runs in `products/conversations/backend/services/mailgun_events.py`.+"""++from typing import Any++from django.http import HttpRequest, HttpResponse, JsonResponse+from django.views.decorators.csrf import csrf_exempt++from posthog.ingress.mailgun.provider import MailgunProvider, build_mailgun_provider+from posthog.ingress.verify.schemes import VerificationOutcome+from posthog.ingress.views import build_webhook_view++from products.conversations.backend.mailgun import get_email_webhook_signing_key++OUTBOUND_SENDER_LOOKUP_QUERY_PARAM = "sender_lookup"+++class _OutboundMailgunProvider(MailgunProvider):+ """An app that captures outbound mail, and the sender probe the other region ran before ingress.++ The regions do not deploy at the same instant, so for one release the outbound route, and the+ catch-all that served it, still have to recognise a `sender_lookup=1` probe from a region on+ the previous version. The probe carries a+ whole delivery, so dispatching it would ingest the probe as real mail. Answering it as a+ handshake keeps the shared view's verification, throttle and metrics. Delete this class, and+ the query parameter with it, once both regions run the ingress version.+ """++ def pre_dispatch_response(self, request: HttpRequest, payload: Any) -> HttpResponse | None:+ if request.GET.get(OUTBOUND_SENDER_LOOKUP_QUERY_PARAM) != "1":+ return None++ deliveries = self.deliveries(request, payload, {})+ if not deliveries:+ return HttpResponse(status=400)++ # Deferred because this module is on the URL conf's import path, and the ingestion modules+ # behind the facade are not cheap to import.+ from products.conversations.backend.facade.api import mailgun_legacy_sender_lookup_status # noqa: PLC0415++ return HttpResponse(status=mailgun_legacy_sender_lookup_status(deliveries[0]))+++_outbound_provider = _OutboundMailgunProvider("outbound", signing_key_getter=get_email_webhook_signing_key)++email_inbound_handler = build_webhook_view(+ build_mailgun_provider("inbound", signing_key_getter=get_email_webhook_signing_key)+)+email_outbound_handler = build_webhook_view(_outbound_provider)+email_capture_handler = build_webhook_view(+ _OutboundMailgunProvider("capture", signing_key_getter=get_email_webhook_signing_key)+)+++@csrf_exempt+def email_sender_status_handler(request: HttpRequest) -> HttpResponse:+ """Answer whether this region holds an active channel for a sender the other region captured.++ Channel uniqueness is per region, so a sender active in both would attach one team's private+ outbound mail to the other team's thread. The asking region replays the delivery's own Mailgun+ signature triple, so the verifier the outbound route already uses is what proves the caller is+ holding a real delivery. This is not a webhook path: nothing is ingested here.+ """+ if request.method != "POST":+ return HttpResponse(status=405)+ if _outbound_provider.verify(request).outcome is not VerificationOutcome.VERIFIED:+ return HttpResponse("Invalid signature", status=403)++ # Deferred because this module is on the URL conf's import path, and the ingestion modules+ # behind the facade are not cheap to import.+ from products.conversations.backend.facade.api import mailgun_sender_is_active_here # noqa: PLC0415+ from products.conversations.backend.services.mailgun_events import ( # noqa: PLC0415+ SENDER_STATUS_ABSENT,+ SENDER_STATUS_ABSENT_BODY,+ SENDER_STATUS_ACTIVE,+ )++ if mailgun_sender_is_active_here(request.POST.get("sender", "")):+ return HttpResponse(status=SENDER_STATUS_ACTIVE)+ # The body is what tells this answer apart from the 404 a region without this route answers.+ return JsonResponse(SENDER_STATUS_ABSENT_BODY, status=SENDER_STATUS_ABSENT)diff --git a/products/conversations/backend/api/tests/mailgun_signing.py b/products/conversations/backend/api/tests/mailgun_signing.pynew file mode 100644index 000000000000..afdc38977f77--- /dev/null+++ b/products/conversations/backend/api/tests/mailgun_signing.py@@ -0,0 +1,109 @@+"""Signing a Mailgun route delivery the way Mailgun does, for the email endpoint tests.++The endpoints verify through `posthog/ingress/`, which reads the signature out of the form and+refuses a timestamp outside a 5 minute window. So a test drives the real route rather than+stubbing the verifier, and posts a freshly signed form each time.+"""++import hmac+import time+import hashlib+from types import SimpleNamespace+from typing import Any+from uuid import uuid4++from unittest.mock import patch++from django.core.cache import cache+from django.test import Client+from django.utils import timezone++from posthog.ingress.contracts import WebhookDelivery+from posthog.ingress.mailgun.provider import FILES_KEY++from products.conversations.backend.services.mailgun_events import SENDER_STATUS_ABSENT, SENDER_STATUS_ABSENT_BODY++MAILGUN_SIGNING_KEY = "mailgun-signing-key"+_SIGNING_KEY_SETTING = "CONVERSATIONS_EMAIL_WEBHOOK_SIGNING_KEY"+# The transport behind the cross-region sender lookup, which a test patches to choose the answer.+SENDER_STATUS_REQUEST = "products.conversations.backend.services.mailgun_events.requests.post"+++def sender_status_response(status_code: int, payload: Any = SENDER_STATUS_ABSENT_BODY) -> SimpleNamespace:+ """What `requests` hands back from the other region's sender-status route.++ A payload of `None` is the region that has no such route yet, whose 404 carries an HTML error+ page rather than an answer.+ """++ def json() -> Any:+ if payload is None:+ raise ValueError("no JSON body")+ return payload++ return SimpleNamespace(status_code=status_code, json=json)+++def _instance_setting(name: str) -> str:+ return MAILGUN_SIGNING_KEY if name == _SIGNING_KEY_SETTING else ""+++def signed_mailgun_fields() -> dict[str, str]:+ """A fresh signature triple, with the token Mailgun mints per delivery.++ The token is the delivery id ingress dedups on, so it has to be new for every post: a real+ redelivery reuses it, and no test here is exercising a redelivery.+ """+ timestamp = str(int(time.time()))+ token = uuid4().hex+ signature = hmac.new(+ key=MAILGUN_SIGNING_KEY.encode("utf-8"),+ msg=f"{timestamp}{token}".encode(),+ digestmod=hashlib.sha256,+ ).hexdigest()+ return {"timestamp": timestamp, "token": token, "signature": signature}+++def post_mailgun(client: Client, path: str, data: dict[str, Any]) -> Any:+ return client.post(path, {**signed_mailgun_fields(), **data})+++def mailgun_delivery(fields: dict[str, Any], *, app: str = "inbound") -> WebhookDelivery:+ """What the provider hands a consumer for one route delivery, for a test that reads fields."""+ payload: dict[str, Any] = {**signed_mailgun_fields(), **fields}+ payload.setdefault(FILES_KEY, {})+ return WebhookDelivery(+ provider="mailgun",+ app=app,+ delivery_id=payload["token"],+ event_type="message_received",+ payload=payload,+ received_at=timezone.now(),+ context={},+ )+++class MailgunWebhookTestMixin:+ """Gives a test class a signing key the endpoints verify against, and an empty dedup cache.++ The outbound path asks the other region whether it also holds the sender. That is the only+ outbound call the service makes, and it answers "no" here, so a test that is not about the+ cross-region check reaches ingestion. A test that is about it patches the same target.+ """++ def setUp(self) -> None:+ super().setUp() # type: ignore[misc]+ signing_key = patch(+ "products.conversations.backend.mailgun.get_instance_setting",+ side_effect=_instance_setting,+ )+ signing_key.start()+ self.addCleanup(signing_key.stop) # type: ignore[attr-defined]++ sender_status = patch(+ SENDER_STATUS_REQUEST,+ return_value=sender_status_response(SENDER_STATUS_ABSENT),+ )+ sender_status.start()+ self.addCleanup(sender_status.stop) # type: ignore[attr-defined]+ cache.clear()diff --git a/products/conversations/backend/api/tests/test_customer_email_ingestion.py b/products/conversations/backend/api/tests/test_customer_email_ingestion.pyindex 24ee6068f146..6b616d300a05 100644--- a/products/conversations/backend/api/tests/test_customer_email_ingestion.py+++ b/products/conversations/backend/api/tests/test_customer_email_ingestion.py@@ -1,22 +1,32 @@import json-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom datetime import UTC, datetime, timedeltafrom uuid import uuid4+import pytestimport time_machinefrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.apps import apps-from django.test import Client, RequestFactory, SimpleTestCase+from django.db import OperationalError+from django.test import Client, SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized+from posthog.ingress.contracts import DeliveryOwnershipfrom posthog.models.comment import Commentfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import User+from products.conversations.backend.api.tests.mailgun_signing import (+ SENDER_STATUS_REQUEST,+ MailgunWebhookTestMixin,+ mailgun_delivery,+ post_mailgun,+ sender_status_response,+)from products.conversations.backend.models import (EMAIL_THREAD_COMMENT_SCOPE,EmailChannel,@@ -39,14 +49,17 @@ from products.conversations.backend.services.email_channel_setup import (from products.conversations.backend.services.mailgun_events import (MAX_FORWARDING_CHALLENGE_TOKENS,MAX_RECIPIENTS,+ MailgunRequest,_forwarding_challenge_tokens,_parse_addresses,_parse_sent_at,+ mailgun_inbound_delivery_ownership,+ mailgun_outbound_delivery_ownership,)from products.customer_analytics.backend.facade.email_matching import recalculate_email_thread_links-class TestCustomerEmailIngestion(BaseTest):+class TestCustomerEmailIngestion(MailgunWebhookTestMixin, BaseTest):def setUp(self) -> None:super().setUp()self.client = Client()@@ -61,12 +74,6 @@ class TestCustomerEmailIngestion(BaseTest):domain_verified=True,connection_status=EmailChannelConnectionStatus.ACTIVE,)- signature_patcher = patch(- "products.conversations.backend.services.mailgun_events.validate_webhook_signature",- return_value=True,- )- signature_patcher.start()- self.addCleanup(signature_patcher.stop)def _post_email(self,@@ -76,9 +83,6 @@ class TestCustomerEmailIngestion(BaseTest):**overrides: str,):data = {- "token": "webhook-token",- "timestamp": "1749565800",- "signature": "webhook-signature","recipient": recipient,"from": "Example customer <[email protected]>","sender": "[email protected]",@@ -90,19 +94,10 @@ class TestCustomerEmailIngestion(BaseTest):"body-plain": "Can you help?",}data.update(overrides)- return self.client.post("/api/conversations/v1/email/inbound", data)+ return post_mailgun(self.client, "/api/conversations/v1/email/inbound", data)- def _post_outbound_email(- self,- *,- message_id: str,- lookup_only: str = "",- **overrides: str,- ):+ def _post_outbound_email(self, *, message_id: str, **overrides: str):data = {- "token": "webhook-token",- "timestamp": "1749565800",- "signature": "webhook-signature","recipient": "[email protected]","from": "Customer success <[email protected]>","sender": "[email protected]",@@ -121,12 +116,7 @@ class TestCustomerEmailIngestion(BaseTest):),}data.update(overrides)- endpoint = (- "/api/conversations/v1/email/capture?sender_lookup=1"- if lookup_only == "1"- else "/api/conversations/v1/email/capture"- )- return self.client.post(endpoint, data)+ return post_mailgun(self.client, "/api/conversations/v1/email/capture", data)def _start_google_setup(self, *, expires_at=None) -> EmailChannelSetup:self.channel.connection_status = EmailChannelConnectionStatus.PENDING_CONFIRMATION@@ -163,8 +153,8 @@ class TestCustomerEmailIngestion(BaseTest):**self._valid_google_confirmation(action_suffix="replacement"),)- assert first_response.status_code == 200- assert second_response.status_code == 200+ assert first_response.status_code == 202+ assert second_response.status_code == 202setup.refresh_from_db()assert setup.confirmation_action == "https://mail-settings.google.com/mail/vf-expected"assert setup.confirmation_message_id_hash@@ -196,8 +186,8 @@ class TestCustomerEmailIngestion(BaseTest):first_response = self._post_email(message_id=f"<challenge-{transport}@posthog.com>", **payload)retry_response = self._post_email(message_id=f"<challenge-{transport}[email protected]>", **payload)- assert first_response.status_code == 200- assert retry_response.status_code == 200+ assert first_response.status_code == 202+ assert retry_response.status_code == 202self.channel.refresh_from_db()assert self.channel.connection_status == EmailChannelConnectionStatus.ACTIVEassert not EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()@@ -218,7 +208,7 @@ class TestCustomerEmailIngestion(BaseTest):**{FORWARDING_CHALLENGE_HEADER: challenge.token},)- assert response.status_code == 200+ assert response.status_code == 202self.channel.refresh_from_db()assert self.channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATIONassert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()@@ -236,7 +226,7 @@ class TestCustomerEmailIngestion(BaseTest):**{FORWARDING_CHALLENGE_HEADER: challenge.token},)- assert response.status_code == 200+ assert response.status_code == 202thread = EmailThread.objects.for_team(self.team.id).get()message = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get(thread=thread)assert message.comment.content == "Can you help?"@@ -256,7 +246,7 @@ class TestCustomerEmailIngestion(BaseTest):**{FORWARDING_CHALLENGE_HEADER: challenge.token},)- assert response.status_code == 200+ assert response.status_code == 202self.channel.refresh_from_db()assert self.channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATIONassert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()@@ -270,7 +260,7 @@ class TestCustomerEmailIngestion(BaseTest):**{FORWARDING_CHALLENGE_HEADER: "forged-token"},)- assert response.status_code == 200+ assert response.status_code == 202self.channel.refresh_from_db()assert self.channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATIONassert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()@@ -295,7 +285,7 @@ class TestCustomerEmailIngestion(BaseTest):response = self._post_email(message_id="<[email protected]>", **payload)- assert response.status_code == 200+ assert response.status_code == 202setup.refresh_from_db()assert setup.confirmation_action == "https://mail.google.com/mail/vf-%5Blive_token%5D-value"assert setup.confirmation_received_at is not None@@ -363,7 +353,7 @@ class TestCustomerEmailIngestion(BaseTest):response = self._post_email(message_id=f"<{_name}@gmail.com>", **payload)- assert response.status_code == 200+ assert response.status_code == 202setup.refresh_from_db()assert setup.confirmation_action is Noneassert not EmailThread.objects.for_team(self.team.id).exists()@@ -376,7 +366,7 @@ class TestCustomerEmailIngestion(BaseTest):**self._valid_google_confirmation(),)- assert response.status_code == 200+ assert response.status_code == 202assert not EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()self.channel.refresh_from_db()assert self.channel.connection_status == EmailChannelConnectionStatus.CONFIRMATION_EXPIRED@@ -408,8 +398,8 @@ class TestCustomerEmailIngestion(BaseTest):**reply_fields,)- assert root_response.status_code == 200- assert reply_response.status_code == 200+ assert root_response.status_code == 202+ assert reply_response.status_code == 202thread = EmailThread.objects.for_team(self.team.id).get()messages = list(EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread).select_related("comment")@@ -431,7 +421,7 @@ class TestCustomerEmailIngestion(BaseTest):def test_forwarded_message_schedules_account_matching(self, mock_schedule: MagicMock) -> None:response = self._post_email(message_id="<[email protected]>")- assert response.status_code == 200+ assert response.status_code == 202thread = EmailThread.objects.for_team(self.team.id).get()mock_schedule.assert_called_once_with(self.team.id, [str(thread.id)])@@ -443,7 +433,7 @@ class TestCustomerEmailIngestion(BaseTest):with self.captureOnCommitCallbacks(execute=True):response = self._post_email(message_id="<[email protected]>")- assert response.status_code == 200+ assert response.status_code == 202thread = EmailThread.objects.for_team(self.team.id).get()assert EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread).count() == 1assert not EmailThreadAccountLink.objects.for_team(self.team.id).exists()@@ -452,7 +442,7 @@ class TestCustomerEmailIngestion(BaseTest):outbound_message_id = "<[email protected]>"outbound_response = self._post_outbound_email(message_id=outbound_message_id)- assert outbound_response.status_code == 200+ assert outbound_response.status_code == 202thread = EmailThread.objects.for_team(self.team.id).get()assert not EmailThreadAccountLink.objects.for_team(self.team.id).filter(thread=thread).exists()@@ -477,7 +467,7 @@ class TestCustomerEmailIngestion(BaseTest):},)- assert reply_response.status_code == 200+ assert reply_response.status_code == 202recalculate_email_thread_links(self.team.id, thread_ids=[str(thread.id)])thread.refresh_from_db()messages = list(EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread))@@ -526,56 +516,166 @@ class TestCustomerEmailIngestion(BaseTest):])def test_outbound_capture_rejects_an_unauthenticated_sender(self, _name: str, overrides: dict[str, str]) -> None:- response = self._post_outbound_email(- message_id=f"<spoofed-{_name}@customer-success.example>",- **overrides,- )+ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ ):+ response = self._post_outbound_email(+ message_id=f"<spoofed-{_name}@customer-success.example>",+ **overrides,+ )- assert response.status_code == 200+ assert response.status_code == 202+ # The From header is the only thing naming a channel, so an unauthenticated one must not+ # make this region replay the delivery to the other one.+ mock_forward.assert_not_called()assert not EmailThread.objects.for_team(self.team.id).exists()@parameterized.expand([- ("secondary_absent", 404, 200, True),- ("sender_in_both_regions", 204, 200, False),- ("secondary_unavailable", None, 502, False),- ("secondary_error", 500, 502, False),+ ("the owning region accepts it", 202, 202),+ # Mailgun redelivers on a non-2xx, so a forward that never landed must not be receipted.+ ("the owning region is unreachable", 500, 502),])- @patch("products.conversations.backend.services.mailgun_events.request_secondary_region_status")- @patch("products.conversations.backend.services.mailgun_events.is_primary_region", return_value=True)- def test_primary_region_checks_secondary_before_ingesting(- self,- _name: str,- secondary_status: int | None,- expected_status: int,- expected_ingestion: bool,- _mock_primary: MagicMock,- mock_secondary_status: MagicMock,+ def test_a_sender_another_region_owns_is_forwarded_from_the_primary(+ self, _name: str, secondary_status: int, expected_status: int+ ) -> None:+ self.channel.connection_status = EmailChannelConnectionStatus.PENDING_CONFIRMATION+ self.channel.save(update_fields=["connection_status"])++ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ ):+ mock_forward.return_value = MagicMock(ok=200 <= secondary_status < 300, status_code=secondary_status)+ response = self._post_outbound_email(message_id=f"<region-{_name}@example.com>")++ assert response.status_code == expected_status+ mock_forward.assert_called_once()+ assert not EmailThread.objects.for_team(self.team.id).exists()++ def test_a_sender_this_region_owns_is_ingested_without_a_forward(self) -> None:+ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ ):+ response = self._post_outbound_email(message_id="<[email protected]>")++ assert response.status_code == 202+ mock_forward.assert_not_called()+ assert EmailThread.objects.for_team(self.team.id).exists()++ @parameterized.expand(+ [+ ("inbound", "_channel_for_inbound_token", "_post_email"),+ ("outbound", "_channel_for_outbound_sender", "_post_outbound_email"),+ ]+ )+ def test_a_timed_out_ownership_lookup_asks_mailgun_to_redeliver(+ self, _name: str, lookup: str, post_email: str) -> None:- mock_secondary_status.return_value = secondary_status+ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ patch(+ f"products.conversations.backend.services.mailgun_events.{lookup}",+ side_effect=OperationalError("canceling statement due to statement timeout"),+ ),+ ):+ response = getattr(self, post_email)(message_id=f"<lookup-timeout-{_name}@example.com>")- response = self._post_outbound_email(message_id=f"<region-{_name}@example.com>")+ assert response.status_code == 502+ mock_forward.assert_not_called()+ assert not EmailThread.objects.for_team(self.team.id).exists()++ @parameterized.expand(+ [+ # Channel uniqueness is per region, so a sender active in both would attach one team's+ # private outbound mail to the other team's thread.+ ("the sender is active in both regions", 204, None, 202, False),+ ("only this region holds the sender", 404, {"sender_active": False}, 202, True),+ # The question went unanswered, so Mailgun has to ask it again.+ ("the other region answers nothing useful", 500, None, 502, False),+ # A region that has not deployed this route yet answers Django's own 404 page. That is+ # an unanswered question, not an answer of "no channel there".+ ("the other region has no such route yet", 404, None, 502, False),+ ]+ )+ def test_the_primary_region_asks_the_other_region_before_it_ingests_a_capture(+ self, _name: str, sender_status: int, sender_body: dict | None, expected_status: int, expected_ingestion: bool+ ) -> None:+ with patch(SENDER_STATUS_REQUEST) as mock_sender_status:+ mock_sender_status.return_value = sender_status_response(sender_status, sender_body)+ response = self._post_outbound_email(message_id=f"<ambiguous-{_name}@example.com>")assert response.status_code == expected_status+ mock_sender_status.assert_called_once()assert EmailThread.objects.for_team(self.team.id).exists() is expected_ingestion@parameterized.expand([- ("active", EmailChannelConnectionStatus.ACTIVE, 204),- ("pending_confirmation", EmailChannelConnectionStatus.PENDING_CONFIRMATION, 404),- ("confirmation_expired", EmailChannelConnectionStatus.CONFIRMATION_EXPIRED, 404),+ # A host other than the primary domain makes this deployment the secondary, which+ # would otherwise ask itself and always find its own channel.+ ("this deployment is the secondary region", {"SITE_URL": "https://us.posthog.com"}),+ # Both region domains point at the one development server, so there is no second+ # region to be ambiguous with and the probe would only fail the local capture.+ ("this deployment is a development server", {"DEBUG": True}),])- def test_outbound_sender_lookup_returns_only_active_channels(- self, _name: str, connection_status: EmailChannelConnectionStatus, expected_status: int+ def test_the_sender_probe_is_skipped_where_there_is_no_other_region(+ self, _name: str, settings_override: dict) -> None:- self.channel.connection_status = connection_status- self.channel.save(update_fields=["connection_status"])+ with self.settings(**settings_override), patch(SENDER_STATUS_REQUEST) as mock_sender_status:+ response = self._post_outbound_email(message_id=f"<no-probe-{_name}@example.com>")- response = self._post_outbound_email(- message_id=f"<lookup-{_name}@customer-success.example>",- lookup_only="1",+ assert response.status_code == 202+ mock_sender_status.assert_not_called()+ assert EmailThread.objects.for_team(self.team.id).exists()++ def test_the_sender_status_endpoint_answers_only_a_signed_caller(self) -> None:+ unsigned = self.client.post("/api/conversations/v1/email/sender-status", {"sender": self.channel.from_email})+ active = post_mailgun(+ self.client, "/api/conversations/v1/email/sender-status", {"sender": self.channel.from_email}+ )+ absent = post_mailgun(+ self.client, "/api/conversations/v1/email/sender-status", {"sender": "[email protected]"}+ )++ assert unsigned.status_code == 403+ assert active.status_code == 204+ assert absent.status_code == 404++ @parameterized.expand(+ [+ ("outbound, the sender is active here", "outbound", "[email protected]", 204),+ ("outbound, no channel here sends as the sender", "outbound", "[email protected]", 404),+ ("capture, the sender is active here", "capture", "[email protected]", 204),+ ("capture, no channel here sends as the sender", "capture", "[email protected]", 404),+ ]+ )+ def test_the_outbound_routes_answer_a_legacy_sender_probe_without_ingesting(+ self, _name: str, route: str, sender_email: str, expected_status: int+ ) -> None:+ response = post_mailgun(+ self.client,+ f"/api/conversations/v1/email/{route}?sender_lookup=1",+ {+ "recipient": "[email protected]",+ "from": f"Customer success <{sender_email}>",+ "sender": sender_email,+ "To": "Prospect <[email protected]>",+ "Message-Id": f"<legacy-probe-{_name}@example.com>",+ "subject": "Account update",+ "body-plain": "Here is your account update.",+ "message-headers": json.dumps(+ [+ ["X-Mailgun-Spf", "Fail"],+ ["X-Mailgun-Dkim-Check-Result", "Pass"],+ ["DKIM-Signature", "v=1; a=rsa-sha256; d=example.com; s=mail"],+ ]+ ),+ },)assert response.status_code == expected_status@@ -595,7 +695,7 @@ class TestCustomerEmailIngestion(BaseTest):response = self._post_outbound_email(message_id=f"<outbound-{_name}@customer-success.example>")- assert response.status_code == 200+ assert response.status_code == 202assert not EmailThread.objects.for_team(self.team.id).exists()def test_outbound_capture_drops_internal_only_messages(self) -> None:@@ -611,7 +711,7 @@ class TestCustomerEmailIngestion(BaseTest):To="Colleague <[email protected]>",)- assert response.status_code == 200+ assert response.status_code == 202assert not EmailThread.objects.for_team(self.team.id).exists()def test_duplicate_delivery_creates_one_message_across_customer_channels(self) -> None:@@ -641,9 +741,9 @@ class TestCustomerEmailIngestion(BaseTest):recipient="[email protected]",)- assert first_response.status_code == 200- assert retry_response.status_code == 200- assert second_owner_response.status_code == 200+ assert first_response.status_code == 202+ assert retry_response.status_code == 202+ assert second_owner_response.status_code == 202thread = EmailThread.objects.for_team(self.team.id).get()assert thread.message_count == 1assert EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread).count() == 1@@ -660,13 +760,11 @@ class TestCustomerEmailIngestion(BaseTest):response = self._post_email(message_id="<[email protected]>")- assert response.status_code == 200+ assert response.status_code == 202assert not EmailThread.objects.for_team(self.team.id).exists()class TestForwardingChallengeTokens(SimpleTestCase):- factory = RequestFactory()-def test_stops_reading_headers_after_reaching_the_token_limit(self) -> None:class HeaderValues(list[list[str]]):def __iter__(self) -> Iterator[list[str]]:@@ -674,7 +772,7 @@ class TestForwardingChallengeTokens(SimpleTestCase):yield [FORWARDING_CHALLENGE_HEADER, f"token-{index}"]raise AssertionError("challenge extraction read beyond its limit")- request = self.factory.post("/", {"message-headers": "[]"})+ request = MailgunRequest(mailgun_delivery({"message-headers": "[]"}))with patch("products.conversations.backend.services.mailgun_events.json.loads", return_value=HeaderValues()):tokens = _forwarding_challenge_tokens(request)@@ -691,8 +789,6 @@ class TestParseAddresses(SimpleTestCase):class TestParseSentAt(SimpleTestCase):- factory = RequestFactory()-@parameterized.expand([# A far-future Date header is rejected and falls back to the authenticated timestamp.@@ -702,6 +798,61 @@ class TestParseSentAt(SimpleTestCase):])def test_parse_sent_at(self, _name: str, date_header: str, expected: datetime) -> None:- request = self.factory.post("/", {"Date": date_header, "timestamp": "1749565800"})+ request = MailgunRequest(mailgun_delivery({"Date": date_header, "timestamp": "1749565800"}))assert _parse_sent_at(request) == expected+++OUTBOUND_OWNERSHIP_DELIVERY = {+ "recipient": "[email protected]",+ "from": "Customer success <[email protected]>",+ "sender": "[email protected]",+ "message-headers": json.dumps(+ [+ ["X-Mailgun-Spf", "Fail"],+ ["X-Mailgun-Dkim-Check-Result", "Pass"],+ ["DKIM-Signature", "v=1; a=rsa-sha256; d=example.com; s=mail"],+ ]+ ),+}+++class TestOwnershipOfATimedOutChannelLookup(SimpleTestCase):+ STATEMENT_TIMEOUT = OperationalError("canceling statement due to statement timeout")++ @parameterized.expand(+ [+ (+ "inbound",+ "_channel_for_inbound_token",+ {"recipient": "[email protected]"},+ "inbound",+ mailgun_inbound_delivery_ownership,+ ),+ (+ "outbound",+ "_channel_for_outbound_sender",+ OUTBOUND_OWNERSHIP_DELIVERY,+ "outbound",+ mailgun_outbound_delivery_ownership,+ ),+ ]+ )+ def test_a_lookup_that_times_out_never_answers_elsewhere(+ self,+ _name: str,+ lookup: str,+ fields: dict[str, str],+ app: str,+ ownership: Callable[..., DeliveryOwnership],+ ) -> None:+ delivery = mailgun_delivery(fields, app=app)++ with (+ patch(+ f"products.conversations.backend.services.mailgun_events.{lookup}",+ side_effect=self.STATEMENT_TIMEOUT,+ ),+ pytest.raises(OperationalError),+ ):+ ownership(delivery)diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex ced44ff8c233..36bcfcb924f9 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -17,6 +17,7 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import User+from products.conversations.backend.api.tests.mailgun_signing import MailgunWebhookTestMixin, post_mailgunfrom products.conversations.backend.mailgun import (MailgunDomainConflict,MailgunDomainNotRegistered,@@ -1485,44 +1486,50 @@ class TestEmailMultiConfig(BaseTest):assert response.status_code == 404-class TestEmailInboundRegionRouting(BaseTest):+class TestEmailInboundRegionRouting(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()def _post(self, data: dict[str, str]):- return self.client.post("/api/conversations/v1/email/inbound", data=data)+ return post_mailgun(self.client, "/api/conversations/v1/email/inbound", data=data)- @patch("products.conversations.backend.services.mailgun_events.proxy_to_secondary_region", return_value=True)- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- @patch("products.conversations.backend.services.mailgun_events.is_primary_region", return_value=True)- def test_proxies_to_secondary_when_token_not_found_on_primary(- self, _mock_region: MagicMock, _mock_sig: MagicMock, mock_proxy: MagicMock+ @parameterized.expand(+ [+ ("the owning region accepts it", 202, 202),+ # Mailgun redelivers on a non-2xx, so a forward that never landed must not be receipted.+ ("the owning region is unreachable", 500, 502),+ ]+ )+ def test_an_inbox_another_region_owns_is_forwarded_from_the_primary(+ self, _name: str, secondary_status: int, expected_status: int):- response = self._post({"recipient": "[email protected]"})+ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ ):+ mock_forward.return_value = MagicMock(ok=200 <= secondary_status < 300, status_code=secondary_status)+ response = self._post({"recipient": "[email protected]"})- assert response.status_code == 200- mock_proxy.assert_called_once()+ assert response.status_code == expected_status+ mock_forward.assert_called_once()- @patch("products.conversations.backend.services.mailgun_events.proxy_to_secondary_region", return_value=False)- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- @patch("products.conversations.backend.services.mailgun_events.is_primary_region", return_value=True)- def test_returns_502_when_proxy_fails(self, _mock_region: MagicMock, _mock_sig: MagicMock, mock_proxy: MagicMock):- response = self._post({"recipient": "[email protected]"})+ def test_an_unknown_inbox_is_not_forwarded_again_from_the_secondary(self):+ with patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward:+ response = self._post({"recipient": "[email protected]"})- assert response.status_code == 502- mock_proxy.assert_called_once()+ assert response.status_code == 202+ mock_forward.assert_not_called()- @patch("products.conversations.backend.services.mailgun_events.proxy_to_secondary_region")- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- @patch("products.conversations.backend.services.mailgun_events.is_primary_region", return_value=False)- def test_returns_404_when_token_not_found_on_secondary(- self, _mock_region: MagicMock, _mock_sig: MagicMock, mock_proxy: MagicMock- ):- response = self._post({"recipient": "[email protected]"})+ def test_a_recipient_that_names_no_inbox_is_not_forwarded(self):+ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,+ ):+ response = self._post({"recipient": "[email protected]"})- assert response.status_code == 404- mock_proxy.assert_not_called()+ assert response.status_code == 202+ mock_forward.assert_not_called()class TestBuildProxyKwargs(BaseTest):@@ -1578,7 +1585,7 @@ class TestBuildProxyKwargs(BaseTest):assert "content-type" not in {k.lower() for k in result["headers"]}-class TestEmailInboundMultiConfig(BaseTest):+class TestEmailInboundMultiConfig(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()@@ -1596,12 +1603,12 @@ class TestEmailInboundMultiConfig(BaseTest):domain_verified=True,)- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_routes_to_correct_config(self, _mock_sig: MagicMock):+ def test_inbound_routes_to_correct_config(self):config1 = self._create_config("[email protected]", "aaa111")self._create_config("[email protected]", "bbb222")- response = self.client.post(+ response = post_mailgun(+ self.client,"/api/conversations/v1/email/inbound",{"recipient": "[email protected]",@@ -1611,18 +1618,18 @@ class TestEmailInboundMultiConfig(BaseTest):"stripped-text": "I need help",},)- assert response.status_code == 200+ assert response.status_code == 202ticket = Ticket.objects.get(team=self.team)assert ticket.email_config_id == config1.idassert ticket.email_from == "[email protected]"- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_routes_to_second_config(self, _mock_sig: MagicMock):+ def test_inbound_routes_to_second_config(self):self._create_config("[email protected]", "aaa111")config2 = self._create_config("[email protected]", "bbb222")- response = self.client.post(+ response = post_mailgun(+ self.client,"/api/conversations/v1/email/inbound",{"recipient": "[email protected]",@@ -1632,13 +1639,13 @@ class TestEmailInboundMultiConfig(BaseTest):"stripped-text": "Here is your invoice",},)- assert response.status_code == 200+ assert response.status_code == 202ticket = Ticket.objects.get(team=self.team)assert ticket.email_config_id == config2.id-class TestEmailInboundContent(BaseTest):+class TestEmailInboundContent(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()@@ -1684,11 +1691,9 @@ class TestEmailInboundContent(BaseTest):),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_content_extraction(- self, _name: str, body_fields: dict[str, str], expected_content: str, _mock_sig: MagicMock- ):- response = self.client.post(+ def test_inbound_content_extraction(self, _name: str, body_fields: dict[str, str], expected_content: str):+ response = post_mailgun(+ self.client,"/api/conversations/v1/email/inbound",{"recipient": "[email protected]",@@ -1698,7 +1703,7 @@ class TestEmailInboundContent(BaseTest):**body_fields,},)- assert response.status_code == 200+ assert response.status_code == 202comment = Comment.objects.get(team=self.team, scope="conversations_ticket")mapping = EmailMessageMapping.objects.get(comment=comment)@@ -1708,18 +1713,19 @@ class TestEmailInboundContent(BaseTest):assert item_context["has_full_email_content"] is Falseassert mapping.full_body_plain is None- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_reply_strips_quoted_thread(self, _mock_sig: MagicMock):+ def test_reply_strips_quoted_thread(self):base = {"recipient": "[email protected]","from": "[email protected]","subject": "Help",}- self.client.post(+ post_mailgun(+ self.client,"/api/conversations/v1/email/inbound",{**base, "Message-Id": "<[email protected]>", "stripped-text": "Initial question"},)- response = self.client.post(+ response = post_mailgun(+ self.client,"/api/conversations/v1/email/inbound",{**base,@@ -1729,7 +1735,7 @@ class TestEmailInboundContent(BaseTest):"body-plain": "Thanks, that worked\n\nOn Mon, Support wrote:\n> Initial question",},)- assert response.status_code == 200+ assert response.status_code == 202reply = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")[1]assert reply.content == "Thanks, that worked"@@ -1753,7 +1759,6 @@ class TestEmailInboundContent(BaseTest):("line_endings_only", "Same reply\nSame details", "Same reply\r\nSame details", "", None),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)def test_reply_full_body_preservation(self,_name: str,@@ -1761,19 +1766,20 @@ class TestEmailInboundContent(BaseTest):full_body_plain: str,body_html: str,expected_full_body: str | None,- _mock_sig: MagicMock,) -> None:base = {"recipient": "[email protected]","from": "[email protected]","subject": "Help",}- self.client.post(+ post_mailgun(+ self.client,"/api/conversations/v1/email/inbound",{**base, "Message-Id": "<[email protected]>", "stripped-text": "Initial question"},)- response = self.client.post(+ response = post_mailgun(+ self.client,"/api/conversations/v1/email/inbound",{**base,@@ -1784,7 +1790,7 @@ class TestEmailInboundContent(BaseTest):"body-html": body_html,},)- assert response.status_code == 200+ assert response.status_code == 202ticket = Ticket.objects.get(team=self.team)reply = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")[1]@@ -2140,7 +2146,7 @@ class TestSendEmailReplyMultiConfig(BaseTest):assert outbox.status == expected_status-class TestEmailInboundDmarcRewrite(BaseTest):+class TestEmailInboundDmarcRewrite(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()@@ -2240,23 +2246,21 @@ class TestEmailInboundDmarcRewrite(BaseTest):),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_dmarc_sender_recovery(self, _name, extra_headers, expected_email, expected_name, _mock_sig):+ def test_dmarc_sender_recovery(self, _name, extra_headers, expected_email, expected_name):data = self._base_data(f"<dmarc-{_name}@test.com>")data.update(extra_headers)- self.client.post("/api/conversations/v1/email/inbound", data)+ post_mailgun(self.client, "/api/conversations/v1/email/inbound", data)ticket = Ticket.objects.get(team=self.team)assert ticket.email_from == expected_emailassert ticket.anonymous_traits["email"] == expected_emailassert ticket.anonymous_traits["name"] == expected_name- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_recovered_sender_flows_to_comment_context(self, _mock_sig: MagicMock):+ def test_recovered_sender_flows_to_comment_context(self):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)+ post_mailgun(self.client, "/api/conversations/v1/email/inbound", data)ticket = Ticket.objects.get(team=self.team)assert ticket.distinct_id == "[email protected]"@@ -2267,7 +2271,7 @@ class TestEmailInboundDmarcRewrite(BaseTest):assert comment.item_context["email_from_name"] == "Alex Smith"-class TestEmailInboundSelfAddressedAutoreply(BaseTest):+class TestEmailInboundSelfAddressedAutoreply(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()@@ -2291,7 +2295,7 @@ class TestEmailInboundSelfAddressedAutoreply(BaseTest):"To": "[email protected]",**extra,}- self.client.post("/api/conversations/v1/email/inbound", data)+ post_mailgun(self.client, "/api/conversations/v1/email/inbound", data)@parameterized.expand([@@ -2301,14 +2305,12 @@ class TestEmailInboundSelfAddressedAutoreply(BaseTest):("x_autoreply", {"X-Autoreply": "yes"}),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_autoreply_from_the_inbox_itself_is_dropped(self, name, headers, _mock_sig):+ def test_autoreply_from_the_inbox_itself_is_dropped(self, name, headers):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.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_autoreply_from_the_inbound_address_is_dropped(self, _mock_sig: MagicMock):+ def test_autoreply_from_the_inbound_address_is_dropped(self):self._post("<[email protected]>",{"from": "[email protected]", "Auto-Submitted": "auto-replied"},@@ -2316,8 +2318,7 @@ class TestEmailInboundSelfAddressedAutoreply(BaseTest):assert Ticket.objects.filter(team=self.team).count() == 0- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_auto_submitted_header_is_read_from_the_message_headers_blob(self, _mock_sig: MagicMock):+ def test_auto_submitted_header_is_read_from_the_message_headers_blob(self):self._post("<[email protected]>",{@@ -2339,14 +2340,12 @@ class TestEmailInboundSelfAddressedAutoreply(BaseTest):("auto_submitted_no", {"from": "Alex Smith <[email protected]>", "Auto-Submitted": "no"}),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_self_addressed_human_mail_still_opens_a_ticket(self, name, headers, _mock_sig):+ def test_self_addressed_human_mail_still_opens_a_ticket(self, name, headers):self._post(f"<human-{name}@posthog.com>", headers)assert Ticket.objects.filter(team=self.team).count() == 1- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_external_automated_mail_still_opens_a_ticket(self, _mock_sig: MagicMock):+ def test_external_automated_mail_still_opens_a_ticket(self):# 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(@@ -2358,7 +2357,7 @@ class TestEmailInboundSelfAddressedAutoreply(BaseTest):assert ticket.email_from == "[email protected]"-class TestEmailInboundTeamMemberDetection(BaseTest):+class TestEmailInboundTeamMemberDetection(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()@@ -2374,10 +2373,9 @@ class TestEmailInboundTeamMemberDetection(BaseTest):)def _post(self, data: dict[str, str]):- return self.client.post("/api/conversations/v1/email/inbound", data)+ return post_mailgun(self.client, "/api/conversations/v1/email/inbound", data)- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_team_member_reply_attribution_and_unread(self, _mock_sig: MagicMock):+ def test_team_member_reply_attribution_and_unread(self):self._post({"recipient": "[email protected]",@@ -2417,8 +2415,7 @@ class TestEmailInboundTeamMemberDetection(BaseTest):ticket.refresh_from_db()assert ticket.unread_team_count == 1- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_team_member_inbound_stamps_from_email_and_no_outbox(self, _mock_sig: MagicMock):+ def test_team_member_inbound_stamps_from_email_and_no_outbox(self):self._post({"recipient": "[email protected]",@@ -2447,8 +2444,7 @@ class TestEmailInboundTeamMemberDetection(BaseTest):assert support_comment.item_context["author_type"] == "support"assert EmailOutboxMessage.objects.filter(comment=support_comment).count() == 0- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_customer_inbound_stamps_from_email(self, _mock_sig: MagicMock):+ def test_customer_inbound_stamps_from_email(self):self._post({"recipient": "[email protected]",@@ -2472,9 +2468,8 @@ class TestEmailInboundTeamMemberDetection(BaseTest):("spf_pass_misaligned_domain", {"sender": "[email protected]", "X-Mailgun-Spf": "Pass"}, False),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)def test_inbound_identity_verified_reflects_spf(- self, _name: str, extra_fields: dict[str, str], expected_verified: bool, _mock_sig: MagicMock+ self, _name: str, extra_fields: dict[str, str], expected_verified: bool):self._post({@@ -2489,8 +2484,7 @@ class TestEmailInboundTeamMemberDetection(BaseTest):ticket = Ticket.objects.get(team=self.team)assert ticket.identity_verified is expected_verified- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_no_spf_treated_as_customer(self, _mock_sig: MagicMock):+ def test_no_spf_treated_as_customer(self):"""From header matches a team member but no SPF pass → customer."""self._post({@@ -2515,8 +2509,7 @@ class TestEmailInboundTeamMemberDetection(BaseTest):assert forged.item_context["author_type"] == "customer"assert forged.created_by is None- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_spf_pass_but_mismatched_envelope_treated_as_customer(self, _mock_sig: MagicMock):+ def test_spf_pass_but_mismatched_envelope_treated_as_customer(self):"""SPF passes but envelope sender domain != From domain → customer."""self._post({@@ -2552,9 +2545,8 @@ class TestEmailInboundTeamMemberDetection(BaseTest):("different_sender", "[email protected]", "[email protected]", False),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)def test_promotion_requires_authenticated_sender_to_match_ticket_identity(- self, _name: str, claimed_email: str, reply_sender: str, expected_verified: bool, _mock_sig: MagicMock+ self, _name: str, claimed_email: str, reply_sender: str, expected_verified: bool):# First message: unauthenticated (no SPF) → unverified ticket claiming `claimed_email`.self._post(@@ -2582,7 +2574,7 @@ class TestEmailInboundTeamMemberDetection(BaseTest):assert ticket.identity_verified is expected_verified-class TestEmailInboundCcParticipants(BaseTest):+class TestEmailInboundCcParticipants(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()@@ -2630,23 +2622,21 @@ class TestEmailInboundCcParticipants(BaseTest):("to_and_cc_merged", "[email protected]", "[email protected]", ["[email protected]", "[email protected]"]),])- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_new_ticket_participants(self, _name, to_header, cc_header, expected, _mock_sig):+ def test_new_ticket_participants(self, _name, to_header, cc_header, expected):data = self._base_data(f"<cc-{_name}@test.com>")if to_header:data["To"] = to_headerif cc_header:data["Cc"] = cc_header- response = self.client.post("/api/conversations/v1/email/inbound", data)- assert response.status_code == 200+ response = post_mailgun(self.client, "/api/conversations/v1/email/inbound", data)+ assert response.status_code == 202ticket = Ticket.objects.get(team=self.team)assert ticket.cc_participants == expected- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_reply_merges_cc_participants(self, _mock_sig: MagicMock):+ def test_reply_merges_cc_participants(self):data1 = self._base_data("<[email protected]>")data1["Cc"] = "[email protected]"- self.client.post("/api/conversations/v1/email/inbound", data1)+ post_mailgun(self.client, "/api/conversations/v1/email/inbound", data1)ticket = Ticket.objects.get(team=self.team)assert ticket.cc_participants == ["[email protected]"]@@ -2654,7 +2644,7 @@ class TestEmailInboundCcParticipants(BaseTest):data2 = self._base_data("<[email protected]>")data2["In-Reply-To"] = "<[email protected]>"data2["Cc"] = "[email protected], [email protected]"- self.client.post("/api/conversations/v1/email/inbound", data2)+ post_mailgun(self.client, "/api/conversations/v1/email/inbound", data2)ticket.refresh_from_db()assert ticket.cc_participants == ["[email protected]", "[email protected]"]@@ -2666,13 +2656,13 @@ class TestEmailInboundCcParticipants(BaseTest):data3["In-Reply-To"] = "<[email protected]>"data3["To"] = "[email protected], [email protected]"data3["Cc"] = "[email protected]"- self.client.post("/api/conversations/v1/email/inbound", data3)+ post_mailgun(self.client, "/api/conversations/v1/email/inbound", data3)ticket.refresh_from_db()assert ticket.cc_participants == ["[email protected]", "[email protected]"]-class TestEmailInboundAttachments(BaseTest):+class TestEmailInboundAttachments(MailgunWebhookTestMixin, BaseTest):def setUp(self):super().setUp()self.client = Client()@@ -2697,15 +2687,16 @@ class TestEmailInboundAttachments(BaseTest):}@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_with_image_attachment(self, _mock_sig: MagicMock, mock_storage: MagicMock):+ def test_inbound_with_image_attachment(self, mock_storage: MagicMock):attachment = SimpleUploadedFile("photo.png", _make_png_bytes(), content_type="image/png")data = self._base_post_data("<[email protected]>")with self.settings(OBJECT_STORAGE_ENABLED=True):- response = self.client.post("/api/conversations/v1/email/inbound", {**data, "attachment-1": attachment})+ response = post_mailgun(+ self.client, "/api/conversations/v1/email/inbound", {**data, "attachment-1": attachment}+ )- assert response.status_code == 200+ assert response.status_code == 202mock_storage.assert_called_once()comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").first()@@ -2720,15 +2711,14 @@ class TestEmailInboundAttachments(BaseTest):assert comment.item_context["email_attachments"][0]["content_type"] == "image/png"@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_with_non_image_attachment(self, _mock_sig: MagicMock, mock_storage: MagicMock):+ def test_inbound_with_non_image_attachment(self, mock_storage: MagicMock):pdf = SimpleUploadedFile("invoice.pdf", b"%PDF-1.4 fake content", content_type="application/pdf")data = self._base_post_data("<[email protected]>")with self.settings(OBJECT_STORAGE_ENABLED=True):- response = self.client.post("/api/conversations/v1/email/inbound", {**data, "attachment-1": pdf})+ response = post_mailgun(self.client, "/api/conversations/v1/email/inbound", {**data, "attachment-1": pdf})- assert response.status_code == 200+ assert response.status_code == 202comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").first()assert comment is not None@@ -2743,18 +2733,17 @@ class TestEmailInboundAttachments(BaseTest):assert len(link_nodes) == 1@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_with_multiple_attachments(self, _mock_sig: MagicMock, mock_storage: MagicMock):+ def test_inbound_with_multiple_attachments(self, mock_storage: MagicMock):png = SimpleUploadedFile("photo.png", _make_png_bytes(), content_type="image/png")pdf = SimpleUploadedFile("doc.pdf", b"%PDF-1.4 content", content_type="application/pdf")data = self._base_post_data("<[email protected]>")with self.settings(OBJECT_STORAGE_ENABLED=True):- response = self.client.post(- "/api/conversations/v1/email/inbound", {**data, "attachment-1": png, "attachment-2": pdf}+ response = post_mailgun(+ self.client, "/api/conversations/v1/email/inbound", {**data, "attachment-1": png, "attachment-2": pdf})- assert response.status_code == 200+ assert response.status_code == 202assert mock_storage.call_count == 2comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").first()@@ -2766,15 +2755,16 @@ class TestEmailInboundAttachments(BaseTest):@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")@patch("products.conversations.backend.services.mailgun_events.MAX_ATTACHMENT_SIZE", 100)- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_attachment_too_large_is_skipped(self, _mock_sig: MagicMock, mock_storage: MagicMock):+ def test_inbound_attachment_too_large_is_skipped(self, mock_storage: MagicMock):oversized = SimpleUploadedFile("big.bin", b"x" * 101, content_type="application/octet-stream")data = self._base_post_data("<[email protected]>")with self.settings(OBJECT_STORAGE_ENABLED=True):- response = self.client.post("/api/conversations/v1/email/inbound", {**data, "attachment-1": oversized})+ response = post_mailgun(+ self.client, "/api/conversations/v1/email/inbound", {**data, "attachment-1": oversized}+ )- assert response.status_code == 200+ assert response.status_code == 202mock_storage.assert_not_called()comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").first()@@ -2784,15 +2774,14 @@ class TestEmailInboundAttachments(BaseTest):assert comment.item_context.get("email_attachments") is None@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_without_object_storage_skips_attachments(self, _mock_sig: MagicMock, mock_storage: MagicMock):+ def test_inbound_without_object_storage_skips_attachments(self, mock_storage: MagicMock):png = SimpleUploadedFile("photo.png", _make_png_bytes(), content_type="image/png")data = self._base_post_data("<[email protected]>")with self.settings(OBJECT_STORAGE_ENABLED=False):- response = self.client.post("/api/conversations/v1/email/inbound", {**data, "attachment-1": png})+ response = post_mailgun(self.client, "/api/conversations/v1/email/inbound", {**data, "attachment-1": png})- assert response.status_code == 200+ assert response.status_code == 202mock_storage.assert_not_called()comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").first()@@ -2801,15 +2790,16 @@ class TestEmailInboundAttachments(BaseTest):assert comment.rich_content is None@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_invalid_image_is_rejected(self, _mock_sig: MagicMock, mock_storage: MagicMock):+ def test_inbound_invalid_image_is_rejected(self, mock_storage: MagicMock):fake_image = SimpleUploadedFile("evil.png", b"<html>not an image</html>", content_type="image/png")data = self._base_post_data("<[email protected]>")with self.settings(OBJECT_STORAGE_ENABLED=True):- response = self.client.post("/api/conversations/v1/email/inbound", {**data, "attachment-1": fake_image})+ response = post_mailgun(+ self.client, "/api/conversations/v1/email/inbound", {**data, "attachment-1": fake_image}+ )- assert response.status_code == 200+ assert response.status_code == 202mock_storage.assert_not_called()comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").first()@@ -2818,13 +2808,12 @@ class TestEmailInboundAttachments(BaseTest):assert comment.rich_content is None@patch("products.conversations.backend.services.attachments.save_content_to_object_storage")- @patch("products.conversations.backend.services.mailgun_events.validate_webhook_signature", return_value=True)- def test_inbound_no_attachments_unchanged(self, _mock_sig: MagicMock, mock_storage: MagicMock):+ def test_inbound_no_attachments_unchanged(self, mock_storage: MagicMock):data = self._base_post_data("<[email protected]>")with self.settings(OBJECT_STORAGE_ENABLED=True):- response = self.client.post("/api/conversations/v1/email/inbound", data)+ response = post_mailgun(self.client, "/api/conversations/v1/email/inbound", data)- assert response.status_code == 200+ assert response.status_code == 202mock_storage.assert_not_called()comment = Comment.objects.filter(team=self.team, scope="conversations_ticket").first()diff --git a/products/conversations/backend/api/urls.py b/products/conversations/backend/api/urls.pyindex e9408838fbd8..d3b098863ba2 100644--- a/products/conversations/backend/api/urls.py+++ b/products/conversations/backend/api/urls.py@@ -2,12 +2,12 @@from django.urls import path, re_path-from products.conversations.backend.services.mailgun_events import (+from .email_events import (email_capture_handler,email_inbound_handler,email_outbound_handler,+ email_sender_status_handler,)-from .email_settings import (EmailConfirmForwardingView,EmailConnectView,@@ -64,6 +64,7 @@ urlpatterns = [re_path(r"^v1/email/capture/?$", email_capture_handler, name="email-capture"),re_path(r"^v1/email/inbound/?$", email_inbound_handler, name="email-inbound"),re_path(r"^v1/email/outbound/?$", email_outbound_handler, name="email-outbound"),+ re_path(r"^v1/email/sender-status/?$", email_sender_status_handler, name="email-sender-status"),re_path(r"^v1/email/status/?$", EmailStatusView.as_view(), name="email-status"),re_path(r"^v1/email/connect/?$", EmailConnectView.as_view(), name="email-connect"),re_path(diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 20fc0c720b67..5f3d53e49052 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -162,6 +162,81 @@ def teams_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:return teams_events.teams_delivery_ownership(delivery)+def accept_mailgun_inbound_message(delivery: WebhookDelivery) -> None:+ """The Mailgun inbox route enters conversations here, so its consumer needs no internal import."""+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ mailgun_events.accept_mailgun_inbound_message(delivery)+++def accept_mailgun_outbound_message(delivery: WebhookDelivery) -> None:+ """The Mailgun outbound capture route enters conversations here."""+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ mailgun_events.accept_mailgun_outbound_message(delivery)+++def accept_mailgun_captured_message(delivery: WebhookDelivery) -> None:+ """The Mailgun catch-all route enters conversations here, for either direction."""+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ mailgun_events.accept_mailgun_captured_message(delivery)+++def mailgun_inbound_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Whether this region holds the email channel the delivery's inbox address belongs to.++ Ingress asks before it dispatches, and forwards the signed request to the other region when+ the answer is elsewhere.+ """+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ return mailgun_events.mailgun_inbound_delivery_ownership(delivery)+++def mailgun_outbound_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Whether this region holds the email channel the captured message was sent from."""+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ return mailgun_events.mailgun_outbound_delivery_ownership(delivery)+++def mailgun_capture_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Whether this region holds the email channel the catch-all delivery belongs to."""+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ return mailgun_events.mailgun_capture_delivery_ownership(delivery)+++def mailgun_sender_is_active_here(sender_email: str) -> bool:+ """Whether this region holds an active customer-communication channel sending as this address.++ The other region asks before it ingests a captured outbound message, because a sender active+ in both regions would otherwise land on the wrong team's thread.+ """+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ return mailgun_events.mailgun_sender_is_active_here(sender_email)+++def mailgun_legacy_sender_lookup_status(delivery: WebhookDelivery) -> int:+ """The answer the outbound route owes a region that still probes it with `sender_lookup=1`.++ Delete this with the provider that reaches it, once both regions run the ingress version.+ """+ # Deferred to keep the email ingestion modules off the facade import path.+ from products.conversations.backend.services import mailgun_events # noqa: PLC0415++ return mailgun_events.mailgun_legacy_sender_lookup_status(delivery)++def sync_google_account_email(integration_id: int, team_id: int) -> None:from products.conversations.backend.services.gmail_sync import ( # noqa: PLC0415 -- avoids the Conversations and Customer Analytics facade cycleGmailSyncError,diff --git a/products/conversations/backend/mailgun.py b/products/conversations/backend/mailgun.pyindex 13ed48b3766f..b9bae5e49300 100644--- a/products/conversations/backend/mailgun.py+++ b/products/conversations/backend/mailgun.py@@ -1,8 +1,5 @@"""Mailgun integration helpers for conversations email channel."""-import hmac-import time-import hashlibfrom typing import Any, TypedDictimport requests@@ -14,11 +11,19 @@ logger = structlog.get_logger(__name__)MAILGUN_API_BASE = "https://api.mailgun.net/v3"-WEBHOOK_TIMESTAMP_MAX_AGE_SECONDS = 300 # 5 minutes-MAILGUN_SEND_TIMEOUT = 30 # seconds+def get_email_webhook_signing_key() -> str | None:+ """The Mailgun account signing key the route endpoints verify with.++ Injected into the ingress provider rather than read there, because the instance setting+ belongs to this product and nothing under `posthog/ingress/` imports a product. The scheme+ calls this on every request, and `get_instance_setting` is cached.+ """+ return get_instance_setting("CONVERSATIONS_EMAIL_WEBHOOK_SIGNING_KEY")++class MailgunDnsRecord(TypedDict, total=False):record_type: strname: str@@ -74,36 +79,6 @@ class MailgunTransientError(MailgunError):"""-def validate_webhook_signature(token: str, timestamp: str, signature: str) -> bool:- """Verify inbound Mailgun webhook authenticity via HMAC-SHA256.-- Also rejects timestamps older than 5 minutes to prevent replay attacks.- """- # Uncomment this to allow debugging in development- # if settings.DEBUG:- # return True-- signing_key = get_instance_setting("CONVERSATIONS_EMAIL_WEBHOOK_SIGNING_KEY")- if not signing_key:- return False-- # Reject stale timestamps- try:- ts = int(timestamp)- except (ValueError, TypeError):- return False- if abs(time.time() - ts) > WEBHOOK_TIMESTAMP_MAX_AGE_SECONDS:- return False-- expected = hmac.new(- key=signing_key.encode("utf-8"),- msg=f"{timestamp}{token}".encode(),- digestmod=hashlib.sha256,- ).hexdigest()-- return hmac.compare_digest(expected, signature)--def _get_api_key() -> str:key = get_instance_setting("CONVERSATIONS_EMAIL_MAILGUN_API_KEY")if not key:diff --git a/products/conversations/backend/services/mailgun_events.py b/products/conversations/backend/services/mailgun_events.pyindex a57f8d7607ff..396fbaea7e5c 100644--- a/products/conversations/backend/services/mailgun_events.py+++ b/products/conversations/backend/services/mailgun_events.py@@ -1,28 +1,42 @@-"""Mailgun email webhook endpoints, and the inbound and outbound handling behind them."""+"""Mailgun route deliveries for the conversations email channels.++Ingress verifies the signature in the form and flattens the delivery before anything here runs,+so no HTTP is left in this module: it answers which region owns a delivery, and it accepts the+deliveries this region owns. The readers keep reading the form under the two names an+`HttpRequest` gave it, through the `MailgunRequest` adapter below, so the parsing is the same+code it has always been.++Attachments are read and stored inside the request. An `UploadedFile` is backed by the request+stream or by a temporary file, so it does not survive the response and cannot be handed to a task.+"""import reimport json-from collections.abc import Iterator+from collections.abc import Iterator, Mappingfrom datetime import UTC, datetime, timedeltafrom email.utils import getaddresses, parseaddr, parsedate_to_datetimefrom typing import Any, cast+from urllib.parse import urlparse+from django.conf import settingsfrom django.core.files.uploadedfile import UploadedFilefrom django.db import IntegrityError, transactionfrom django.db.models import F-from django.http import HttpRequest, HttpResponsefrom django.utils import timezone-from django.views.decorators.csrf import csrf_exempt+import requestsimport structlog+from requests import RequestException+from posthog.ingress.contracts import DeliveryOwnership, WebhookDelivery+from posthog.ingress.dispatch.database import bounded_statement_timeout+from posthog.ingress.mailgun.provider import FILES_KEYfrom posthog.models.comment import Commentfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import User-from posthog.regions import is_primary_region+from posthog.regions import PRIMARY_REGION_DOMAIN, SECONDARY_REGION_DOMAIN-from products.conversations.backend.mailgun import validate_webhook_signaturefrom products.conversations.backend.models import (Channel,EmailChannel,@@ -50,16 +64,11 @@ from products.conversations.backend.services.email_thread_ingestion import (ParsedEmail,ingest_customer_email,)-from products.conversations.backend.services.region_routing import (- proxy_to_secondary_region,- request_secondary_region_status,-)logger = structlog.get_logger(__name__)INBOUND_TOKEN_PATTERN = re.compile(r"^team-([a-f0-9]+)@")OUTBOUND_CAPTURE_LOCAL_PART = "sent"-OUTBOUND_SENDER_LOOKUP_QUERY_PARAM = "sender_lookup"_VIA_SUFFIX_RE = re.compile(r"\s+via\s+.+$", re.IGNORECASE)_BASIC_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")_MESSAGE_ID_RE = re.compile(r"<[^<>\s]+>")@@ -86,6 +95,46 @@ AUTORESPONDER_HEADERS = ("X-Autoreply", "X-Autorespond")# authenticated webhook timestamp (or now) instead.MAX_SENT_AT_CLOCK_SKEW = timedelta(minutes=5)+# The channel lookups run inside the request, before dispatch, so they draw on the delivery's+# wall-clock budget.+_CHANNEL_LOOKUP_TIMEOUT_MS = 800+SENDER_STATUS_PATH = "/api/conversations/v1/email/sender-status"+# The same window the endpoint allowed the cross-region sender lookup before it moved to ingress.+_SENDER_STATUS_TIMEOUT_SECONDS = 10+# The other region holds an active channel for this sender.+SENDER_STATUS_ACTIVE = 204+# It does not.+SENDER_STATUS_ABSENT = 404+# A region that does not serve the sender-status route yet answers Django's own 404 to it, so the+# absent answer needs a body to be told apart from that miss.+SENDER_STATUS_ABSENT_BODY = {"sender_active": False}+++class MailgunSenderProbeError(Exception):+ """The other region could not say whether it also holds an active channel for the sender.++ Raising costs the delivery its receipt, so Mailgun redelivers and the question is asked again.+ Ingesting on an unanswered question is the failure this check exists to prevent.+ """+++class MailgunRequest:+ """One verified route delivery, in the shape the readers below already read it.++ Every reader took an `HttpRequest` and read `request.POST` and `request.FILES` before these+ routes moved onto ingress. The fields are the same fields, so they keep those two names and+ the readers keep their bodies. The attachments arrive under the provider's reserved `_files`+ key, which is also where the provider applies the file cap.++ This exists only so the readers that predate ingress did not have to be rewritten. New code+ reads `delivery.payload` directly, which is the contract ingress actually defines.+ """++ def __init__(self, delivery: WebhookDelivery) -> None:+ payload: Mapping[str, Any] = delivery.payload+ self.POST: dict[str, str] = {name: value for name, value in payload.items() if isinstance(value, str)}+ self.FILES: dict[str, UploadedFile] = payload.get(FILES_KEY) or {}+def _extract_inbound_token(recipient: str) -> str | None:match = INBOUND_TOKEN_PATTERN.match(recipient)@@ -210,7 +259,7 @@ def _is_plausible_email(addr: str) -> bool:def _recover_dmarc_rewritten_sender(- request: HttpRequest,+ request: MailgunRequest,config: EmailChannel,sender_email: str,sender_name: str,@@ -275,7 +324,7 @@ def _recover_dmarc_rewritten_sender(return sender_email, sender_name-def _dkim_aligned_with_sender(request: HttpRequest, sender_domain: str) -> bool:+def _dkim_aligned_with_sender(request: MailgunRequest, sender_domain: str) -> bool:if not _mailgun_authentication_passed(request, "X-Mailgun-Dkim-Check-Result"):return False@@ -287,7 +336,7 @@ def _dkim_aligned_with_sender(request: HttpRequest, sender_domain: str) -> bool:return bool(signing_domains) and all(domain == sender_domain for domain in signing_domains)-def _sender_authenticated(request: HttpRequest, sender_email: str) -> bool:+def _sender_authenticated(request: MailgunRequest, sender_email: str) -> bool:"""Verify the From header domain before trusting it for identity.Mailgun SPF checks can fail for legitimate senders, so aligned DKIM is accepted as a fallback.@@ -304,11 +353,18 @@ def _sender_authenticated(request: HttpRequest, sender_email: str) -> bool:return spf_passed or _dkim_aligned_with_sender(request, from_domain)-def _outbound_sender_authenticated(request: HttpRequest, sender_email: str) -> bool:+def _outbound_sender_authenticated(request: MailgunRequest, sender_email: str) -> bool:_, envelope_sender = parseaddr(request.POST.get("sender", ""))return envelope_sender.strip().lower() == sender_email.lower() and _sender_authenticated(request, sender_email)+def _outbound_sender_email(request: MailgunRequest) -> str:+ _, sender_email = parseaddr(request.POST.get("from", ""))+ if not sender_email:+ sender_email = request.POST.get("sender", "")+ return sender_email.strip().lower()[:400]++def _parse_message_ids(value: str) -> tuple[str, ...]:message_ids = _MESSAGE_ID_RE.findall(value)if not message_ids:@@ -316,7 +372,7 @@ def _parse_message_ids(value: str) -> tuple[str, ...]:return tuple(dict.fromkeys(message_id.strip()[:998] for message_id in message_ids if message_id.strip()))-def _iter_message_header_values(request: HttpRequest, header_name: str) -> Iterator[str]:+def _iter_message_header_values(request: MailgunRequest, header_name: str) -> Iterator[str]:direct_value = request.POST.get(header_name, "")if direct_value:yield direct_value@@ -341,11 +397,11 @@ def _iter_message_header_values(request: HttpRequest, header_name: str) -> Iterayield header[1]-def _message_header_values(request: HttpRequest, header_name: str) -> tuple[str, ...]:+def _message_header_values(request: MailgunRequest, header_name: str) -> tuple[str, ...]:return tuple(dict.fromkeys(_iter_message_header_values(request, header_name)))-def _forwarding_challenge_tokens(request: HttpRequest) -> tuple[str, ...]:+def _forwarding_challenge_tokens(request: MailgunRequest) -> tuple[str, ...]:tokens: list[str] = []seen: set[str] = set()@@ -367,14 +423,14 @@ def _forwarding_challenge_tokens(request: HttpRequest) -> tuple[str, ...]:return tuple(tokens)-def _mailgun_authentication_passed(request: HttpRequest, header_name: str) -> bool:+def _mailgun_authentication_passed(request: MailgunRequest, header_name: str) -> bool:results = tuple(dict.fromkeys(value.strip().lower() for value in _message_header_values(request, header_name) if value.strip()))return results == ("pass",)-def _dkim_signing_domains(request: HttpRequest) -> tuple[str, ...]:+def _dkim_signing_domains(request: MailgunRequest) -> tuple[str, ...]:domains: list[str] = []for signature in _message_header_values(request, "DKIM-Signature"):tags: dict[str, str] = {}@@ -390,7 +446,7 @@ def _dkim_signing_domains(request: HttpRequest) -> tuple[str, ...]:return tuple(dict.fromkeys(domains))-def _is_auto_generated(request: HttpRequest) -> bool:+def _is_auto_generated(request: MailgunRequest) -> 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=...".@@ -418,7 +474,7 @@ def _parse_addresses(value: str) -> tuple[EmailAddress, ...]:return tuple(addresses)-def _parse_sent_at(request: HttpRequest) -> datetime:+def _parse_sent_at(request: MailgunRequest) -> datetime:now = timezone.now()date_header = request.POST.get("Date", "") or request.POST.get("date", "")if date_header:@@ -441,7 +497,7 @@ def _parse_sent_at(request: HttpRequest) -> datetime:return now-def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedEmail | None:+def _parse_inbound_email(request: MailgunRequest, config: EmailChannel) -> ParsedEmail | None:message_ids = _parse_message_ids(request.POST.get("Message-Id", ""))if not message_ids:return None@@ -551,16 +607,16 @@ def _process_support_email(config: EmailChannel,inbound_token: str,email: ParsedEmail,-) -> HttpResponse:+) -> None:team = config.teamsettings_dict = team.conversations_settings or {}if not settings_dict.get("email_enabled"):logger.info("email_inbound_disabled", team_id=team.id)- return HttpResponse(status=200)+ returnif EmailMessageMapping.objects.filter(message_id=email.message_id, team=team).exists():logger.info("email_inbound_duplicate", message_id=email.message_id)- return HttpResponse(status=200)+ returnexisting_ticket = _find_thread_ticket(team.id, email.in_reply_to, email.references)sender_name = email.sender.name@@ -676,7 +732,7 @@ def _process_support_email()except IntegrityError:logger.info("email_inbound_duplicate_race", message_id=email.message_id)- return HttpResponse(status=200)+ returnlogger.info("email_inbound_processed",@@ -684,7 +740,6 @@ def _process_support_email(ticket_id=str(ticket.id),is_reply=existing_ticket is not None,)- return HttpResponse(status=200)def _is_outbound_capture_recipient(recipient: str) -> bool:@@ -715,82 +770,218 @@ def _has_external_recipient(*, config: EmailChannel, email: ParsedEmail) -> boolreturn bool(recipient_emails - internal_emails)-@csrf_exempt-def email_outbound_handler(request: HttpRequest) -> HttpResponse:- if request.method != "POST":- return HttpResponse(status=405)+def _channel_for_inbound_token(inbound_token: str) -> EmailChannel | None:+ """The channel the inbound address belongs to, or None when no channel here holds it.++ A cancelled statement raises, because a lookup that never finished is not an answer. Callers+ let it out rather than guessing past it.+ """+ with bounded_statement_timeout(_CHANNEL_LOOKUP_TIMEOUT_MS, models=[EmailChannel]):+ return EmailChannel.objects.select_related("team", "owner").filter(inbound_token=inbound_token).first()+++def _channel_for_outbound_sender(sender_email: str) -> EmailChannel | None:+ """The active customer-communication channel that sends as this address, or None.++ Only an active channel counts. A channel still waiting for its forwarding confirmation is not+ sending mail yet, so a capture claiming to come from it belongs to whichever region does hold+ an active one.+ """+ with bounded_statement_timeout(_CHANNEL_LOOKUP_TIMEOUT_MS, models=[EmailChannel]):+ return (+ EmailChannel.objects.select_related("team", "owner")+ .filter(+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ connection_status=EmailChannelConnectionStatus.ACTIVE,+ from_email__iexact=sender_email,+ )+ .first()+ )+++def mailgun_sender_is_active_here(sender_email: str) -> bool:+ """Whether this region holds an active customer-communication channel for this sender.++ The other region asks this before it ingests a captured outbound message. It is a lookup and+ nothing else: the asking region decides what to do with the answer.+ """+ return bool(sender_email) and _channel_for_outbound_sender(sender_email) is not None+++def _other_region_sender_status_url() -> str | None:+ """The other region's sender-status URL, or None when this deployment is the other region.++ `posthog.regions.is_primary_region` answers the same question from a request host, and nothing+ here sees a request any more. `SITE_URL` is this deployment's own address, which is how+ `posthog.regions` derives the primary domain in development, so comparing the two says which+ region this is without a second source for it. Only the primary asks, because the secondary+ would otherwise ask itself and find its own channel.+ """+ if settings.DEBUG:+ # A development server is both region domains at once, so it would probe itself over a+ # scheme it does not serve and fail every local outbound capture. There is no second+ # region to be ambiguous with there.+ return None+ if urlparse(settings.SITE_URL).netloc != PRIMARY_REGION_DOMAIN:+ return None+ return f"https://{SECONDARY_REGION_DOMAIN}{SENDER_STATUS_PATH}"+++def _answered_that_the_sender_is_absent(response: requests.Response) -> bool:+ """Whether a 404 came from the sender-status route, and not from a region that lacks it.++ A region running the previous version has no such route, so Django answers its own 404 page.+ The status alone cannot tell the two apart, and an unanswered question has to read as unknown+ rather than as absent.+ """+ try:+ return response.json() == SENDER_STATUS_ABSENT_BODY+ except ValueError:+ return False+++def _sender_is_active_in_other_region(request: MailgunRequest, sender_email: str) -> bool:+ """Ask the other region whether it also holds an active channel for this sender.++ Channel uniqueness is per region, so a sender active in both would otherwise attach one team's+ private outbound mail to the other team's thread. The probe replays the delivery's own Mailgun+ signature triple, which is the proof the endpoint checks, exactly as the old `sender_lookup`+ mode on the webhook path did.+ """+ target_url = _other_region_sender_status_url()+ if target_url is None:+ return False++ try:+ response = requests.post(+ target_url,+ data={+ "timestamp": request.POST.get("timestamp", ""),+ "token": request.POST.get("token", ""),+ "signature": request.POST.get("signature", ""),+ "sender": sender_email,+ },+ timeout=_SENDER_STATUS_TIMEOUT_SECONDS,+ )+ except RequestException as error:+ raise MailgunSenderProbeError(f"sender status request failed: {error}") from error++ if response.status_code == SENDER_STATUS_ACTIVE:+ return True+ if response.status_code == SENDER_STATUS_ABSENT and _answered_that_the_sender_is_absent(response):+ return False+ raise MailgunSenderProbeError(f"sender status answered {response.status_code}")- token = request.POST.get("token", "")- timestamp = request.POST.get("timestamp", "")- signature = request.POST.get("signature", "")- if not validate_webhook_signature(token, timestamp, signature):- logger.warning("email_outbound_invalid_signature")- return HttpResponse("Invalid signature", status=403)+def _ownership_of_channel(channel: EmailChannel | None) -> DeliveryOwnership:+ """A channel this region does not hold is `ELSEWHERE` rather than undecided.++ The other region is the only one that can tell a channel it holds from one nobody holds, so+ the delivery has to reach it. This takes an answered lookup: a lookup that never finished has+ not shown that no channel here holds the delivery either.+ """+ return DeliveryOwnership.LOCAL if channel is not None else DeliveryOwnership.ELSEWHERE+++def mailgun_inbound_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Which region holds the channel this inbound address belongs to.++ A lookup that raised, the statement timeout included, propagates rather than answering+ `ELSEWHERE`. Ingress turns that into Mailgun's retry status, so the message is asked for again+ instead of being forwarded to a region that may not hold the channel either.+ """+ request = MailgunRequest(delivery)+ inbound_token = _extract_inbound_token(request.POST.get("recipient", ""))+ if not inbound_token:+ # Nothing in the delivery names a channel, so no region can claim it.+ return DeliveryOwnership.UNDECIDED++ return _ownership_of_channel(_channel_for_inbound_token(inbound_token))+++def mailgun_outbound_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Which region holds the channel this captured message was sent from.++ An unauthenticated sender is undecided rather than elsewhere: the From header is the only+ thing naming a channel, and an unauthenticated one must not make this region replay the+ delivery to the other one.+ """+ request = MailgunRequest(delivery)+ if not _is_outbound_capture_recipient(request.POST.get("recipient", "")):+ return DeliveryOwnership.UNDECIDED++ sender_email = _outbound_sender_email(request)+ if not sender_email or not _outbound_sender_authenticated(request, sender_email):+ return DeliveryOwnership.UNDECIDED++ # A raised lookup costs the receipt here for one more reason than on the inbound route: the+ # same sender can be active in both regions, so forwarding on an unfinished lookup hands the+ # capture to a region that ingests it at once, because only the primary runs the ambiguity+ # probe.+ return _ownership_of_channel(_channel_for_outbound_sender(sender_email))+++def mailgun_capture_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """The catch-all route serves both directions, so the recipient picks the ownership question."""+ if _is_outbound_capture_recipient(MailgunRequest(delivery).POST.get("recipient", "")):+ return mailgun_outbound_delivery_ownership(delivery)+ return mailgun_inbound_delivery_ownership(delivery)+++def mailgun_legacy_sender_lookup_status(delivery: WebhookDelivery) -> int:+ """The status the outbound route answered a `sender_lookup=1` probe with, before ingress.++ The ownership answer is the same question in the shape ingress asks it, so it decides this one+ too and the two cannot drift. Only the recipient differs: the old route answered 400 for a+ recipient that is not the capture address, where ownership calls that undecided. Delete this+ together with the provider that reaches it, once both regions run the ingress version.+ """+ if not _is_outbound_capture_recipient(MailgunRequest(delivery).POST.get("recipient", "")):+ return 400+ ownership = mailgun_outbound_delivery_ownership(delivery)+ if ownership is DeliveryOwnership.UNDECIDED:+ return 200+ return SENDER_STATUS_ACTIVE if ownership is DeliveryOwnership.LOCAL else SENDER_STATUS_ABSENT+++def accept_mailgun_outbound_message(delivery: WebhookDelivery) -> None:+ """Record mail a customer's own agent sent, captured by the outbound route."""+ request = MailgunRequest(delivery)recipient = request.POST.get("recipient", "")if not _is_outbound_capture_recipient(recipient):logger.warning("email_outbound_invalid_recipient", recipient=recipient)- return HttpResponse("Invalid recipient", status=400)+ return- _, sender_email = parseaddr(request.POST.get("from", ""))- if not sender_email:- sender_email = request.POST.get("sender", "")- sender_email = sender_email.strip().lower()[:400]+ sender_email = _outbound_sender_email(request)if not sender_email or not _outbound_sender_authenticated(request, sender_email):logger.warning("email_outbound_unauthenticated_sender", sender_email=sender_email)- return HttpResponse(status=200)-- config = (- EmailChannel.objects.select_related("team", "owner")- .filter(- kind=EmailChannelKind.CUSTOMER_COMMUNICATION,- connection_status=EmailChannelConnectionStatus.ACTIVE,- from_email__iexact=sender_email,- )- .first()- )- lookup_only = request.GET.get(OUTBOUND_SENDER_LOOKUP_QUERY_PARAM) == "1"+ return++ # Unguarded on purpose: a lookup that raises costs the delivery its receipt, so the dispatcher+ # releases the dedup mark and Mailgun's redelivery reaches this consumer again.+ config = _channel_for_outbound_sender(sender_email)if config is None:- if lookup_only:- return HttpResponse(status=404)- if is_primary_region(request):- success = proxy_to_secondary_region(request, log_prefix="email_outbound", timeout=10)- return HttpResponse(status=200 if success else 502)- logger.info("email_outbound_unknown_sender", sender_email=sender_email)- return HttpResponse(status=200)-- if lookup_only:- return HttpResponse(status=204)-- if is_primary_region(request):- secondary_status = request_secondary_region_status(- request,- log_prefix="email_outbound_sender_lookup",- timeout=10,- query_params={OUTBOUND_SENDER_LOOKUP_QUERY_PARAM: "1"},- accepted_statuses=frozenset({404}),+ # Quiet on purpose: ingress reports a delivery no region here owns, off the ownership+ # answer this module gave it before dispatch.+ return++ if _sender_is_active_in_other_region(request, sender_email):+ logger.error(+ "email_outbound_sender_region_ambiguous",+ sender_email=sender_email,+ team_id=config.team_id,+ config_id=str(config.id),)- if secondary_status is None or secondary_status >= 500:- return HttpResponse(status=502)- if secondary_status == 204:- logger.error(- "email_outbound_sender_region_ambiguous",- sender_email=sender_email,- team_id=config.team_id,- config_id=str(config.id),- )- return HttpResponse(status=200)- if secondary_status != 404:- return HttpResponse(status=502)+ returnemail = _parse_inbound_email(request, config)if email is None:logger.warning("email_outbound_no_message_id", team_id=config.team_id)- return HttpResponse(status=200)+ returnif not _has_external_recipient(config=config, email=email):logger.info("email_outbound_internal_only", team_id=config.team_id, config_id=str(config.id))- return HttpResponse(status=200)+ returnresult = ingest_customer_email(team_id=config.team_id,@@ -806,40 +997,27 @@ def email_outbound_handler(request: HttpRequest) -> HttpResponse:message_id=str(result.message_id),created=result.created,)- return HttpResponse(status=200)--@csrf_exempt-def email_inbound_handler(request: HttpRequest) -> HttpResponse:- if request.method != "POST":- return HttpResponse(status=405)-- token = request.POST.get("token", "")- timestamp = request.POST.get("timestamp", "")- signature = request.POST.get("signature", "")- if not validate_webhook_signature(token, timestamp, signature):- logger.warning("email_inbound_invalid_signature")- return HttpResponse("Invalid signature", status=403)+def accept_mailgun_inbound_message(delivery: WebhookDelivery) -> None:+ """Turn mail sent to a PostHog inbox address into a ticket or a customer email thread."""+ request = MailgunRequest(delivery)recipient = request.POST.get("recipient", "")inbound_token = _extract_inbound_token(recipient)if not inbound_token:logger.warning("email_inbound_no_token", recipient=recipient)- return HttpResponse("Invalid recipient", status=400)+ return- try:- config = EmailChannel.objects.select_related("team", "owner").get(inbound_token=inbound_token)- except EmailChannel.DoesNotExist:- if is_primary_region(request):- success = proxy_to_secondary_region(request, log_prefix="email_inbound", timeout=10)- return HttpResponse(status=200 if success else 502)- logger.warning("email_inbound_unknown_token", inbound_token=inbound_token)- return HttpResponse("Unknown recipient", status=404)+ # Unguarded on purpose, for the same reason as the outbound lookup above.+ config = _channel_for_inbound_token(inbound_token)+ if config is None:+ # Quiet on purpose: ingress reports a delivery no region here owns.+ returnemail = _parse_inbound_email(request, config)if email is None:logger.warning("email_inbound_no_message_id", team_id=config.team_id)- return HttpResponse(status=200)+ returnif email.auto_generated and _is_self_addressed(config=config, inbound_token=inbound_token, sender_email=email.sender.email@@ -854,7 +1032,7 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:config_id=str(config.id),message_id=email.message_id,)- return HttpResponse(status=200)+ returnif config.kind == EmailChannelKind.CUSTOMER_COMMUNICATION:challenge_result = process_forwarding_challenges(@@ -870,7 +1048,7 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:config_id=str(config.id),result=challenge_result,)- return HttpResponse(status=200)+ returnif config.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION:captured = capture_google_forwarding_confirmation(@@ -884,9 +1062,9 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:config_id=str(config.id),captured=captured,)- return HttpResponse(status=200)+ returnif config.connection_status != EmailChannelConnectionStatus.ACTIVE:- return HttpResponse(status=200)+ returntry:result = ingest_customer_email(@@ -897,14 +1075,14 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:)except ValueError as error:# A misconfigured channel (e.g. a dangling owner) can't be fixed by redelivery, so log- # and ack rather than 500 into a Mailgun retry loop.+ # and ack rather than raise into a Mailgun retry loop.logger.warning("customer_email_channel_misconfigured",team_id=config.team_id,config_id=str(config.id),error=str(error),)- return HttpResponse(status=200)+ returnlogger.info("customer_email_inbound_processed",team_id=config.team_id,@@ -913,13 +1091,14 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:message_id=str(result.message_id),created=result.created,)- return HttpResponse(status=200)+ return- return _process_support_email(config=config, inbound_token=inbound_token, email=email)+ _process_support_email(config=config, inbound_token=inbound_token, email=email)-@csrf_exempt-def email_capture_handler(request: HttpRequest) -> HttpResponse:- if _is_outbound_capture_recipient(request.POST.get("recipient", "")):- return email_outbound_handler(request)- return email_inbound_handler(request)+def accept_mailgun_captured_message(delivery: WebhookDelivery) -> None:+ """The catch-all route serves both directions, so the recipient picks the handler."""+ if _is_outbound_capture_recipient(MailgunRequest(delivery).POST.get("recipient", "")):+ accept_mailgun_outbound_message(delivery)+ return+ accept_mailgun_inbound_message(delivery)diff --git a/products/conversations/backend/services/region_routing.py b/products/conversations/backend/services/region_routing.pyindex b1d7c93f59f1..43cc5f885797 100644--- a/products/conversations/backend/services/region_routing.py+++ b/products/conversations/backend/services/region_routing.py@@ -3,9 +3,8 @@If the primary region doesn't own the resource, it proxies therequest to the secondary region (US).-The endpoints on `posthog/ingress/` forward through that package instead. This proxy stays for-the ones that have not moved: they take multipart bodies, which the raw-bytes replay there-cannot reconstruct.+The endpoints on `posthog/ingress/` forward through that package instead, off a consumer's+`ownership` answer. This proxy stays only for the endpoints that have not moved yet."""from urllib.parse import urlparse, urlunparse@@ -49,14 +48,7 @@ def _build_proxy_kwargs(request: HttpRequest, headers: dict[str, str]) -> dict:return {"data": data, "files": files, "headers": cleaned_headers}-def request_secondary_region_status(- request: HttpRequest,- *,- log_prefix: str,- timeout: int = 3,- query_params: dict[str, str] | None = None,- accepted_statuses: frozenset[int] = frozenset(),-) -> int | None:+def request_secondary_region_status(request: HttpRequest, *, log_prefix: str, timeout: int = 3) -> int | None:parsed_url = urlparse(request.build_absolute_uri())target_url = urlunparse(parsed_url._replace(netloc=SECONDARY_REGION_DOMAIN))headers = {key: value for key, value in request.headers.items() if key.lower() != "host"}@@ -66,11 +58,11 @@ def request_secondary_region_status(response = requests.request(method=request.method or "POST",url=target_url,- params=query_params if query_params is not None else dict(request.GET.lists()) if request.GET else None,+ params=dict(request.GET.lists()) if request.GET else None,timeout=timeout,**proxy_kwargs,)- if response.ok or response.status_code in accepted_statuses:+ if response.ok:logger.info(f"{log_prefix}_proxy_to_secondary_region",target_url=target_url,diff --git a/products/conversations/backend/webhook_consumers.py b/products/conversations/backend/webhook_consumers.pyindex c585c2cf7f67..b2ee8a282177 100644--- a/products/conversations/backend/webhook_consumers.py+++ b/products/conversations/backend/webhook_consumers.py@@ -1,4 +1,4 @@-"""Conversations' consumers on the customer-facing GitHub App and the SupportHog Slack and Teams bots.+"""Conversations' consumers on the customer-facing GitHub App, the SupportHog Slack and Teams bots and the Mailgun email routes.The registry imports this module on the first delivery, so it stays cheap: every callable defersits own product import.@@ -45,6 +45,42 @@ def _teams_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:return teams_delivery_ownership(delivery)+def _run_email_inbound(delivery: WebhookDelivery) -> None:+ from products.conversations.backend.facade.api import accept_mailgun_inbound_message # noqa: PLC0415++ accept_mailgun_inbound_message(delivery)+++def _email_inbound_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ from products.conversations.backend.facade.api import mailgun_inbound_delivery_ownership # noqa: PLC0415++ return mailgun_inbound_delivery_ownership(delivery)+++def _run_email_outbound(delivery: WebhookDelivery) -> None:+ from products.conversations.backend.facade.api import accept_mailgun_outbound_message # noqa: PLC0415++ accept_mailgun_outbound_message(delivery)+++def _email_outbound_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ from products.conversations.backend.facade.api import mailgun_outbound_delivery_ownership # noqa: PLC0415++ return mailgun_outbound_delivery_ownership(delivery)+++def _run_email_capture(delivery: WebhookDelivery) -> None:+ from products.conversations.backend.facade.api import accept_mailgun_captured_message # noqa: PLC0415++ accept_mailgun_captured_message(delivery)+++def _email_capture_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ from products.conversations.backend.facade.api import mailgun_capture_delivery_ownership # noqa: PLC0415++ return mailgun_capture_delivery_ownership(delivery)++WEBHOOK_CONSUMERS = (WebhookConsumer(name="conversations",@@ -81,4 +117,28 @@ WEBHOOK_CONSUMERS = (handler=_run_teams_events,ownership=_teams_ownership,),+ WebhookConsumer(+ name="conversations_email_inbound",+ provider="mailgun",+ app="inbound",+ event_types=frozenset({"message_received"}),+ handler=_run_email_inbound,+ ownership=_email_inbound_ownership,+ ),+ WebhookConsumer(+ name="conversations_email_outbound",+ provider="mailgun",+ app="outbound",+ event_types=frozenset({"message_sent"}),+ handler=_run_email_outbound,+ ownership=_email_outbound_ownership,+ ),+ WebhookConsumer(+ name="conversations_email_capture",+ provider="mailgun",+ app="capture",+ event_types=frozenset({"message_received"}),+ handler=_run_email_capture,+ ownership=_email_capture_ownership,+ ),)