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.

chore(vercel): verify the Vercel Marketplace webhook through ingress (#104023)

Julian Bez257a07982122
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.md
index 659063e49fe4..e1bd57960f2d 100644
--- a/.agents/skills/adding-inbound-webhooks/SKILL.md
+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md
@@ -84,7 +84,7 @@ Then:
2. Wire the URL with `build_webhook_view()` where the App registration lives. The owner of the third-party App owns the route: a product that registered the App declares `urlpatterns` in its own `products/<product>/backend/routes.py`, for example `opt_slash_path("webhooks/<product>/<provider>", build_webhook_view(build_<provider>_provider()))`. The path must start with `webhooks/<product>/` or `api/<product>/`, or the URL conf fails to load. Only an App several products consume stays in `posthog/urls.py`, which today is the customer-facing GitHub App alone. See [docs/internal/url-routing.md](../../../docs/internal/url-routing.md).
3. Write `posthog/ingress/<provider>/README.md` with the fixed sections, in this order: headers, signature scheme, delivery id and event type, apps and secrets, quirks, consumers. `posthog/ingress/test/test_provider_readme_sections.py` fails on a provider folder without one, and on a README with different or reordered headings.
4. Add the provider's signature header name to the `$HEADER` regex in `.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml`, plus a fixture case in the `.py` beside it. The header names are spelled out rather than matched generically because a generic header pattern makes semgrep time out on a large module, which drops that file from the scan without failing it.
-5. Delete the migrated endpoint's line from `paths.exclude` in the same rule. That list is a ratchet of verifiers that predate ingress, and the migrating PR removes its own entry.
+5. Do not add the endpoint to `paths.exclude` in the same rule. Every verifier that predated ingress is migrated, so the rule has no grandfathered paths left.
6. Preserve the endpoint's externally observable behavior. Existing tests are the contract: move or extend them, do not drop assertions.
### The DRF adapter path
@@ -102,7 +102,7 @@ Each was a real proposal already; ["Non-goals" in the package README](../../../p
## Verify
```sh
-semgrep --config .semgrep/rules/devex/ . # the ratchet entry is really gone
+semgrep --config .semgrep/rules/devex/ . # no hand-rolled verifier is left
semgrep --test .semgrep/ # only if you changed the rule itself
lint-imports # the webhook_consumers contract
hogli product:lint <product> # the AST backstop for that contract
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
index c2a03329d49c..71f4c9b335b3 100644
--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
@@ -111,7 +111,3 @@ rules:
- '**/tests/**'
- 'test_*.py'
- '*_test.py'
- # Ratchet. Each entry is a verifier that predates ingress, and the PR that
- # migrates that endpoint removes its line. The paths are the ones on master,
- # so the rule holds whether or not the migrations land with it.
- - /ee/api/vercel/vercel_webhooks.py
diff --git a/docs/published/handbook/engineering/vercel-integration.md b/docs/published/handbook/engineering/vercel-integration.md
index 26f924825d13..5bfe3090a3d2 100644
--- a/docs/published/handbook/engineering/vercel-integration.md
+++ b/docs/published/handbook/engineering/vercel-integration.md
@@ -509,7 +509,7 @@ For connectable integrations (linked existing accounts), the webhook handler sim
**Key files:**
-- `ee/api/vercel/vercel_webhooks.py` - Webhook handler
+- `ee/api/vercel/webhook_events.py` - Webhook event handling
- `ee/vercel/integration.py` - `VercelIntegration.delete_installation()`
- `billing/api/billing.py` - Uninstall endpoint
- `billing/models/customer.py` - `cancel_billing_provider_subscription()`
@@ -532,19 +532,19 @@ For integration or billing issues that need Vercel's involvement, post in the sh
### PostHog repo (`posthog/`)
-| File | Purpose |
-| -------------------------------------------- | ---------------------------------------------------------------------- |
-| `ee/api/vercel/vercel_installation.py` | Installation CRUD (`PUT /api/vercel/v1/installations/{id}`) |
-| `ee/api/vercel/vercel_connect.py` | Connectable account OAuth flow |
-| `ee/api/vercel/vercel_sso.py` | SSO endpoints (`/login/vercel`) |
-| `ee/api/vercel/vercel_webhooks.py` | Webhook handler (`/webhooks/vercel`) |
-| `ee/api/vercel/vercel_resource.py` | Resource management (Vercel projects) |
-| `ee/api/vercel/vercel_product.py` | Product plans |
-| `ee/vercel/client.py` | `VercelAPIClient` - HTTP client for Vercel APIs |
-| `ee/vercel/integration.py` | `VercelIntegration` class - core logic (upsert, delete, sync flags) |
-| `ee/billing/billing_manager.py` | `BillingManager` - intermediary for all billing service calls |
-| `posthog/models/organization_integration.py` | `OrganizationIntegration` model (org-level, stores Vercel credentials) |
-| `posthog/models/integration/model.py` | `Integration` model (team/project-level resource record) |
+| File | Purpose |
+| -------------------------------------------- | ------------------------------------------------------------------------ |
+| `ee/api/vercel/vercel_installation.py` | Installation CRUD (`PUT /api/vercel/v1/installations/{id}`) |
+| `ee/api/vercel/vercel_connect.py` | Connectable account OAuth flow |
+| `ee/api/vercel/vercel_sso.py` | SSO endpoints (`/login/vercel`) |
+| `ee/api/vercel/webhook_events.py` | Webhook event handling (`/webhooks/vercel`, served by `posthog/ingress`) |
+| `ee/api/vercel/vercel_resource.py` | Resource management (Vercel projects) |
+| `ee/api/vercel/vercel_product.py` | Product plans |
+| `ee/vercel/client.py` | `VercelAPIClient` - HTTP client for Vercel APIs |
+| `ee/vercel/integration.py` | `VercelIntegration` class - core logic (upsert, delete, sync flags) |
+| `ee/billing/billing_manager.py` | `BillingManager` - intermediary for all billing service calls |
+| `posthog/models/organization_integration.py` | `OrganizationIntegration` model (org-level, stores Vercel credentials) |
+| `posthog/models/integration/model.py` | `Integration` model (team/project-level resource record) |
### Billing repo (`billing/`)
diff --git a/ee/api/vercel/test/test_vercel_webhooks.py b/ee/api/vercel/test/test_vercel_webhooks.py
index c4be36f8473c..560cb65f4072 100644
--- a/ee/api/vercel/test/test_vercel_webhooks.py
+++ b/ee/api/vercel/test/test_vercel_webhooks.py
@@ -4,401 +4,254 @@ import hashlib
from unittest.mock import MagicMock, patch
+from django.db import OperationalError
from django.test import override_settings
-from rest_framework import status
+from requests import RequestException
+from posthog.ingress.dispatch.loading import reset_consumer_registry
from posthog.models.organization_integration import OrganizationIntegration
from ee.api.vercel.test.base import VercelTestBase
+SECRET = "test_webhook_secret"
+
+def _forward_response(status_code: int) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 300
+ return response
+
+
+@override_settings(VERCEL_CLIENT_INTEGRATION_SECRET=SECRET)
class TestVercelWebhooks(VercelTestBase):
def setUp(self):
super().setUp()
self.url = "/webhooks/vercel"
- self.secret = "test_webhook_secret"
-
- def _sign_payload(self, payload: dict) -> str:
- body = json.dumps(payload).encode("utf-8")
- return hmac.new(
- self.secret.encode("utf-8"),
- body,
- hashlib.sha1,
- ).hexdigest()
-
- def _post_webhook(self, payload: dict, signature: str | None = None):
- if signature is not None:
- return self.client.post(
- self.url,
- data=json.dumps(payload),
- content_type="application/json",
- headers={"x-vercel-signature": signature},
- )
- return self.client.post(
- self.url,
- data=json.dumps(payload),
- content_type="application/json",
- )
+ reset_consumer_registry()
+ self.addCleanup(reset_consumer_registry)
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_invalid_signature_returns_401(self):
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": self.installation_id, "invoiceId": "mi_123"},
- }
+ self.addCleanup(patch.stopall)
+ # `pytest.ini` sets DEBUG, which makes `posthog/regions.py` rewrite both domains to
+ # localhost hosts where neither branch of the forward is reachable. `testserver` is the
+ # secondary region here, because that is the region Vercel's one webhook URL names.
+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "testserver").start()
+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "eu.posthog.com").start()
- response = self._post_webhook(payload, signature="invalid_signature")
+ self.forward = patch("posthog.ingress.dispatch.forward.requests.request").start()
+ self.forward.return_value = _forward_response(202)
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
- assert response.json()["error"] == "Invalid signature"
+ def _post(self, payload: dict, signature: str | None = "sign"):
+ body = json.dumps(payload).encode("utf-8")
+ if signature == "sign":
+ signature = hmac.new(SECRET.encode("utf-8"), body, hashlib.sha1).hexdigest()
+ headers = {"x-vercel-signature": signature} if signature is not None else {}
+ return self.client.post(self.url, data=body, content_type="application/json", headers=headers, secure=True)
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_missing_signature_returns_401(self):
- payload = {
+ def _billing_payload(self, installation_id: str) -> dict:
+ return {
"type": "marketplace.invoice.paid",
- "payload": {"installationId": self.installation_id, "invoiceId": "mi_123"},
+ "payload": {"installationId": installation_id, "invoiceId": "mi_123"},
}
- response = self._post_webhook(payload, signature=None)
+ def _deauthorization_payload(self, installation_id: str) -> dict:
+ return {"type": "integration-configuration.removed", "payload": {"installationId": installation_id}}
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ def test_an_invalid_signature_is_refused(self):
+ response = self._post(self._billing_payload(self.installation_id), signature="invalid_signature")
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_missing_config_id_returns_400(self):
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"invoiceId": "mi_123"}, # Missing installationId
- }
- signature = self._sign_payload(payload)
+ self.assertEqual(response.status_code, 401)
+ self.forward.assert_not_called()
- response = self._post_webhook(payload, signature=signature)
+ def test_a_missing_signature_is_refused(self):
+ response = self._post(self._billing_payload(self.installation_id), signature=None)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "configurationId" in response.json()["error"] # Error message still says configurationId
+ self.assertEqual(response.status_code, 401)
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_unknown_config_returns_404(self):
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": "icfg_unknown", "invoiceId": "mi_123"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_404_NOT_FOUND
- assert "Unknown configuration" in response.json()["error"]
-
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_non_billing_events_ignored(self):
- for event_type in [
- "deployment.created",
- "marketplace.member.created",
- None,
- ]:
- payload = {
- "type": event_type,
- "payload": {"installationId": self.installation_id},
- }
- signature = self._sign_payload(payload)
+ @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="")
+ @patch("posthog.ingress.views.capture_exception")
+ def test_a_missing_secret_is_refused_and_reported(self, capture):
+ # The 401 is the same one a stranger's bad signature gets, so a dropped secret is
+ # invisible in the status codes while every invoice event is refused.
+ response = self._post(self._billing_payload(self.installation_id))
- response = self._post_webhook(payload, signature=signature)
+ self.assertEqual(response.status_code, 401)
+ self.assertEqual(capture.call_count, 1)
+
+ @patch("ee.api.vercel.webhook_events.BillingManager")
+ def test_a_billing_event_without_an_installation_id_runs_no_billing_call(self, billing_manager):
+ response = self._post({"type": "marketplace.invoice.paid", "payload": {"invoiceId": "mi_123"}})
- assert response.status_code == status.HTTP_200_OK
- assert response.json()["status"] == "ignored"
+ self.assertEqual(response.status_code, 202)
+ billing_manager.assert_not_called()
+ self.forward.assert_not_called()
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
@patch("ee.api.vercel.webhook_events.VercelIntegration")
- def test_deauthorization_native_calls_delete_installation(self, mock_vercel_integration):
- assert OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()
+ def test_a_deauthorization_without_a_configuration_id_deletes_nothing(self, vercel_integration):
+ response = self._post({"type": "integration-configuration.removed", "payload": {"user": {"id": "usr_123"}}})
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"installationId": self.installation_id},
- }
- signature = self._sign_payload(payload)
+ self.assertEqual(response.status_code, 202)
+ vercel_integration.delete_installation.assert_not_called()
+ self.forward.assert_not_called()
- response = self._post_webhook(payload, signature=signature)
+ @patch("ee.api.vercel.webhook_events.VercelIntegration")
+ def test_a_deauthorization_this_region_holds_deletes_the_installation(self, vercel_integration):
+ response = self._post(self._deauthorization_payload(self.installation_id))
- assert response.status_code == status.HTTP_200_OK
- assert response.json()["status"] == "ok"
- mock_vercel_integration.delete_installation.assert_called_once_with(self.installation_id)
+ self.assertEqual(response.status_code, 202)
+ vercel_integration.delete_installation.assert_called_once_with(self.installation_id)
+ self.forward.assert_not_called()
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_deauthorization_connectable_deletes_directly(self):
+ def test_a_connectable_deauthorization_deletes_the_row_directly(self):
self.installation.config["type"] = "connectable"
self.installation.save()
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"installationId": self.installation_id},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
+ response = self._post(self._deauthorization_payload(self.installation_id))
- assert response.status_code == status.HTTP_200_OK
- assert response.json()["status"] == "ok"
- assert not OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()
+ self.assertEqual(response.status_code, 202)
+ self.assertFalse(OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists())
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_deauthorization_with_configuration_id_payload(self):
+ def test_a_deauthorization_can_name_the_installation_under_configuration_id(self):
self.installation.config["type"] = "connectable"
self.installation.save()
- payload = {
- "type": "integration-configuration.removed",
- "payload": {
- "configuration": {"id": self.installation_id},
- },
- }
- signature = self._sign_payload(payload)
+ response = self._post(
+ {
+ "type": "integration-configuration.removed",
+ "payload": {"configuration": {"id": self.installation_id}},
+ }
+ )
- response = self._post_webhook(payload, signature=signature)
+ self.assertEqual(response.status_code, 202)
+ self.assertFalse(OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists())
- assert response.status_code == status.HTTP_200_OK
- assert not OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()
+ @patch("ee.api.vercel.webhook_events.BillingManager")
+ def test_an_event_type_this_integration_does_not_act_on_runs_nothing(self, billing_manager):
+ for event_type in ["deployment.created", "marketplace.member.created", None]:
+ with self.subTest(event_type=event_type):
+ response = self._post({"type": event_type, "payload": {"installationId": self.installation_id}})
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_deauthorization_with_empty_configuration_returns_400(self):
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"configuration": {}},
- }
- signature = self._sign_payload(payload)
+ self.assertEqual(response.status_code, 202)
- response = self._post_webhook(payload, signature=signature)
+ billing_manager.assert_not_called()
+ self.forward.assert_not_called()
- assert response.status_code == status.HTTP_400_BAD_REQUEST
+ @patch("ee.api.vercel.webhook_events.BillingManager")
+ @patch("ee.api.vercel.webhook_events.License")
+ def test_a_billing_event_this_region_holds_reaches_the_billing_service(self, license_model, billing_manager_class):
+ license_model.objects.first.return_value = MagicMock()
+ billing_manager = MagicMock()
+ billing_manager_class.return_value = billing_manager
+ payload = self._billing_payload(self.installation_id)
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_deauthorization_with_no_config_fields_returns_400(self):
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"user": {"id": "usr_123"}},
- }
- signature = self._sign_payload(payload)
+ response = self._post(payload)
+
+ self.assertEqual(response.status_code, 202)
+ billing_manager.handle_billing_provider_webhook.assert_called_once_with(
+ event_type="marketplace.invoice.paid",
+ event_data=payload["payload"],
+ organization=self.organization,
+ billing_provider="vercel",
+ )
+ self.forward.assert_not_called()
- response = self._post_webhook(payload, signature=signature)
+ @patch("ee.api.vercel.webhook_events.BillingManager")
+ def test_a_billing_event_the_other_region_holds_is_forwarded_and_not_billed_here(self, billing_manager):
+ response = self._post(self._billing_payload("icfg_unknown"))
- assert response.status_code == status.HTTP_400_BAD_REQUEST
+ self.assertEqual(response.status_code, 202)
+ billing_manager.assert_not_called()
+ self.forward.assert_called_once()
+ self.assertEqual(self.forward.call_args.kwargs["url"], "https://eu.posthog.com/webhooks/vercel")
+ # The other region waits up to 30 s for the billing service, so a shorter deadline here
+ # would abandon an invoice it is still processing.
+ self.assertGreater(self.forward.call_args.kwargs["timeout"], 30)
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- def test_deauthorization_unknown_config_succeeds(self):
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"installationId": "icfg_unknown"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_200_OK
- assert response.json()["status"] == "ok"
-
- @override_settings(
- VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret",
- SITE_URL="https://us.posthog.com",
- REGION_US_DOMAIN="us.posthog.com",
- REGION_EU_DOMAIN="eu.posthog.com",
- )
- @patch("ee.api.vercel.webhook_events.outbound_requests.post")
- def test_deauthorization_unknown_config_on_us_proxies_to_eu(self, mock_post):
- mock_eu_response = MagicMock()
- mock_eu_response.status_code = 200
- mock_post.return_value = mock_eu_response
-
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"installationId": "icfg_unknown"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_200_OK
- assert response.json()["status"] == "ok"
-
- mock_post.assert_called_once()
- call_kwargs = mock_post.call_args
- assert call_kwargs.kwargs["url"] == "https://eu.posthog.com/webhooks/vercel"
- assert call_kwargs.kwargs["headers"]["x-vercel-signature"] == signature
-
- @override_settings(
- VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret",
- SITE_URL="https://eu.posthog.com",
- REGION_US_DOMAIN="us.posthog.com",
- REGION_EU_DOMAIN="eu.posthog.com",
- )
- @patch("ee.api.vercel.webhook_events.outbound_requests.post")
- def test_deauthorization_unknown_config_on_eu_does_not_proxy(self, mock_post):
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"installationId": "icfg_unknown"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_200_OK
- mock_post.assert_not_called()
-
- @override_settings(
- VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret",
- SITE_URL="http://localhost:8000",
- REGION_US_DOMAIN="us.posthog.com",
- REGION_EU_DOMAIN="eu.posthog.com",
- )
- @patch("ee.api.vercel.webhook_events.outbound_requests.post")
- def test_deauthorization_unknown_config_on_dev_does_not_proxy(self, mock_post):
- payload = {
- "type": "integration-configuration.removed",
- "payload": {"installationId": "icfg_unknown"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_200_OK
- mock_post.assert_not_called()
-
- @override_settings(
- VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret",
- SITE_URL="https://us.posthog.com",
- REGION_US_DOMAIN="us.posthog.com",
- REGION_EU_DOMAIN="eu.posthog.com",
- )
- @patch("ee.api.vercel.webhook_events.outbound_requests.post")
- def test_billing_event_unknown_config_on_us_proxies_to_eu(self, mock_post):
- mock_eu_response = MagicMock()
- mock_eu_response.status_code = 200
- mock_post.return_value = mock_eu_response
-
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": "icfg_unknown", "invoiceId": "mi_123"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_200_OK
- mock_post.assert_called_once()
- call_kwargs = mock_post.call_args
- assert call_kwargs.kwargs["url"] == "https://eu.posthog.com/webhooks/vercel"
- assert call_kwargs.kwargs["headers"]["x-vercel-signature"] == signature
- # EU waits up to 30s for the billing service. A shorter read deadline would make US
- # abandon an invoice EU accepted, and log it as an unknown installation.
- _, read_timeout = call_kwargs.kwargs["timeout"]
- assert read_timeout > 30
-
- @override_settings(
- VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret",
- SITE_URL="https://us.posthog.com",
- REGION_US_DOMAIN="us.posthog.com",
- REGION_EU_DOMAIN="eu.posthog.com",
- )
- @patch("ee.api.vercel.webhook_events.capture_exception")
- @patch("ee.api.vercel.webhook_events.outbound_requests.post")
- def test_billing_event_unknown_in_both_regions_returns_404(self, mock_post, mock_capture_exception):
- mock_eu_response = MagicMock()
- mock_eu_response.status_code = 404
- mock_post.return_value = mock_eu_response
-
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": "icfg_unknown", "invoiceId": "mi_123"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_404_NOT_FOUND
- mock_post.assert_called_once()
- mock_capture_exception.assert_not_called()
-
- @override_settings(
- VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret",
- SITE_URL="https://eu.posthog.com",
- REGION_US_DOMAIN="us.posthog.com",
- REGION_EU_DOMAIN="eu.posthog.com",
- )
- @patch("ee.api.vercel.webhook_events.outbound_requests.post")
- def test_billing_event_unknown_config_on_eu_does_not_proxy(self, mock_post):
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": "icfg_unknown", "invoiceId": "mi_123"},
- }
- signature = self._sign_payload(payload)
+ def test_the_forwarded_request_carries_the_signature_the_other_region_checks(self):
+ self._post(self._billing_payload("icfg_unknown"))
- response = self._post_webhook(payload, signature=signature)
+ headers = {key.lower(): value for key, value in self.forward.call_args.kwargs["headers"].items()}
+ self.assertIn("x-vercel-signature", headers)
+ # The other region reads which region it is off the connection, so a forwarded host would
+ # make it forward the delivery on again.
+ self.assertNotIn("host", headers)
- assert response.status_code == status.HTTP_404_NOT_FOUND
- mock_post.assert_not_called()
+ def test_a_forward_that_fails_is_not_receipted(self):
+ self.forward.side_effect = RequestException("boom")
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
- @patch("ee.api.vercel.webhook_events.BillingManager")
- @patch("ee.api.vercel.webhook_events.License")
- def test_billing_event_forwarded_to_billing_service(self, mock_license_model, mock_billing_manager_class):
- mock_license = MagicMock()
- mock_license_model.objects.first.return_value = mock_license
+ response = self._post(self._billing_payload("icfg_unknown"))
- mock_billing_manager = MagicMock()
- mock_billing_manager_class.return_value = mock_billing_manager
+ self.assertEqual(response.status_code, 500)
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": self.installation_id, "invoiceId": "mi_123"},
- }
- signature = self._sign_payload(payload)
+ def test_a_forward_the_other_region_refuses_is_not_receipted(self):
+ self.forward.return_value = _forward_response(500)
- response = self._post_webhook(payload, signature=signature)
+ response = self._post(self._billing_payload("icfg_unknown"))
- assert response.status_code == status.HTTP_200_OK
- assert response.json()["status"] == "ok"
+ self.assertEqual(response.status_code, 500)
- mock_billing_manager.handle_billing_provider_webhook.assert_called_once_with(
- event_type="marketplace.invoice.paid",
- event_data=payload["payload"],
- organization=self.organization,
- billing_provider="vercel",
- )
+ @patch("ee.api.vercel.webhook_events.BillingManager")
+ @patch("ee.api.vercel.webhook_events._get_integration", side_effect=OperationalError("statement timeout"))
+ def test_an_ownership_lookup_that_fails_dispatches_nothing(self, _lookup, billing_manager):
+ # A lookup that did not answer rules no region out. Dispatching anyway would run the
+ # consumer, find nothing local, and receipt a delivery the owning region never sees.
+ response = self._post(self._billing_payload(self.installation_id))
+
+ self.assertEqual(response.status_code, 500)
+ self.forward.assert_not_called()
+ billing_manager.assert_not_called()
+
+ @patch("ee.api.vercel.webhook_events.logger")
+ def test_an_installation_no_region_holds_is_reported_quietly_in_the_region_that_forwards(self, logger):
+ # This region sees a local miss for every event of every installation the other region
+ # holds, so a warning here would fire on all of them.
+ response = self._post(self._billing_payload("icfg_unknown"))
+
+ self.assertEqual(response.status_code, 202)
+ self.assertNotIn("vercel_webhook_unknown_config", [call.args[0] for call in logger.warning.call_args_list])
+ self.assertIn("vercel_webhook_unknown_config", [call.args[0] for call in logger.info.call_args_list])
+
+ @patch("ee.api.vercel.webhook_events.logger")
+ def test_an_installation_no_region_holds_is_reported_by_the_region_that_looks_last(self, logger):
+ # Both regions have looked by the time the forwarded request lands here, so this miss is
+ # the one worth a warning, and the delivery is receipted rather than retried forever.
+ with (
+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),
+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "us.posthog.com"),
+ ):
+ response = self._post(self._billing_payload("icfg_unknown"))
+
+ self.assertEqual(response.status_code, 202)
+ self.assertIn("vercel_webhook_unknown_config", [call.args[0] for call in logger.warning.call_args_list])
+
+ def test_the_region_that_receives_forwards_never_forwards_again(self):
+ # Without this guard a delivery no region holds would bounce between the two regions.
+ with (
+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),
+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "us.posthog.com"),
+ ):
+ response = self._post(self._billing_payload("icfg_unknown"))
+
+ self.assertEqual(response.status_code, 202)
+ self.forward.assert_not_called()
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
@patch("ee.api.vercel.webhook_events.BillingManager")
@patch("ee.api.vercel.webhook_events.License")
- def test_billing_error_returns_500(self, mock_license_model, mock_billing_manager_class):
- mock_license = MagicMock()
- mock_license_model.objects.first.return_value = mock_license
+ def test_a_billing_service_error_is_not_receipted(self, license_model, billing_manager_class):
+ license_model.objects.first.return_value = MagicMock()
+ billing_manager = MagicMock()
+ billing_manager_class.return_value = billing_manager
+ billing_manager.handle_billing_provider_webhook.side_effect = Exception("Billing service error")
- mock_billing_manager = MagicMock()
- mock_billing_manager_class.return_value = mock_billing_manager
- mock_billing_manager.handle_billing_provider_webhook.side_effect = Exception("Billing service error")
+ response = self._post(self._billing_payload(self.installation_id))
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": self.installation_id, "invoiceId": "mi_123"},
- }
- signature = self._sign_payload(payload)
-
- response = self._post_webhook(payload, signature=signature)
-
- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
- assert "Processing failed" in response.json()["error"]
+ self.assertEqual(response.status_code, 500)
- @override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="test_webhook_secret")
@patch("ee.api.vercel.webhook_events.License")
- def test_no_license_returns_500(self, mock_license_model):
- mock_license_model.objects.first.return_value = None
-
- payload = {
- "type": "marketplace.invoice.paid",
- "payload": {"installationId": self.installation_id, "invoiceId": "mi_123"},
- }
- signature = self._sign_payload(payload)
+ def test_a_missing_license_is_not_receipted(self, license_model):
+ license_model.objects.first.return_value = None
- response = self._post_webhook(payload, signature=signature)
+ response = self._post(self._billing_payload(self.installation_id))
- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
- assert "Processing failed" in response.json()["error"]
+ self.assertEqual(response.status_code, 500)
diff --git a/ee/api/vercel/vercel_webhooks.py b/ee/api/vercel/vercel_webhooks.py
deleted file mode 100644
index 003800edbf1d..000000000000
--- a/ee/api/vercel/vercel_webhooks.py
+++ /dev/null
@@ -1,66 +0,0 @@
-import hmac
-import hashlib
-
-from django.conf import settings
-
-import structlog
-from rest_framework import status
-from rest_framework.decorators import api_view, authentication_classes, permission_classes
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.exceptions_capture import capture_exception
-
-from ee.api.vercel.webhook_events import VercelEventOutcome, VercelEventProcessingError, handle_vercel_event
-
-logger = structlog.get_logger(__name__)
-
-
-def _is_valid_signature(payload: bytes, signature: str | None) -> bool:
- if not signature:
- return False
-
- secret = getattr(settings, "VERCEL_CLIENT_INTEGRATION_SECRET", None)
- if not secret:
- logger.error("vercel_webhook_missing_secret")
- capture_exception(Exception("VERCEL_CLIENT_INTEGRATION_SECRET not configured"), {})
- return False
-
- expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha1).hexdigest()
- return hmac.compare_digest(expected, signature)
-
-
-# The outcomes the handling reports, and what each one answers Vercel.
-_OUTCOME_RESPONSES = {
- VercelEventOutcome.ACCEPTED: ({"status": "ok"}, status.HTTP_200_OK),
- VercelEventOutcome.IGNORED: ({"status": "ignored"}, status.HTTP_200_OK),
- VercelEventOutcome.MISSING_CONFIG_ID: ({"error": "Missing configurationId"}, status.HTTP_400_BAD_REQUEST),
- VercelEventOutcome.UNKNOWN_CONFIG: ({"error": "Unknown configuration"}, status.HTTP_404_NOT_FOUND),
-}
-
-
-@api_view(["POST"])
-@authentication_classes([])
-@permission_classes([])
-def vercel_webhook(request: Request) -> Response:
- """
- Handle Vercel webhooks. Routes billing events (marketplace.invoice.*) to the billing service.
- Non-billing events are acknowledged but not processed.
- """
- signature = request.headers.get("x-vercel-signature")
- if not _is_valid_signature(request.body, signature):
- logger.warning("vercel_webhook_invalid_signature")
- return Response({"error": "Invalid signature"}, status=status.HTTP_401_UNAUTHORIZED)
-
- try:
- outcome = handle_vercel_event(
- event_type=request.data.get("type"),
- payload=request.data.get("payload", {}),
- raw_body=request.body,
- signature=signature,
- )
- except VercelEventProcessingError:
- return Response({"error": "Processing failed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
-
- body, response_status = _OUTCOME_RESPONSES[outcome]
- return Response(body, status=response_status)
diff --git a/ee/api/vercel/webhook_consumers.py b/ee/api/vercel/webhook_consumers.py
new file mode 100644
index 000000000000..398c31a50174
--- /dev/null
+++ b/ee/api/vercel/webhook_consumers.py
@@ -0,0 +1,66 @@
+"""The Vercel Marketplace webhook consumer.
+
+`ee/` is not a product, so this module is named in `posthog.ingress.dispatch.loading` rather
+than discovered. It stays cheap to import: the handling is behind a deferred import, because the
+registry loads this module on the first delivery of any provider.
+"""
+
+from typing import Any
+
+import structlog
+
+from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDelivery
+from posthog.ingress.vercel.provider import RECEIVING_REGION_CONTEXT_KEY, VERCEL_EVENT_TYPES
+
+logger = structlog.get_logger(__name__)
+
+
+def _event_payload(delivery: WebhookDelivery) -> dict[str, Any]:
+ """The `payload` field of the Vercel envelope the provider passed through whole."""
+ payload = dict(delivery.payload).get("payload")
+ return payload if isinstance(payload, dict) else {}
+
+
+def _in_receiving_region(delivery: WebhookDelivery) -> bool:
+ return delivery.context.get(RECEIVING_REGION_CONTEXT_KEY) == "true"
+
+
+def _run_vercel_event(delivery: WebhookDelivery) -> None:
+ from ee.api.vercel.webhook_events import (
+ handle_vercel_event, # noqa: PLC0415 - keeps billing and the license model off the registry's import path
+ )
+
+ event_type = dict(delivery.payload).get("type")
+ outcome = handle_vercel_event(
+ event_type=event_type,
+ payload=_event_payload(delivery),
+ in_receiving_region=_in_receiving_region(delivery),
+ )
+ logger.info("vercel_webhook_handled", event_type=event_type, outcome=str(outcome))
+
+
+def _vercel_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
+ """Which region holds the installation this event is about.
+
+ Both event families ask, because both are processed by the region that holds the
+ installation: only there does `BillingManager` find the `Organization` a billing call needs,
+ and only there is there an installation to delete.
+ """
+ from ee.api.vercel.webhook_events import extract_config_id, installation_is_local # noqa: PLC0415 - as above
+
+ config_id = extract_config_id(_event_payload(delivery))
+ if not config_id:
+ return DeliveryOwnership.UNDECIDED
+ return DeliveryOwnership.LOCAL if installation_is_local(config_id) else DeliveryOwnership.ELSEWHERE
+
+
+WEBHOOK_CONSUMERS = (
+ WebhookConsumer(
+ name="vercel_marketplace",
+ provider="vercel",
+ app="marketplace",
+ event_types=VERCEL_EVENT_TYPES,
+ handler=_run_vercel_event,
+ ownership=_vercel_ownership,
+ ),
+)
diff --git a/ee/api/vercel/webhook_events.py b/ee/api/vercel/webhook_events.py
index b8222a628d3f..cfb26a601aef 100644
--- a/ee/api/vercel/webhook_events.py
+++ b/ee/api/vercel/webhook_events.py
@@ -1,18 +1,17 @@
"""What PostHog does with one verified Vercel webhook event.
-Separate from the view, because the transport around this endpoint is being replaced and the
-handling is not. The caller decides what an outcome answers on the wire; nothing here does.
+Separate from the transport, which is `posthog/ingress/`: the caller decides what an outcome
+answers on the wire, and nothing here does. Which region holds an installation is answered here
+too, because only this module knows what an installation is; the forward itself is ingress's.
"""
from enum import StrEnum
from typing import Any
-from django.conf import settings
-
-import requests as outbound_requests
import structlog
from posthog.exceptions_capture import capture_exception
+from posthog.ingress.dispatch.database import bounded_statement_timeout
from posthog.models.organization_integration import OrganizationIntegration
from ee.billing.billing_manager import BillingManager, BillingServiceOpenInvoicesError
@@ -24,12 +23,10 @@ logger = structlog.get_logger(__name__)
BILLING_EVENT_PREFIX = "marketplace.invoice."
DEAUTHORIZATION_EVENT = "integration-configuration.removed"
-CROSS_REGION_PROXY_TIMEOUT = 10
-# EU waits up to 30 seconds for the billing service, so the billing hop needs a longer read
-# deadline. A shorter one makes US report a slow billing service as an unknown installation.
-CROSS_REGION_BILLING_PROXY_TIMEOUT = (10, 35)
-DEFAULT_US_DOMAIN = "us.posthog.com"
-DEFAULT_EU_DOMAIN = "eu.posthog.com"
+# The lookup below is a sequential scan: the only index on the table is the unique
+# (organization, kind, integration_id), and this reads by kind and integration_id alone. The table
+# is small, but this runs inside the request, so the cost is capped rather than assumed.
+OWNERSHIP_LOOKUP_TIMEOUT_MS = 2000
class VercelEventOutcome(StrEnum):
@@ -40,7 +37,7 @@ class VercelEventOutcome(StrEnum):
IGNORED = "ignored"
# The event named no installation, so there is nothing to look up.
MISSING_CONFIG_ID = "missing_config_id"
- # A billing event for an installation no region holds.
+ # An event for an installation this region does not hold.
UNKNOWN_CONFIG = "unknown_config"
@@ -48,41 +45,6 @@ class VercelEventProcessingError(Exception):
"""Handling failed on our side, so the event was not processed."""
-def _is_us_region() -> bool:
- us_domain = getattr(settings, "REGION_US_DOMAIN", DEFAULT_US_DOMAIN)
- return settings.SITE_URL == f"https://{us_domain}"
-
-
-def _proxy_to_eu(
- raw_body: bytes,
- signature: str | None,
- timeout: float | tuple[float, float] = CROSS_REGION_PROXY_TIMEOUT,
-) -> int | None:
- """Forward a webhook to EU. Returns the EU status code, or None on failure."""
- eu_domain = getattr(settings, "REGION_EU_DOMAIN", DEFAULT_EU_DOMAIN)
- target_url = f"https://{eu_domain}/webhooks/vercel"
-
- headers: dict[str, str] = {"Content-Type": "application/json"}
- if signature:
- headers["x-vercel-signature"] = signature
-
- try:
- response = outbound_requests.post(
- url=target_url,
- data=raw_body,
- headers=headers,
- timeout=timeout,
- )
- logger.info(
- "vercel_webhook_proxied_to_eu",
- status_code=response.status_code,
- )
- return response.status_code
- except outbound_requests.RequestException as e:
- logger.warning("vercel_webhook_proxy_to_eu_failed", error=str(e))
- return None
-
-
def extract_config_id(payload: dict[str, Any]) -> str | None:
# Billing events use "installationId". Deauthorization events use "configuration.id".
return payload.get("installationId") or payload.get("configuration", {}).get("id")
@@ -98,14 +60,35 @@ def is_deauthorization_event(event_type: str | None) -> bool:
def _get_integration(config_id: str) -> OrganizationIntegration | None:
try:
- return OrganizationIntegration.objects.select_related("organization").get(
- kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
- integration_id=config_id,
- )
+ with bounded_statement_timeout(OWNERSHIP_LOOKUP_TIMEOUT_MS, models=[OrganizationIntegration]):
+ return OrganizationIntegration.objects.select_related("organization").get(
+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
+ integration_id=config_id,
+ )
except OrganizationIntegration.DoesNotExist:
return None
+def installation_is_local(config_id: str) -> bool:
+ """Whether this region holds the installation, for ingress's ownership lookup.
+
+ A database error is let out rather than answered as a miss: ingress asks Vercel for the
+ delivery again, where a guess would send the event to the wrong region or lose it.
+ """
+ return _get_integration(config_id) is not None
+
+
+def _log_unknown_config(event_name: str, config_id: str, event_type: str | None, in_receiving_region: bool) -> None:
+ """Report an installation this region does not hold, as loudly as the region warrants.
+
+ The receiving region sees this for every event of every installation the other region holds,
+ because the forward is what settles those. Only the other region, which looks last, can say
+ that no region holds the installation, so only there is it a warning.
+ """
+ log = logger.info if in_receiving_region else logger.warning
+ log(event_name, config_id=config_id, event_type=event_type)
+
+
def _forward_to_billing_service(event_type: str, payload: dict[str, Any], integration: OrganizationIntegration) -> None:
license = License.objects.first()
if not license:
@@ -120,53 +103,40 @@ def _forward_to_billing_service(event_type: str, payload: dict[str, Any], integr
)
-def _handle_deauthorization(
- config_id: str,
- raw_body: bytes,
- signature: str | None,
-) -> VercelEventOutcome:
+def _handle_deauthorization(config_id: str, in_receiving_region: bool) -> VercelEventOutcome:
integration = _get_integration(config_id)
- if integration:
- is_connectable = integration.config.get("type") == "connectable"
- logger.info(
- "vercel_webhook_deauthorize",
- config_id=config_id,
- org_id=str(integration.organization_id),
- is_connectable=is_connectable,
+ if not integration:
+ _log_unknown_config(
+ "vercel_webhook_deauthorize_unknown_config", config_id, DEAUTHORIZATION_EVENT, in_receiving_region
)
- if is_connectable:
- integration.delete()
- return VercelEventOutcome.ACCEPTED
- try:
- VercelIntegration.delete_installation(config_id)
- except BillingServiceOpenInvoicesError as e:
- # Vercel ignores non-200 from webhooks and shows "Integration Deleted" regardless.
- # The marketplace DELETE API endpoint handles the actual blocking with 409.
- # Log the warning but accept the event to avoid misleading error tracking noise.
- logger.warning(
- "vercel_webhook_deauthorize_blocked_by_open_invoices",
- config_id=config_id,
- reason=e.message,
- )
- except Exception as e:
- logger.exception("vercel_webhook_deauthorize_delete_failed", config_id=config_id)
- capture_exception(e, {"config_id": config_id})
- raise VercelEventProcessingError(str(e)) from e
- return VercelEventOutcome.ACCEPTED
+ return VercelEventOutcome.UNKNOWN_CONFIG
- if _is_us_region():
- logger.info("vercel_webhook_deauthorize_proxying_to_eu", config_id=config_id)
- eu_status = _proxy_to_eu(raw_body, signature)
- if eu_status is None or eu_status >= 300:
- logger.warning(
- "vercel_webhook_deauthorize_eu_proxy_non_ok",
- config_id=config_id,
- eu_status=eu_status,
- )
- else:
- logger.warning("vercel_webhook_deauthorize_unknown_config", config_id=config_id)
+ is_connectable = integration.config.get("type") == "connectable"
+ logger.info(
+ "vercel_webhook_deauthorize",
+ config_id=config_id,
+ org_id=str(integration.organization_id),
+ is_connectable=is_connectable,
+ )
+ if is_connectable:
+ integration.delete()
+ return VercelEventOutcome.ACCEPTED
- # A deauthorization for an installation this region never held is still done with.
+ try:
+ VercelIntegration.delete_installation(config_id)
+ except BillingServiceOpenInvoicesError as e:
+ # Vercel ignores non-200 from webhooks and shows "Integration Deleted" regardless.
+ # The marketplace DELETE API endpoint handles the actual blocking with 409.
+ # Log the warning but accept the event to avoid misleading error tracking noise.
+ logger.warning(
+ "vercel_webhook_deauthorize_blocked_by_open_invoices",
+ config_id=config_id,
+ reason=e.message,
+ )
+ except Exception as e:
+ logger.exception("vercel_webhook_deauthorize_delete_failed", config_id=config_id)
+ capture_exception(e, {"config_id": config_id})
+ raise VercelEventProcessingError(str(e)) from e
return VercelEventOutcome.ACCEPTED
@@ -174,25 +144,11 @@ def _handle_billing(
event_type: str,
payload: dict[str, Any],
config_id: str,
- raw_body: bytes,
- signature: str | None,
+ in_receiving_region: bool,
) -> VercelEventOutcome:
integration = _get_integration(config_id)
if not integration:
- # All Vercel webhooks arrive on US, so the installation can belong to EU.
- eu_status = (
- _proxy_to_eu(raw_body, signature, timeout=CROSS_REGION_BILLING_PROXY_TIMEOUT) if _is_us_region() else None
- )
- if eu_status is not None and eu_status < 300:
- logger.info("vercel_webhook_billing_proxied_to_eu", config_id=config_id, event_type=event_type)
- return VercelEventOutcome.ACCEPTED
-
- logger.warning(
- "vercel_webhook_unknown_config",
- config_id=config_id,
- event_type=event_type,
- eu_status=eu_status,
- )
+ _log_unknown_config("vercel_webhook_unknown_config", config_id, event_type, in_receiving_region)
return VercelEventOutcome.UNKNOWN_CONFIG
try:
@@ -210,10 +166,13 @@ def handle_vercel_event(
*,
event_type: str | None,
payload: dict[str, Any],
- raw_body: bytes,
- signature: str | None,
+ in_receiving_region: bool,
) -> VercelEventOutcome:
- """Route one verified event. Raises `VercelEventProcessingError` when handling failed."""
+ """Route one verified event. Raises `VercelEventProcessingError` when handling failed.
+
+ `in_receiving_region` says whether Vercel delivered here or the other region forwarded it,
+ which decides how loudly an installation nobody holds is reported.
+ """
config_id = extract_config_id(payload)
logger.info("vercel_webhook_received", event_type=event_type, config_id=config_id)
@@ -221,7 +180,7 @@ def handle_vercel_event(
if not config_id:
logger.error("vercel_webhook_deauthorize_missing_config_id")
return VercelEventOutcome.MISSING_CONFIG_ID
- return _handle_deauthorization(config_id, raw_body, signature)
+ return _handle_deauthorization(config_id, in_receiving_region)
if not is_billing_event(event_type):
logger.info("vercel_webhook_non_billing_event", event_type=event_type)
@@ -233,4 +192,4 @@ def handle_vercel_event(
# Guaranteed by the is_billing_event check above.
assert event_type is not None
- return _handle_billing(event_type, payload, config_id, raw_body, signature)
+ return _handle_billing(event_type, payload, config_id, in_receiving_region)
diff --git a/ee/urls.py b/ee/urls.py
index fe93323c9a54..80c7de2e5ab3 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -11,6 +11,8 @@ from django_otp.plugins.otp_static.models import StaticDevice
from django_otp.plugins.otp_totp.models import TOTPDevice
from posthog.admin import register_all_admin
+from posthog.ingress.vercel.provider import build_vercel_provider
+from posthog.ingress.views import build_webhook_view
from posthog.middleware import impersonated_session_logout
from posthog.views import api_key_search_view, redis_edit_ttl_view, redis_values_view
@@ -19,7 +21,7 @@ from products.cdp.backend.api import hooks
from ee.admin.loginas_views import loginas_user, upgrade_impersonation
from ee.admin.oauth_views import admin_auth_check, admin_oauth_success
from ee.api import integration
-from ee.api.vercel import vercel_connect, vercel_sso, vercel_webhooks
+from ee.api.vercel import vercel_connect, vercel_sso
from ee.middleware import admin_oauth2_callback
from ee.support_sidebar_max.views import MaxChatViewSet
@@ -247,7 +249,7 @@ urlpatterns: list[Any] = [
r"^api/vercel/connect/session/?$",
vercel_connect.VercelConnectLinkViewSet.as_view({"get": "session_info"}),
),
- path("webhooks/vercel", csrf_exempt(vercel_webhooks.vercel_webhook), name="vercel_webhooks"),
+ path("webhooks/vercel", build_webhook_view(build_vercel_provider()), name="vercel_webhooks"),
path("scim/v2/<str:scim_slug>/Users", csrf_exempt(scim_views.SCIMUsersView.as_view()), name="scim_users"),
path(
"scim/v2/<str:scim_slug>/Users/<int:user_id>",
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index d34501a785f8..76e9b08e8b4c 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -53,7 +53,7 @@ An HMAC over raw bytes proves only the signature, so its `facts` are empty and `
`verify/schemes.py` holds `HmacSignature` and `SnsSignature`; `verify/jwt.py` holds `BearerJwt`, for a provider that authenticates with a signed token instead of a shared secret.
Each class docstring carries its own reasoning.
-`HmacSha256` is `HmacSignature` with the default digest, and it is the name to reach for. Only a provider that signs with something else sets `digest`, and everything else about the scheme, `rejects_headers` included, behaves the same whichever digest it carries.
+`HmacSha256` is `HmacSignature` with the default digest, and it is the name to reach for. Only a provider that signs with something else sets `digest`, which today is Vercel with SHA-1, and everything else about the scheme, `rejects_headers` included, behaves the same whichever digest it carries.
A scheme also answers `rejects_headers(headers)`, the part of the check that needs no body: `HmacSha256` refuses a missing or malformed signature header and a missing, malformed or stale timestamp header there, and `BearerJwt` refuses a request that carries no bearer token. The answer is the same INVALID the full check would reach, with the same status, log line and metric outcome, so an unauthenticated caller cannot make an endpoint read a body of up to the request limit for it. A scheme that cannot decide from headers alone answers `False`, which is what `SnsSignature` does, and so does an HMAC scheme whose secret is unset, so an unconfigured endpoint still answers NOT_CONFIGURED.
@@ -79,10 +79,12 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf
| `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` |
+| `vercel` | `/webhooks/vercel` | `marketplace` | `vercel_marketplace` | `ee/api/vercel/webhook_consumers.py` |
The owner of the third-party App registration owns the route.
The customer-facing GitHub App is shared across products, so its two endpoints are declared in `posthog/urls.py`.
Every other endpoint is declared by the product that registered the App, in its own `routes.py`.
+The Vercel Marketplace App is registered by `ee/`, which is not a product, so its route is declared in `ee/urls.py` and its consumer module is named in `posthog/ingress/dispatch/loading.py` rather than discovered.
The Vapi endpoint is the only one that caps request volume: its provider sets `throttle_class` to a per-IP throttle, because the endpoint is public and Vapi's egress is shared across tenants.
@@ -187,8 +189,8 @@ Ingress carries both as general controls, so the next endpoint gets them without
## Regional forwarding
A third party holds one callback URL, which points at one region, so a delivery about a resource the other region owns still arrives there first.
-For every App registered today that URL is the primary region (EU) and the forward runs to the secondary one (US).
-A provider whose App was registered against the secondary region instead overrides `receiving_region_domain()`, and the forward runs the other way.
+For almost every App that URL is the primary region (EU) and the forward runs to the secondary one (US).
+A provider whose App was registered against the secondary region instead overrides `receiving_region_domain()`, and the forward runs the other way; Vercel is the only one today.
Ingress owns the forward, because what is replayed is the signed body — a consumer only ever sees the parsed mapping.
A consumer whose resources are split by region declares `ownership`, a callable that takes the delivery and answers a `DeliveryOwnership`:
diff --git a/posthog/ingress/dispatch/loading.py b/posthog/ingress/dispatch/loading.py
index 2ec571842650..4baddbfd06dc 100644
--- a/posthog/ingress/dispatch/loading.py
+++ b/posthog/ingress/dispatch/loading.py
@@ -5,6 +5,7 @@ path, which `posthog/test/repo_invariants/test_startup_import_budget.py` exists
clear -- a shell, a migrate and every Celery worker would pay for it.
"""
+import importlib
from collections.abc import Sequence
from functools import lru_cache
@@ -17,6 +18,27 @@ from posthog.products import load_product_modules
PRODUCT_CONSUMER_MODULE = "webhook_consumers"
PRODUCT_CONSUMER_ATTRIBUTE = "WEBHOOK_CONSUMERS"
+# `ee/` is not a product, so `load_product_modules` never finds it. The modules it declares
+# consumers in are named here instead, and a build without `ee/` simply has none of them.
+NON_PRODUCT_CONSUMER_MODULES = ("ee.api.vercel.webhook_consumers",)
+
+
+def non_product_consumers() -> list[WebhookConsumer]:
+ """Consumers declared outside `products/`, by a tree core knows by name."""
+ consumers: list[WebhookConsumer] = []
+ for module_name in NON_PRODUCT_CONSUMER_MODULES:
+ try:
+ module = importlib.import_module(module_name)
+ except ModuleNotFoundError as error:
+ # Only the tree being absent is a reason to skip. A broken import inside the module
+ # raises the same class, and swallowing it would deregister the consumer in silence.
+ if error.name is not None and (module_name == error.name or module_name.startswith(f"{error.name}.")):
+ continue
+ raise
+ declared: Sequence[WebhookConsumer] = getattr(module, PRODUCT_CONSUMER_ATTRIBUTE, ())
+ consumers.extend(declared)
+ return consumers
+
def product_consumers() -> list[WebhookConsumer]:
"""Consumers declared by `products/<x>/backend/webhook_consumers.py`."""
@@ -31,7 +53,7 @@ def product_consumers() -> list[WebhookConsumer]:
def get_consumer_registry() -> ConsumerRegistry:
return ConsumerRegistry(
providers=provider_specs(),
- consumers=[*core_consumers(), *product_consumers()],
+ consumers=[*core_consumers(), *non_product_consumers(), *product_consumers()],
)
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index 54fcdbc4c7b5..33209e765e3b 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -30,6 +30,7 @@ _INCARNATION_MODULES = (
"posthog.ingress.mailgun.provider",
"posthog.ingress.vapi.provider",
"posthog.ingress.sns.provider",
+ "posthog.ingress.vercel.provider",
)
diff --git a/posthog/ingress/test/test_registry.py b/posthog/ingress/test/test_registry.py
index 24e186899511..a6cb111545bd 100644
--- a/posthog/ingress/test/test_registry.py
+++ b/posthog/ingress/test/test_registry.py
@@ -1,7 +1,11 @@
+from unittest.mock import patch
+
from django.test import SimpleTestCase
+from parameterized import parameterized
+
from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
-from posthog.ingress.dispatch.loading import get_consumer_registry, reset_consumer_registry
+from posthog.ingress.dispatch.loading import get_consumer_registry, non_product_consumers, reset_consumer_registry
from posthog.ingress.dispatch.registry import ConsumerRegistry, RegistryError
from posthog.ingress.github.provider import SPECS as GITHUB_SPECS
@@ -82,6 +86,30 @@ class TestConsumerRegistry(SimpleTestCase):
["installation_lifecycle"],
)
+ def test_the_named_non_product_module_is_registered(self) -> None:
+ self.assertEqual([consumer.name for consumer in non_product_consumers()], ["vercel_marketplace"])
+
+ @parameterized.expand(
+ [
+ # A build without `ee/` has no Vercel endpoint either, so there is nothing to register.
+ ("the_named_module_itself", "ee.api.vercel.webhook_consumers", []),
+ ("the_tree_above_it", "ee", []),
+ # Anything else means the module is there and broken, and a consumer that silently
+ # leaves the registry takes its endpoint's deliveries with it.
+ ("a_module_the_declaration_imports", "ee.billing.billing_manager", None),
+ ("an_unrelated_module", "some_third_party", None),
+ ]
+ )
+ def test_only_a_missing_ee_tree_is_skipped(self, _name: str, missing: str, expected: list[str] | None) -> None:
+ error = ModuleNotFoundError(f"No module named {missing!r}", name=missing)
+
+ with patch("posthog.ingress.dispatch.loading.importlib.import_module", side_effect=error):
+ if expected is None:
+ with self.assertRaises(ModuleNotFoundError):
+ non_product_consumers()
+ else:
+ self.assertEqual([consumer.name for consumer in non_product_consumers()], expected)
+
def test_no_github_consumer_opts_into_regional_forwarding(self) -> None:
# Each region runs its own GitHub App, with its own webhook URL and its own secret, so a
# replayed delivery can only fail the other region's signature check. The forward lane
diff --git a/posthog/ingress/test/test_vercel.py b/posthog/ingress/test/test_vercel.py
new file mode 100644
index 000000000000..43d841a84603
--- /dev/null
+++ b/posthog/ingress/test/test_vercel.py
@@ -0,0 +1,100 @@
+import hmac
+import json
+
+from unittest.mock import patch
+
+from django.http import HttpRequest
+from django.test import RequestFactory, SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.ingress.vercel.provider import (
+ RECEIVING_REGION_CONTEXT_KEY,
+ VERCEL_BILLING_EVENT,
+ VERCEL_DEAUTHORIZATION_EVENT,
+ build_vercel_provider,
+)
+from posthog.ingress.verify.schemes import VerificationOutcome
+
+SECRET = "vercel-integration-client-secret"
+
+
+def _request(body: bytes, *, signed: bool = True, host: str | None = None) -> HttpRequest:
+ headers = {"x-vercel-signature": hmac.digest(SECRET.encode(), body, "sha1").hex()} if signed else {}
+ if host is not None:
+ headers["Host"] = host
+ return RequestFactory().post("/webhooks/vercel", data=body, content_type="application/json", headers=headers)
+
+
+@override_settings(VERCEL_CLIENT_INTEGRATION_SECRET=SECRET)
+class TestVercelProvider(SimpleTestCase):
+ def setUp(self) -> None:
+ self.provider = build_vercel_provider()
+ self.body = json.dumps({"type": "marketplace.invoice.paid", "payload": {"installationId": "icfg_1"}}).encode()
+
+ def test_the_signature_is_hmac_sha1_over_the_raw_body(self) -> None:
+ # Vercel signs with SHA-1, which no other provider here does, so a digest default that
+ # silently applied would refuse every real delivery.
+ verified = self.provider.verify(_request(self.body))
+ refused = self.provider.verify(_request(self.body, signed=False))
+
+ self.assertEqual(verified.outcome, VerificationOutcome.VERIFIED)
+ self.assertEqual(refused.outcome, VerificationOutcome.INVALID)
+
+ def test_the_forward_waits_longer_than_the_billing_call_it_may_be_waiting_on(self) -> None:
+ # The owning region blocks up to 30 s on the billing service, so a shorter deadline here
+ # makes the receiving region give up on an invoice the other region is still processing.
+ self.assertGreater(self.provider.forward_timeout_seconds, 30)
+
+ def test_a_missing_secret_is_reported_rather_than_only_refused(self) -> None:
+ # Both a bad signature and a missing secret answer 401, so nothing in the status code
+ # distinguishes a dropped secret from a stranger probing the endpoint.
+ self.assertTrue(self.provider.reports_unconfigured)
+ self.assertEqual(self.provider.unconfigured_status, 401)
+ self.assertEqual(self.provider.invalid_signature_status, 401)
+
+ @parameterized.expand(
+ [
+ ("paid", "marketplace.invoice.paid", VERCEL_BILLING_EVENT),
+ ("refunded", "marketplace.invoice.refunded", VERCEL_BILLING_EVENT),
+ # A family member Vercel has not shipped yet still reaches the one consumer.
+ ("unseen_member", "marketplace.invoice.disputed", VERCEL_BILLING_EVENT),
+ ("deauthorization", VERCEL_DEAUTHORIZATION_EVENT, VERCEL_DEAUTHORIZATION_EVENT),
+ ("unrelated", "deployment.created", "deployment.created"),
+ ]
+ )
+ def test_the_invoice_family_collapses_to_one_registered_event_type(
+ self, _name: str, sent: str, expected: str
+ ) -> None:
+ body = json.dumps({"type": sent, "payload": {}}).encode()
+
+ deliveries = self.provider.deliveries(_request(body), json.loads(body), {})
+
+ self.assertEqual([delivery.event_type for delivery in deliveries], [expected])
+
+ def test_the_whole_envelope_travels_so_the_consumer_can_read_the_exact_event_name(self) -> None:
+ deliveries = self.provider.deliveries(_request(self.body), json.loads(self.body), {})
+
+ self.assertEqual(deliveries[0].payload["type"], "marketplace.invoice.paid")
+ self.assertIsNone(deliveries[0].delivery_id)
+
+ @parameterized.expand([("receiving", "us.posthog.com", "true"), ("other", "eu.posthog.com", "false")])
+ def test_a_delivery_says_whether_it_arrived_in_the_region_that_forwards(
+ self, _name: str, host: str, expected: str
+ ) -> None:
+ # The consumer reports an installation no region holds at warning level only in the
+ # region that looks last, and this flag is how it tells the two apart.
+ request = _request(self.body, host=host)
+
+ with (
+ patch("posthog.regions.SECONDARY_REGION_DOMAIN", "us.posthog.com"),
+ override_settings(ALLOWED_HOSTS=["us.posthog.com", "eu.posthog.com"]),
+ ):
+ deliveries = self.provider.deliveries(request, json.loads(self.body), {})
+
+ self.assertEqual(deliveries[0].context[RECEIVING_REGION_CONTEXT_KEY], expected)
+
+ def test_a_body_that_is_not_an_object_becomes_no_delivery(self) -> None:
+ # Vercel always sends an object. A verified body that is not one names no event, so there
+ # is nothing to dispatch and nothing a redelivery could fix.
+ self.assertEqual(self.provider.deliveries(_request(b"[]"), [], {}), ())
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 226dbc8d0b14..7c65048bdf3a 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -741,9 +741,11 @@ class TestRegionalForwarding(_DispatchingViewTestCase):
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:
+ def test_only_the_named_provider_receives_in_the_other_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.
+ # redirects signed deliveries for an endpoint whose owners never asked for that. A name
+ # on this list is a deliberate redirect, and every other provider forwards EU to US.
+ expected = ["posthog.ingress.vercel.provider.VercelProvider"]
overriding: list[str] = []
for module_name in _INCARNATION_MODULES:
module = importlib.import_module(module_name)
@@ -753,7 +755,7 @@ class TestRegionalForwarding(_DispatchingViewTestCase):
if candidate.receiving_region_domain is not WebhookProvider.receiving_region_domain:
overriding.append(f"{module_name}.{candidate.__name__}")
- self.assertEqual(overriding, [])
+ self.assertEqual(overriding, expected)
def test_a_provider_registered_against_the_secondary_region_forwards_the_other_way(self) -> None:
view = self._view(
diff --git a/posthog/ingress/vercel/README.md b/posthog/ingress/vercel/README.md
new file mode 100644
index 000000000000..2ad032e92905
--- /dev/null
+++ b/posthog/ingress/vercel/README.md
@@ -0,0 +1,63 @@
+# Vercel
+
+Deliveries from the Vercel Marketplace integration: invoice lifecycle events and the deauthorization event.
+
+## Headers
+
+- `x-vercel-signature` carries the signature ([Vercel request headers](https://vercel.com/docs/headers/request-headers#x-vercel-signature)).
+
+Vercel sends no delivery header and no timestamp header. The delivery id is in the body.
+
+## Signature scheme
+
+HMAC-SHA1 over the raw body, hex encoded, with no prefix.
+The key is the integration's Client Secret, which Vercel also calls the Integration Secret ([Vercel request headers](https://vercel.com/docs/headers/request-headers#x-vercel-signature)).
+SHA-1 is Vercel's choice, not one made here; every other provider in this package signs with SHA-256.
+There is no replay window, because there is no timestamp to check.
+Vercel ships no Python verifier, so the shared `HmacSignature` does the check rather than a vendor SDK.
+
+## Delivery id and event type
+
+Vercel sends a delivery id as the body's `id` field ([Vercel webhooks](https://vercel.com/docs/webhooks)).
+It is not used: `delivery_id` is `None`, so dedup is off.
+Turning dedup on changes which redeliveries reach the consumer, and a mark that outlives a run can drop a delivery, so it gets its own change rather than riding along with a transport swap.
+The consumer carries its own idempotency in the meantime, as it did before.
+
+The event type is the body's `type`.
+Vercel names every invoice event `marketplace.invoice.<something>` and adds to the family over time, while the registry matches an exact event type.
+So the family is registered under the prefix `marketplace.invoice`, the whole envelope travels as the delivery payload, and the consumer reads the exact name off `type`.
+`integration-configuration.removed` is passed through unchanged.
+
+## Apps and secrets
+
+One app, `marketplace`.
+The secret is the Django setting `VERCEL_CLIENT_INTEGRATION_SECRET`.
+
+## Quirks
+
+The marketplace App holds one webhook URL, registered against the secondary region (US), so `receiving_region_domain()` is overridden and the forward runs to the primary region (EU).
+Vercel is the only provider here that does that.
+
+Both event families declare ownership, because both are processed by the region that holds the installation: only there does the billing manager find the `Organization` a billing call needs, and only there is there an installation to delete.
+The ownership lookup reads `OrganizationIntegration` by kind and integration id, which is a scan of a small table rather than an indexed point lookup, so it runs under `bounded_statement_timeout`.
+
+A bad signature answers 401, and so does a missing secret.
+Both are what the endpoint answered before this moved onto ingress, and Vercel's integration is built against them.
+A missing secret also reaches error tracking (`reports_unconfigured`), because the 401 hides it from anyone reading status codes while every invoice event is refused.
+
+A delivery ingress cannot vouch for answers 500 rather than the 202 receipt: a consumer that raised, a forward that failed or answered non-2xx, or an ownership lookup that did not answer.
+Vercel does not publish a retry policy, so whether that buys a redelivery is unknown.
+The status is right either way, because the work did not run, and it is what the endpoint answered before.
+
+An event for an installation **no** region holds is receipted with 202, and that is a deliberate change from the 404 the endpoint used to answer.
+By the time the primary region has looked, both regions have looked, and no later attempt can find an installation that does not exist, so a failure status reports a failure that will never resolve.
+The miss is still reported: the primary region, which looks last, logs `vercel_webhook_unknown_config` or `vercel_webhook_deauthorize_unknown_config` at warning level.
+The secondary region logs the same at info, because there a local miss is what the forward is for, and a warning per delivery would fire for every event of every installation the other region holds.
+
+## Consumers
+
+One consumer, `vercel_marketplace`, declared in `ee/api/vercel/webhook_consumers.py` and named in `posthog/ingress/dispatch/loading.py`, because `ee/` is not a product and nothing discovers it.
+A build without an `ee/` tree skips it and has no Vercel endpoint either.
+
+The handler runs inside the request. It hands a billing event to the billing service, which waits up to 30 seconds, and a deauthorization to `VercelIntegration.delete_installation`.
+That 30 seconds is why `forward_timeout_seconds` is 35: a shorter deadline would make the receiving region give up on an invoice the other region is still processing.
diff --git a/posthog/ingress/vercel/__init__.py b/posthog/ingress/vercel/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/vercel/provider.py b/posthog/ingress/vercel/provider.py
new file mode 100644
index 000000000000..6357acf2f70c
--- /dev/null
+++ b/posthog/ingress/vercel/provider.py
@@ -0,0 +1,106 @@
+"""Vercel Marketplace webhooks.
+
+Three quirks: Vercel signs with HMAC-SHA1, its marketplace App is registered against the
+secondary region rather than the primary one, and its invoice events are an open-ended family
+that the registry, which matches an exact event type, sees under one collapsed name.
+"""
+
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+from django.conf import settings
+from django.http import HttpRequest
+from django.utils import timezone
+
+from posthog import regions
+from posthog.ingress.contracts import ProviderSpec, WebhookDelivery
+from posthog.ingress.providers import WebhookProvider
+from posthog.ingress.verify.schemes import HmacSignature, SignatureScheme
+
+# Vercel names every invoice event `marketplace.invoice.<something>` and adds to the family over
+# time. The registry matches an exact event type, so the family is registered under its prefix
+# and the consumer reads the exact name off the payload.
+VERCEL_BILLING_EVENT = "marketplace.invoice"
+VERCEL_DEAUTHORIZATION_EVENT = "integration-configuration.removed"
+VERCEL_EVENT_TYPES = frozenset({VERCEL_BILLING_EVENT, VERCEL_DEAUTHORIZATION_EVENT})
+
+VERCEL_SIGNATURE_HEADER = "x-vercel-signature"
+
+# Whether the request reached the region the marketplace App's one webhook URL names. Only that
+# region forwards, so only there is a local miss somebody else's to settle; the consumer reads
+# this to decide how loudly to report an installation it does not hold.
+RECEIVING_REGION_CONTEXT_KEY = "is_receiving_region"
+
+SPECS = (ProviderSpec(provider="vercel", app="marketplace", event_types=VERCEL_EVENT_TYPES),)
+
+
+def _vercel_secret() -> str | None:
+ return getattr(settings, "VERCEL_CLIENT_INTEGRATION_SECRET", "") or None
+
+
+def delivery_event_type(raw_event_type: str) -> str:
+ """The name the registry matches on, which collapses the invoice family to its prefix."""
+ if raw_event_type.startswith(f"{VERCEL_BILLING_EVENT}."):
+ return VERCEL_BILLING_EVENT
+ return raw_event_type
+
+
+class VercelProvider(WebhookProvider):
+ provider = "vercel"
+ app = "marketplace"
+ invalid_signature_status = 401
+ # The endpoint answered 401 for a missing secret as well as a bad signature, because the old
+ # verifier could not tell the caller apart from the operator. Inherited rather than chosen.
+ unconfigured_status = 401
+ # A dropped secret makes every marketplace invoice answer 401, and the 401 above hides that
+ # from anyone reading status codes, so it has to reach error tracking as the old view made it.
+ reports_unconfigured = True
+ # A delivery no consumer accepted answers 500, which is what this endpoint answered before.
+ # Vercel publishes no retry policy, so whether that buys a redelivery is unknown; the status is
+ # right either way, because the work did not run.
+ retry_status = 500
+ # The owning region waits up to 30 s for the billing service (`BillingManager
+ # .handle_billing_provider_webhook`), so a shorter deadline here would make the receiving
+ # region abandon an invoice the other region is still processing.
+ forward_timeout_seconds = 35.0
+
+ def __init__(self) -> None:
+ self._scheme = HmacSignature(
+ secret_getter=_vercel_secret,
+ signature_header=VERCEL_SIGNATURE_HEADER,
+ digest="sha1",
+ )
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def receiving_region_domain(self) -> str:
+ # The marketplace App holds one webhook URL, on the secondary region, so deliveries arrive
+ # there and the ones the primary region owns are forwarded on. A request that arrives on
+ # any other host is reported as `ingress_delivery_host_matches_no_region`.
+ return regions.SECONDARY_REGION_DOMAIN
+
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping):
+ return ()
+ in_receiving_region = request.get_host() == self.receiving_region_domain()
+ # The whole body travels, not its `payload` field: the consumer needs the exact event
+ # name the prefix above collapsed, and that lives on the envelope.
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ # Vercel does send one, as the body's `id`. It is left unused because turning
+ # dedup on changes which redeliveries reach the consumer, and that belongs in its
+ # own change rather than in a transport swap. Dedup stays the consumer's own job.
+ delivery_id=None,
+ event_type=delivery_event_type(str(payload.get("type", ""))),
+ payload=payload,
+ received_at=timezone.now(),
+ context={RECEIVING_REGION_CONTEXT_KEY: "true" if in_receiving_region else "false"},
+ ),
+ )
+
+
+def build_vercel_provider() -> VercelProvider:
+ return VercelProvider()