:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingress): report an unconfigured secret and an unroutable host (#103799)
Julian Bezae82344d328e
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex d68418bfde01..3ad2a5c8a5a8 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -203,6 +203,7 @@ Every delivery in the request is assessed first, and the request is then forwardOne forward per request rather than per delivery, because the unit being replayed is the HTTP request.Local dispatch runs either way: a consumer that answered `ELSEWHERE` no-ops on its own, and the other consumers on the endpoint are unaffected.Only the receiving region forwards; on the region that receives forwards an `ELSEWHERE` answer is logged as `ingress_delivery_unowned_here`, because a local miss there is that consumer's unresolved routing rather than proof that no region owns the delivery.+A request whose host is neither region skips the forward and is receipted anyway, so the owning region never sees the delivery. That is logged as `ingress_delivery_host_matches_no_region` with the host, because the likely cause is a callback URL registered against a hostname no region names and nothing else reports it. It keys off an `ELSEWHERE` answer, so local development, where both domains resolve to localhost hosts, does not warn on every delivery.The replay carries the signed bytes and the provider's own headers, but never the headers that name the host this region answered on: `Host`, `X-Forwarded-Host`, `X-Forwarded-Port`, `X-Forwarded-Proto` and `Forwarded`.The receiving region reads which region it is off the connection it receives, so a forwarded host would make it forward the delivery on again.@@ -232,7 +233,7 @@ The same attribute answers a delivery whose consumers did not accept it, under oAdd a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `vapi/` for a small one):- `SPECS` — one `ProviderSpec` per app, naming the event types the app is subscribed to. The registry validates consumers against these.-- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. The 500 suits an endpoint whose secret is always set, because an unconfigured one is then an operator fault; an endpoint that a deployment may legitimately never configure, such as Slack and Mailgun on a self-hosted instance, sets `unconfigured_status = 403` instead, or the URL answers a server error to every anonymous probe. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well, and so does one that must not tell an unauthenticated caller whether the secret is merely unset. Three more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, and `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted. See [The lanes one request runs through](#the-lanes-one-request-runs-through).+- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. The 500 suits an endpoint whose secret is always set, because an unconfigured one is then an operator fault; an endpoint that a deployment may legitimately never configure, such as Slack and Mailgun on a self-hosted instance, sets `unconfigured_status = 403` instead, or the URL answers a server error to every anonymous probe. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well, and so does one that must not tell an unauthenticated caller whether the secret is merely unset. Four more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted, and `reports_unconfigured`, which also sends a missing secret to error tracking. That last one is off by default, because an endpoint that answers an unconfigured request like an unknown route lets an unauthenticated prober fill error tracking from the outside; turn it on where the deliveries are lost while the secret is unset and nothing else would notice. See [The lanes one request runs through](#the-lanes-one-request-runs-through).- A `build_<provider>_provider(...)` function returning that provider, which the URLconf hands to `build_webhook_view()`.A builder that takes an `app` name checks it with `require_known_app(provider, app, SPECS)` before anything else, so a typo raises `UnknownApp` at import. Without that check the endpoint builds and serves: consumers register against the declared app names, so nothing matches and every delivery is receipted and dropped, or the app has no secret getter and every delivery answers `NOT_CONFIGURED`.diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.pyindex 8df911cc122a..54fcdbc4c7b5 100644--- a/posthog/ingress/providers.py+++ b/posthog/ingress/providers.py@@ -106,6 +106,12 @@ 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+ # Whether a missing secret also reaches error tracking, on top of the log line every provider+ # writes. Off by default: an endpoint that answers an unconfigured request like an unknown+ # route (SNS) would let an unauthenticated prober fill error tracking from the outside. Turn it+ # on for an endpoint whose deliveries are lost while the secret is unset and where nothing else+ # would notice.+ reports_unconfigured: bool = False# 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.diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.pyindex 0be1db34c556..eae01e729b1f 100644--- a/posthog/ingress/test/test_views.py+++ b/posthog/ingress/test/test_views.py@@ -72,6 +72,12 @@ class _SecondaryRegionGitHubProvider(GitHubProvider):return regions.SECONDARY_REGION_DOMAIN+class _ReportingUnconfiguredGitHubProvider(GitHubProvider):+ # Stands in for an endpoint whose deliveries are lost while the secret is unset, and where+ # nothing but error tracking would notice.+ reports_unconfigured = True++class _SlowForwardGitHubProvider(GitHubProvider):# Stands in for a provider whose deliveries carry uploaded files, which Mailgun's do.forward_timeout_seconds = 10.0@@ -317,6 +323,31 @@ class TestWebhookView(SimpleTestCase):self.assertEqual(response.status_code, 500)self.assertEqual(response.content, b"Webhook not configured")+ @parameterized.expand(+ [+ ("a_provider_that_opts_in", _ReportingUnconfiguredGitHubProvider, 1),+ ("a_provider_that_does_not", GitHubProvider, 0),+ ]+ )+ def test_a_missing_secret_reaches_error_tracking_only_when_the_provider_asks(+ self, _name: str, provider_class: type[GitHubProvider], captures: int+ ) -> None:+ # An endpoint that answers an unconfigured request like an unknown route would otherwise let+ # an unauthenticated prober fill error tracking from the outside.+ body = json.dumps({"action": "opened"}).encode()+ request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})++ with (+ patch("posthog.ingress.github.provider.get_instance_setting", return_value=""),+ patch("posthog.ingress.views.capture_exception") as capture,+ ):+ response = build_webhook_view(provider_class("posthog"))(request)++ self.assertEqual(response.status_code, 500)+ self.assertEqual(capture.call_count, captures)+ if captures:+ self.assertIn("github/posthog", str(capture.call_args.args[0]))+@parameterized.expand([("a_bad_signature", SECRET),@@ -647,6 +678,9 @@ class TestRegionalForwarding(_DispatchingViewTestCase):with (patch("posthog.regions.PRIMARY_REGION_DOMAIN", "eu.posthog.com"),+ # Both domains, so the request host is the region that receives forwards rather than a+ # host neither region names, which is a different branch and a different warning.+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "testserver"),patch("posthog.ingress.views.logger") as logger,):response = view(self._github_request())@@ -656,6 +690,42 @@ class TestRegionalForwarding(_DispatchingViewTestCase):self.handler.assert_called_once()self.assertEqual([call.args[0] for call in logger.warning.call_args_list], ["ingress_delivery_unowned_here"])+ def test_a_host_neither_region_names_is_reported_rather_than_passing_silently(self) -> None:+ # A callback URL registered against a hostname no region names skips the forward and+ # receipts the delivery anyway, so the owning region never sees it and nothing says so.+ view = self._view(+ [_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)]+ )++ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "eu.posthog.com"),+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "us.posthog.com"),+ patch("posthog.ingress.views.logger") as logger,+ ):+ response = view(self._github_request())++ self.assertEqual(response.status_code, 202)+ self.requests.assert_not_called()+ self.handler.assert_called_once()+ warnings = {call.args[0]: call.kwargs for call in logger.warning.call_args_list}+ self.assertEqual(list(warnings), ["ingress_delivery_host_matches_no_region"])+ self.assertEqual(warnings["ingress_delivery_host_matches_no_region"]["host"], "testserver")++ def test_a_delivery_no_consumer_sends_elsewhere_reports_no_region_problem(self) -> None:+ # The warning above keys off an ELSEWHERE answer. Without that, local development, where+ # both region domains resolve to localhost hosts, would warn on every delivery.+ view = self._view([_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.LOCAL)])++ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "eu.posthog.com"),+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "us.posthog.com"),+ patch("posthog.ingress.views.logger") as logger,+ ):+ response = view(self._github_request())++ self.assertEqual(response.status_code, 202)+ logger.warning.assert_not_called()+def test_every_provider_on_the_package_receives_in_the_primary_region(self) -> None:# The forward direction is shared machinery, so a provider that quietly overrides it# redirects signed deliveries for an endpoint whose owners never asked for that.diff --git a/posthog/ingress/views.py b/posthog/ingress/views.pyindex 2b25b2c4d881..a5de9e8f8cee 100644--- a/posthog/ingress/views.py+++ b/posthog/ingress/views.py@@ -10,6 +10,7 @@ import structlogfrom rest_framework.request import Request as DRFRequestfrom rest_framework.throttling import ScopedRateThrottle+from posthog.exceptions_capture import capture_exceptionfrom posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_secondsfrom posthog.ingress.dispatch.forward import forward_to_other_regionfrom posthog.ingress.dispatch.loading import get_dispatcher@@ -92,6 +93,10 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httverification = provider.verify(request)if verification.outcome is VerificationOutcome.NOT_CONFIGURED:logger.error("ingress_webhook_not_configured", provider=provider.provider, app=provider.app)+ if provider.reports_unconfigured:+ capture_exception(+ Exception(f"Inbound webhook {provider.provider}/{provider.app} has no secret configured")+ )observe_delivery(provider=provider.provider, app=provider.app, outcome="not_configured")reason = "Webhook not configured" if provider.explains_rejections else ""return HttpResponse(reason, status=provider.unconfigured_status)@@ -172,7 +177,7 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httif 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)- else:+ elif request.get_host() == other_region_domain(provider.receiving_region_domain()):# This region is the one deliveries are forwarded to, so a local miss here is that# consumer's unresolved routing, not proof that no region owns the delivery.logger.warning(@@ -181,6 +186,17 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httapp=provider.app,consumers=list(elsewhere),)+ else:+ # Neither region answers on this host, so the forward is skipped and the delivery is+ # receipted here whatever the consumer said. The likely cause is a callback URL+ # registered against a hostname no region names, and nothing else reports it.+ logger.warning(+ "ingress_delivery_host_matches_no_region",+ provider=provider.provider,+ app=provider.app,+ host=request.get_host(),+ consumers=list(elsewhere),+ )unaccepted: dict[str, None] = {}for delivery in deliveries: