Skip to content

: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.

feat(ingress): add a Mailgun incarnation for form-signed webhooks (#101489)

Julian Bezc80d2026314f
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index be45d6143075..3807d9c86dbf 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -50,6 +50,8 @@ An HMAC over raw bytes proves only the signature, so its `facts` are empty and `
| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `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/api/email_events.py` |
+| `mailgun` | `/api/conversations/v1/email/outbound` | `outbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/api/email_events.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` |
@@ -176,6 +178,11 @@ The ownership lookup runs inside the request, before dispatch, and inside the sa
A lookup that reads the database must be bounded with `bounded_statement_timeout(ms, models=...)`.
A lookup that raises is logged, captured, counted as `failed` and treated as `UNDECIDED`, so one consumer cannot cost the delivery the receipt it earned by signing.
+What crosses is the raw signed body, except for a provider that signs the form rather than the body.
+Reading that form consumes the request stream and leaves no raw bytes, so the forward rebuilds the fields and the files and drops the original `Content-Type`, which names the boundary of a body that is gone.
+
+The forward runs under the provider's `forward_timeout_seconds`, which defaults to 3 and which a provider whose deliveries carry uploaded files raises, because the forward rebuilds and re-sends every part.
+
A failed forward keeps the receipt by default.
A provider that redelivers on a non-2xx (Slack does, GitHub does not) sets `retry_status` on its incarnation, and the view answers that status with outcome `forward_failed` instead — so the provider sends the delivery again rather than losing it.
The same attribute answers a delivery whose consumers did not accept it, under outcome `retry_requested`; see ["Ingress does not let a consumer decide the response"](#non-goals).
@@ -214,6 +221,7 @@ Last, write `<provider>/README.md` with the fixed sections every provider README
Two shapes that already exist and are worth copying rather than re-deriving:
- **Several apps on one provider.** One incarnation can serve several apps, each with its own secret getter, its own subscribed event types, and its own consumer set. Consumers register against the app name. `github/` is the case.
+- **A provider that signs the form rather than the body.** The incarnation overrides both `verify()` and `parse()` to read `request.POST`, assembles the signed input from the form fields, and hands it to `HmacSha256` as if it came from headers. `mailgun/` is the case.
- **The DRF adapter path.** An endpoint that genuinely needs DRF's team scoping keeps its view, and the incarnation contributes a scheme only, declaring no spec, because nothing dispatches there. `customerio/` is the case. The view verifies through `posthog.auth.WebhookSignatureAuthentication`.
That base class computes its digest with `hmac_sha256_signature()` and compares with `signatures_match()` from `verify/schemes.py`, so the adapter path and the dispatched path share one implementation of HMAC-SHA256.
It backs three endpoints rather than Customer.io alone, because the tasks cross-region usage lookup and the AI observability cross-region spend lookup subclass it too, each with its own header names, signed-input format, and secret.
diff --git a/posthog/ingress/dispatch/forward.py b/posthog/ingress/dispatch/forward.py
index 192cca83c29a..c2bcf977caec 100644
--- a/posthog/ingress/dispatch/forward.py
+++ b/posthog/ingress/dispatch/forward.py
@@ -4,11 +4,17 @@ A third party sends every delivery to the primary region, so a delivery for a re
region holds has to be forwarded there. The forward is the raw signed bytes, unchanged: the other
region verifies the same signature over the same body, which is why no consumer can do this --
by the time a consumer sees a delivery, the body is a parsed mapping.
+
+A provider that signs the form rather than the body is the one exception, and it is rebuilt rather
+than replayed. See `_replay_kwargs`.
"""
+from collections.abc import Mapping
+from typing import Any
from urllib.parse import urlparse, urlunparse
from django.http import HttpRequest
+from django.http.request import RawPostDataException
import requests
import structlog
@@ -19,6 +25,39 @@ from posthog.regions import SECONDARY_REGION_DOMAIN
logger = structlog.get_logger(__name__)
+ReplayFile = tuple[str, tuple[str | None, bytes, str | None]]
+
+
+def _replay_kwargs(request: HttpRequest, headers: Mapping[str, str]) -> dict[str, Any]:
+ """What `requests` needs to put this request on the wire again.
+
+ The raw bytes are preferred, because the other region checks the same signature over the same
+ body. A provider that signs the form reads `request.POST` first, and a multipart read consumes
+ the stream, so those bytes are gone. The form is rebuilt from the parsed fields and files
+ instead, which is sound for such a provider: its signature covers named fields, not the body.
+ """
+ try:
+ return {"data": request.body, "headers": dict(headers)}
+ except RawPostDataException:
+ # `requests` mints a fresh multipart boundary for the rebuilt body, so the original
+ # Content-Type, which names the boundary of the body that is gone, must not travel with it.
+ # The rebuilt body also has its own length, and `requests` keeps an explicit Content-Length,
+ # so the original one makes the other region read a short body or wait for bytes that never
+ # come.
+ rebuilt_headers = {
+ key: value for key, value in headers.items() if key.lower() not in {"content-type", "content-length"}
+ }
+ fields = [(key, value) for key, values in request.POST.lists() for value in values]
+ files: list[ReplayFile] = []
+ for field_name in request.FILES:
+ for uploaded in request.FILES.getlist(field_name):
+ uploaded.seek(0)
+ files.append((field_name, (uploaded.name, uploaded.read(), uploaded.content_type)))
+ # With no files `requests` sends the fields urlencoded, and Django fills `request.POST`
+ # from either encoding, so the other region reads the same form either way.
+ return {"data": fields, "files": files, "headers": rebuilt_headers}
+
+
# The other region reads its own identity off the connection it receives, so a host this region
# put on the request would let it read itself as the primary region and forward the delivery on
# again. X-Forwarded-Proto travels with them because SECURE_PROXY_SSL_HEADER resolves the scheme
@@ -39,9 +78,8 @@ def forward_to_secondary_region(request: HttpRequest, *, provider: str, app: str
response = requests.request(
method=request.method or "POST",
url=target_url,
- data=request.body,
- headers=headers,
timeout=timeout,
+ **_replay_kwargs(request, headers),
)
except RequestException as error:
logger.exception(
diff --git a/posthog/ingress/mailgun/README.md b/posthog/ingress/mailgun/README.md
new file mode 100644
index 000000000000..39b8562384ea
--- /dev/null
+++ b/posthog/ingress/mailgun/README.md
@@ -0,0 +1,67 @@
+# Mailgun
+
+Deliveries from Mailgun routes, which forward a mail message to PostHog.
+
+## Headers
+
+None.
+Mailgun signs a route delivery in the form body, not in a header: the fields are `signature`, `timestamp` and `token`.
+The incarnation hands those three to the shared HMAC scheme as if they were headers, because the scheme reads a mapping and does not care where the caller found it.
+
+## Signature scheme
+
+HMAC-SHA256 over `timestamp + token`, hex encoded, with no prefix.
+The signature does not bind the message, because Mailgun signs those two fields and nothing else.
+A captured pair therefore authenticates any body until the replay window closes, which is why the window is not optional: the scheme refuses a timestamp more than 5 minutes old, and one more than 5 minutes in the future.
+
+`verify` reads `request.POST`, never `request.body`.
+A multipart body is consumed by the form parser, which leaves no raw bytes for a later read.
+`parse` then reads the same cached form again, so the second read costs nothing.
+
+## Delivery id and event type
+
+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`.
+
+## Apps and secrets
+
+Two 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.
+
+Both 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.
+
+## Quirks
+
+Mailgun never posts JSON to a route.
+The payload is the form flattened to a mapping of field name to string, plus one reserved key, `_files`, which holds the uploaded attachments by field name.
+
+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 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.
+An unsigned caller therefore buys a full multipart parse for its 403, which is a reason to set `throttle_class` on the provider when an endpoint mounts it.
+
+A forwarded delivery crosses as a rebuilt form rather than as the raw bytes, because the form read leaves none.
+[Regional forwarding](../README.md#regional-forwarding) carries the rule, and a region-split consumer declares `ownership` as it would on any other provider.
+
+Mailgun's event webhooks (delivered, failed, opened) are a different payload shape, with the event name in the form.
+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.
+See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/ingress/mailgun/__init__.py b/posthog/ingress/mailgun/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/mailgun/provider.py b/posthog/ingress/mailgun/provider.py
new file mode 100644
index 000000000000..55b70d0acce3
--- /dev/null
+++ b/posthog/ingress/mailgun/provider.py
@@ -0,0 +1,125 @@
+"""Mailgun route deliveries: a mail message posted as a form, and signed inside that form.
+
+Mailgun never posts JSON to a route. It posts an urlencoded or a multipart form, and it puts
+the three signature fields in the same form as the message. So `verify` and `parse` both read
+`request.POST` rather than `request.body`: a multipart body is consumed by the form parser, and
+the raw bytes are no longer available afterwards.
+"""
+
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any, cast
+
+from django.core.files.uploadedfile import UploadedFile
+from django.http import HttpRequest, QueryDict, UnreadablePostError
+from django.http.multipartparser import MultiPartParserError
+from django.utils import timezone
+
+from posthog.ingress.contracts import ProviderSpec, WebhookDelivery
+from posthog.ingress.providers import InvalidPayload, WebhookProvider
+from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme, Verification, VerificationOutcome
+
+# These go to the HMAC scheme as header names, because the scheme reads a mapping and does not
+# care where the caller found it.
+SIGNATURE_FIELD = "signature"
+TIMESTAMP_FIELD = "timestamp"
+TOKEN_FIELD = "token"
+
+# A route carries a message rather than an event, so there is no event field to read and the app
+# decides the event type.
+_APP_EVENT_TYPES: Mapping[str, str] = {
+ "inbound": "message_received",
+ "outbound": "message_sent",
+}
+
+SPECS = tuple(
+ ProviderSpec(provider="mailgun", app=app, event_types=frozenset({event_type}))
+ for app, event_type in _APP_EVENT_TYPES.items()
+)
+
+_FORM_CONTENT_TYPES = frozenset({"application/x-www-form-urlencoded", "multipart/form-data"})
+
+# A consumer must read these inside the request. An UploadedFile is backed by the request stream
+# or a temporary file, so it does not survive the response and cannot be handed to a task.
+FILES_KEY = "_files"
+
+# Bounds what a consumer iterates, not what the request costs: the form parser reads and spools
+# every part before this code runs, and DATA_UPLOAD_MAX_NUMBER_FILES is what bounds that.
+MAX_FILES = 20
+
+
+def _files_in_request(request: HttpRequest) -> dict[str, UploadedFile]:
+ return {name: cast(UploadedFile, request.FILES[name]) for name in list(request.FILES)[:MAX_FILES]}
+
+
+class MailgunProvider(WebhookProvider):
+ provider = "mailgun"
+ # 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.0
+
+ def __init__(self, app: str, *, signing_key_getter: Callable[[], str | None]) -> None:
+ event_type = _APP_EVENT_TYPES.get(app)
+ if event_type is None:
+ raise ValueError(f"Unknown Mailgun app {app!r}, expected one of {sorted(_APP_EVENT_TYPES)}")
+ self.app = app
+ self.event_type = event_type
+ self._scheme = HmacSha256(
+ secret_getter=signing_key_getter,
+ signature_header=SIGNATURE_FIELD,
+ timestamp_header=TIMESTAMP_FIELD,
+ )
+
+ def _form(self, request: HttpRequest) -> QueryDict | None:
+ if request.content_type not in _FORM_CONTENT_TYPES:
+ return None
+ try:
+ return request.POST
+ except (MultiPartParserError, UnreadablePostError):
+ # A truncated or malformed multipart body is the caller's problem, so it must not
+ # become a 500. Django answers RequestDataTooBig and TooManyFieldsSent itself.
+ return None
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def verify(self, request: HttpRequest) -> Verification:
+ form = self._form(request)
+ if form is None:
+ return Verification(outcome=VerificationOutcome.INVALID)
+ timestamp = form.get(TIMESTAMP_FIELD, "")
+ token = form.get(TOKEN_FIELD, "")
+ # Mailgun signs the concatenation of the timestamp and the token, not the body.
+ return self._scheme.verify(
+ body=f"{timestamp}{token}".encode(),
+ headers={SIGNATURE_FIELD: form.get(SIGNATURE_FIELD, ""), TIMESTAMP_FIELD: timestamp},
+ )
+
+ def parse(self, request: HttpRequest) -> Any:
+ form = self._form(request)
+ if form is None:
+ raise InvalidPayload(f"expected a form body, got content type {request.content_type!r}")
+ # Django caches the parsed form, so this second read costs nothing.
+ payload: dict[str, Any] = form.dict()
+ payload[FILES_KEY] = _files_in_request(request)
+ return payload
+
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping):
+ return ()
+ token = payload.get(TOKEN_FIELD)
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ # Mailgun mints a fresh token per delivery, so it keys dedup on its own.
+ delivery_id=str(token) if token else None,
+ event_type=self.event_type,
+ payload=payload,
+ received_at=timezone.now(),
+ context={},
+ ),
+ )
+
+
+def build_mailgun_provider(app: str, *, signing_key_getter: Callable[[], str | None]) -> MailgunProvider:
+ return MailgunProvider(app, signing_key_getter=signing_key_getter)
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index aec76aa9229c..78985ce6cd42 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -25,6 +25,7 @@ _INCARNATION_MODULES = (
"posthog.ingress.github.provider",
"posthog.ingress.slack.provider",
"posthog.ingress.pandadoc.provider",
+ "posthog.ingress.mailgun.provider",
"posthog.ingress.vapi.provider",
"posthog.ingress.sns.provider",
)
@@ -66,6 +67,10 @@ class WebhookProvider(ABC):
# An incarnation that answers 404 to withhold the endpoint's existence sets this False, so the
# body does not name the reason the status code was chosen to hide.
explains_rejections: bool = True
+ # How long the forward to the owning region may take. The default suits a small JSON body; a
+ # provider whose deliveries carry uploaded files needs longer, because the forward rebuilds
+ # and re-sends every part.
+ forward_timeout_seconds: float = 3.0
@abstractmethod
def scheme(self) -> SignatureScheme:
diff --git a/posthog/ingress/test/test_mailgun.py b/posthog/ingress/test/test_mailgun.py
new file mode 100644
index 000000000000..99e3c8826b58
--- /dev/null
+++ b/posthog/ingress/test/test_mailgun.py
@@ -0,0 +1,107 @@
+import hmac
+import time
+from urllib.parse import urlencode
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.test import RequestFactory, SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.ingress.mailgun.provider import FILES_KEY, MAX_FILES, MailgunProvider, build_mailgun_provider
+from posthog.ingress.providers import InvalidPayload
+from posthog.ingress.verify.schemes import VerificationOutcome
+
+SIGNING_KEY = "mailgun-signing-key"
+URL = "/api/conversations/v1/email/inbound"
+FORM_CONTENT_TYPE = "application/x-www-form-urlencoded"
+
+
+def _signed_fields(*, age_seconds: int = 0, token: str = "delivery-token") -> dict[str, str]:
+ timestamp = str(int(time.time()) - age_seconds)
+ signature = hmac.digest(SIGNING_KEY.encode(), f"{timestamp}{token}".encode(), "sha256").hex()
+ return {"timestamp": timestamp, "token": token, "signature": signature}
+
+
+def _provider(app: str = "inbound", *, signing_key: str | None = SIGNING_KEY) -> MailgunProvider:
+ return build_mailgun_provider(app, signing_key_getter=lambda: signing_key)
+
+
+class TestMailgunProvider(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("a_fresh_signed_form", 0, {}, SIGNING_KEY, VerificationOutcome.VERIFIED),
+ ("a_wrong_signature", 0, {"signature": "f" * 64}, SIGNING_KEY, VerificationOutcome.INVALID),
+ ("a_token_swapped_after_signing", 0, {"token": "other"}, SIGNING_KEY, VerificationOutcome.INVALID),
+ ("a_stale_timestamp", 600, {}, SIGNING_KEY, VerificationOutcome.INVALID),
+ ("no_signing_key", 0, {}, None, VerificationOutcome.NOT_CONFIGURED),
+ ]
+ )
+ def test_verification_reads_the_signature_out_of_the_form(
+ self,
+ _name: str,
+ age_seconds: int,
+ overrides: dict[str, str],
+ signing_key: str | None,
+ expected: VerificationOutcome,
+ ) -> None:
+ fields = _signed_fields(age_seconds=age_seconds) | overrides
+ request = RequestFactory().post(URL, data=urlencode(fields), content_type=FORM_CONTENT_TYPE)
+
+ self.assertEqual(_provider(signing_key=signing_key).verify(request).outcome, expected)
+
+ def test_a_multipart_delivery_verifies_and_parses_into_the_form_fields_and_its_files(self) -> None:
+ fields = _signed_fields()
+ request = RequestFactory().post(
+ URL,
+ data={
+ **fields,
+ "recipient": "[email protected]",
+ "body-plain": "hello",
+ "attachment-1": SimpleUploadedFile("note.txt", b"attached", content_type="text/plain"),
+ },
+ )
+ provider = _provider()
+
+ self.assertEqual(provider.verify(request).outcome, VerificationOutcome.VERIFIED)
+
+ payload = provider.parse(request)
+ self.assertEqual(payload["recipient"], "[email protected]")
+ self.assertEqual(payload["body-plain"], "hello")
+ self.assertEqual(payload["token"], fields["token"])
+ self.assertEqual(list(payload[FILES_KEY]), ["attachment-1"])
+ self.assertEqual(payload[FILES_KEY]["attachment-1"].read(), b"attached")
+
+ (delivery,) = provider.deliveries(request, payload, {})
+ self.assertEqual(delivery.delivery_id, fields["token"])
+
+ @parameterized.expand([("inbound", "message_received"), ("outbound", "message_sent")])
+ 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)
+
+ (delivery,) = provider.deliveries(request, provider.parse(request), {})
+
+ self.assertEqual((delivery.app, delivery.event_type), (app, event_type))
+
+ def test_a_body_that_is_not_a_form_is_refused_rather_than_read_as_one(self) -> None:
+ request = RequestFactory().post(URL, data='{"token": "delivery-token"}', content_type="application/json")
+ provider = _provider()
+
+ self.assertEqual(provider.verify(request).outcome, VerificationOutcome.INVALID)
+ with self.assertRaises(InvalidPayload):
+ provider.parse(request)
+
+ def test_the_number_of_files_one_delivery_can_carry_is_capped(self) -> None:
+ files = {
+ f"attachment-{index}": SimpleUploadedFile(f"{index}.txt", b"attached", content_type="text/plain")
+ for index in range(MAX_FILES + 5)
+ }
+ request = RequestFactory().post(URL, data={**_signed_fields(), **files})
+
+ payload = _provider().parse(request)
+
+ self.assertEqual(len(payload[FILES_KEY]), MAX_FILES)
+
+ def test_an_unknown_app_is_refused_at_build(self) -> None:
+ with self.assertRaises(ValueError):
+ _provider("events")
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 207b546fe35c..4c13f3835426 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -8,6 +8,7 @@ from urllib.parse import urlencode
from unittest.mock import Mock, patch
from django.core.cache import cache
+from django.core.files.uploadedfile import SimpleUploadedFile
from django.http import HttpRequest
from django.test import RequestFactory, SimpleTestCase, override_settings
@@ -58,6 +59,11 @@ class _RedeliveringGitHubProvider(GitHubProvider):
retry_status = 502
+class _SlowForwardGitHubProvider(GitHubProvider):
+ # Stands in for a provider whose deliveries carry uploaded files, which Mailgun's do.
+ forward_timeout_seconds = 10.0
+
+
class _ClaimsGitHubProvider(GitHubProvider):
# Stands in for a scheme that checks a signed token, which names the sender before the body
# is parsed. The claims land in the delivery's context so the test can read them back.
@@ -461,6 +467,25 @@ class TestRegionalForwarding(_DispatchingViewTestCase):
self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], [outcome])
self.assertEqual(self.handler.call_count, dispatched)
+ @parameterized.expand(
+ [
+ ("the package default", GitHubProvider, 3.0),
+ ("a provider whose deliveries carry files", _SlowForwardGitHubProvider, 10.0),
+ ]
+ )
+ def test_the_forward_runs_under_the_providers_own_timeout(
+ self, _name: str, provider_class: type[GitHubProvider], expected_timeout: float
+ ) -> None:
+ view = self._view(
+ [_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)],
+ provider=provider_class("posthog"),
+ )
+
+ with patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"):
+ view(self._github_request())
+
+ self.assertEqual(self.requests.call_args.kwargs["timeout"], expected_timeout)
+
def test_the_secondary_region_reports_an_unowned_delivery_rather_than_forwarding_it_back(self) -> None:
view = self._view(
[_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)]
@@ -655,3 +680,42 @@ class TestForwardToSecondaryRegion(SimpleTestCase):
self.assertEqual(sent & HOST_IDENTIFYING_HEADERS, set())
self.assertIn("x-forwarded-for", sent)
self.assertIn(SECONDARY_REGION_DOMAIN, kwargs["url"])
+
+ def test_a_multipart_request_read_as_a_form_is_rebuilt_from_its_fields_and_files(self) -> None:
+ multipart = RequestFactory().post(
+ "/webhooks/mailgun/",
+ data={
+ "token": "delivery-token",
+ "recipient": "[email protected]",
+ "attachment-1": SimpleUploadedFile("note.txt", b"attached", content_type="text/plain"),
+ },
+ )
+ # A form provider verifies through request.POST, which leaves no raw body to replay.
+ self.assertEqual(multipart.POST["token"], "delivery-token")
+
+ with patch("posthog.ingress.dispatch.forward.requests.request") as request:
+ request.return_value = Mock(ok=True, status_code=202)
+ forward_to_secondary_region(multipart, provider="mailgun", app="inbound")
+
+ kwargs = request.call_args.kwargs
+ self.assertIn(("token", "delivery-token"), kwargs["data"])
+ self.assertIn(("recipient", "[email protected]"), kwargs["data"])
+ self.assertEqual(kwargs["files"], [("attachment-1", ("note.txt", b"attached", "text/plain"))])
+ forwarded_header_names = {key.lower() for key in kwargs["headers"]}
+ self.assertNotIn("content-type", forwarded_header_names)
+ self.assertNotIn("content-length", forwarded_header_names)
+
+ def test_a_urlencoded_form_read_still_replays_its_raw_bytes(self) -> None:
+ body = b"token=delivery-token&recipient=team-abc%40example.com"
+ urlencoded = RequestFactory().post(
+ "/webhooks/mailgun/", data=body, content_type="application/x-www-form-urlencoded"
+ )
+ self.assertEqual(urlencoded.POST["token"], "delivery-token")
+
+ with patch("posthog.ingress.dispatch.forward.requests.request") as request:
+ request.return_value = Mock(ok=True, status_code=202)
+ forward_to_secondary_region(urlencoded, provider="mailgun", app="inbound")
+
+ kwargs = request.call_args.kwargs
+ self.assertEqual(kwargs["data"], body)
+ self.assertNotIn("files", kwargs)
diff --git a/posthog/ingress/views.py b/posthog/ingress/views.py
index 41469d211304..c05d1e744232 100644
--- a/posthog/ingress/views.py
+++ b/posthog/ingress/views.py
@@ -123,7 +123,12 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Htt
if elsewhere:
if is_primary_region(request):
# Once for the request, not once per delivery: what is replayed is the signed body.
- forwarded = forward_to_secondary_region(request, provider=provider.provider, app=provider.app)
+ forwarded = forward_to_secondary_region(
+ request,
+ provider=provider.provider,
+ app=provider.app,
+ timeout=provider.forward_timeout_seconds,
+ )
if not forwarded and provider.retry_status is not None:
observe_delivery(provider=provider.provider, app=provider.app, outcome="forward_failed")
return HttpResponse(status=provider.retry_status)