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.

fix(vercel): let whole-installation transfers complete (#118063)

Matt Brooker0b84bb24d9a1
diff --git a/docs/published/handbook/engineering/vercel-integration.md b/docs/published/handbook/engineering/vercel-integration.md
index 647e7896d624..c8a75c501fe6 100644
--- a/docs/published/handbook/engineering/vercel-integration.md
+++ b/docs/published/handbook/engineering/vercel-integration.md
@@ -128,6 +128,16 @@ sequenceDiagram
**Note:** Connectable installs do NOT call the billing service. The customer keeps their existing PostHog billing. On uninstall, the `OrganizationIntegration` record is simply deleted with no billing side effects.
+### C. Transfer to another Vercel team
+
+A Vercel user can move a Marketplace install, with its resources, to another Vercel team ([Vercel docs](https://vercel.com/docs/integrations/install-an-integration/transferring-an-integration)). The installation ID, its access token, the PostHog organization and its billing stay the same. Vercel enables transfers per integration, so ask in [#posthog-vercel](https://posthog.slack.com/archives/C08LYBQ58N5) before relying on them.
+
+- Vercel calls `GET /v1/installations/{id}/resources/{resourceId}/plans` during the transfer, and the transfer stalls until that call succeeds.
+- Vercel does not call the installation endpoint. The `integration-configuration.transferred` webhook refreshes `config.account` (team name, dashboard URL, contact) from Vercel's account endpoint instead.
+- Connectable installs cannot be transferred, and the webhook handler leaves them unchanged.
+- The new team's contact becomes an Owner. If they signed in through Vercel before the webhook arrived, the webhook promotes them. If not, they become an Owner when they first sign in.
+- Members of the old team keep their PostHog access. Nothing removes them.
+
---
## 3. Billing & subscriptions
diff --git a/ee/api/vercel/test/test_vercel_resource.py b/ee/api/vercel/test/test_vercel_resource.py
index ad096ebc95c2..c025e461dba4 100644
--- a/ee/api/vercel/test/test_vercel_resource.py
+++ b/ee/api/vercel/test/test_vercel_resource.py
@@ -318,3 +318,23 @@ class TestVercelResourceAPI(VercelTestBase):
response = self.client.post(url, **headers)
self.assert_not_found(response)
+
+ @parameterized.expand([("a_resource_posthog_holds", None), ("a_resource_whose_project_was_deleted", "99999")])
+ def test_resource_plans_list_the_billing_plans(self, _name, resource_id):
+ resource_id = resource_id or self.primary_resource["resource_id"]
+ url = f"{self.primary_resource['base_url']}/{resource_id}/plans/"
+ headers = self.auth_headers(self.installation_id, "system")
+
+ response = self.client.get(url, **headers)
+
+ self.assert_success(response)
+ self.assertEqual([plan["id"] for plan in response.json()["plans"]], ["posthog-usage-based"])
+
+ def test_resource_plans_reject_a_token_for_another_installation(self):
+ other_installation = self.create_installation()
+ url = f"{self.primary_resource['resource_url']}plans/"
+ headers = self.auth_headers(other_installation["id"], "system")
+
+ response = self.client.get(url, **headers)
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
diff --git a/ee/api/vercel/test/test_vercel_webhooks.py b/ee/api/vercel/test/test_vercel_webhooks.py
index 560cb65f4072..5d66d5438e55 100644
--- a/ee/api/vercel/test/test_vercel_webhooks.py
+++ b/ee/api/vercel/test/test_vercel_webhooks.py
@@ -7,9 +7,11 @@ from unittest.mock import MagicMock, patch
from django.db import OperationalError
from django.test import override_settings
-from requests import RequestException
+from parameterized import parameterized
+from requests import HTTPError, RequestException
from posthog.ingress.dispatch.loading import reset_consumer_registry
+from posthog.models.organization import OrganizationMembership
from posthog.models.organization_integration import OrganizationIntegration
from ee.api.vercel.test.base import VercelTestBase
@@ -58,6 +60,17 @@ class TestVercelWebhooks(VercelTestBase):
def _deauthorization_payload(self, installation_id: str) -> dict:
return {"type": "integration-configuration.removed", "payload": {"installationId": installation_id}}
+ def _transfer_payload(self, installation_id: str) -> dict:
+ return {
+ "type": "integration-configuration.transferred",
+ "payload": {
+ "installationId": installation_id,
+ "configuration": {"id": installation_id},
+ "previousTeamId": "team_old",
+ "newTeamId": "team_new",
+ },
+ }
+
def test_an_invalid_signature_is_refused(self):
response = self._post(self._billing_payload(self.installation_id), signature="invalid_signature")
@@ -126,6 +139,113 @@ class TestVercelWebhooks(VercelTestBase):
self.assertEqual(response.status_code, 202)
self.assertFalse(OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists())
+ @parameterized.expand(
+ [
+ (
+ "vercel_returns_a_contact",
+ {"email": "[email protected]", "name": "Old owner"},
+ {"email": "[email protected]", "name": "New owner"},
+ {"email": "[email protected]", "name": "New owner"},
+ OrganizationMembership.Level.OWNER,
+ ),
+ (
+ "vercel_returns_no_contact",
+ {"email": "[email protected]", "name": "Old owner"},
+ None,
+ {"email": "[email protected]", "name": "Old owner"},
+ OrganizationMembership.Level.MEMBER,
+ ),
+ ("no_contact_anywhere", None, None, None, OrganizationMembership.Level.MEMBER),
+ ]
+ )
+ @patch("ee.vercel.client.requests.Session.request", autospec=True)
+ def test_a_transfer_stores_the_new_team_from_vercel(
+ self,
+ _name: str,
+ stored_contact: dict[str, str] | None,
+ live_contact: dict[str, str] | None,
+ expected_contact: dict[str, str] | None,
+ expected_new_owner_level: OrganizationMembership.Level,
+ vercel_request: MagicMock,
+ ) -> None:
+ old_account: dict = {"url": "https://vercel.com/old-team/~/integrations/posthog/icfg_old", "name": "Old team"}
+ if stored_contact:
+ old_account["contact"] = stored_contact
+ self.installation.config = {
+ "billing_plan_id": "free",
+ "user_mappings": {"vercel_user_1": self.user.pk},
+ "account": old_account,
+ }
+ self.installation.sensitive_config = {"credentials": {"access_token": "test_token", "token_type": "Bearer"}}
+ self.installation.save()
+ new_owner = self._create_user("[email protected]")
+ both_mappings = {"vercel_user_1": self.user.pk, "vercel_user_2": new_owner.pk}
+
+ def answer_while_sso_maps_another_user(session, method, url, **kwargs):
+ OrganizationIntegration.objects.filter(pk=self.installation.pk).update(
+ config={**self.installation.config, "user_mappings": both_mappings}
+ )
+ vercel_response = MagicMock(status_code=200)
+ vercel_response.json.return_value = {
+ "url": "https://vercel.com/new-team/~/integrations/posthog/icfg_old",
+ "name": "New team",
+ "contact": live_contact,
+ }
+ return vercel_response
+
+ vercel_request.side_effect = answer_while_sso_maps_another_user
+
+ response = self._post(self._transfer_payload(self.installation_id))
+
+ self.assertEqual(response.status_code, 202)
+ session, method, url = vercel_request.call_args.args
+ self.assertEqual(
+ (method, url), ("GET", f"https://api.vercel.com/v1/installations/{self.installation_id}/account")
+ )
+ self.assertEqual(session.headers["Authorization"], "Bearer test_token")
+ expected_account: dict = {
+ "url": "https://vercel.com/new-team/~/integrations/posthog/icfg_old",
+ "name": "New team",
+ }
+ if expected_contact:
+ expected_account["contact"] = expected_contact
+ self.installation.refresh_from_db()
+ self.assertEqual(
+ self.installation.config,
+ {"billing_plan_id": "free", "user_mappings": both_mappings, "account": expected_account},
+ )
+ self.assertEqual(
+ dict(self.organization.memberships.values_list("user_id", "level")),
+ {self.user.pk: OrganizationMembership.Level.ADMIN, new_owner.pk: expected_new_owner_level},
+ )
+
+ @patch("ee.vercel.client.requests.Session.request")
+ def test_a_transfer_of_a_linked_account_changes_nothing(self, vercel_request):
+ self.installation.config["type"] = "connectable"
+ self.installation.save()
+ config_before = dict(self.installation.config)
+
+ response = self._post(self._transfer_payload(self.installation_id))
+
+ self.assertEqual(response.status_code, 202)
+ vercel_request.assert_not_called()
+ self.installation.refresh_from_db()
+ self.assertEqual(self.installation.config, config_before)
+
+ @patch("ee.vercel.client.requests.Session.request")
+ def test_a_transfer_whose_account_lookup_fails_is_not_receipted(self, vercel_request):
+ vercel_response = MagicMock(status_code=500, text="upstream error")
+ vercel_response.raise_for_status.side_effect = HTTPError(response=vercel_response)
+ vercel_request.return_value = vercel_response
+ config_before = dict(self.installation.config)
+
+ response = self._post(self._transfer_payload(self.installation_id))
+
+ self.assertEqual(response.status_code, 500)
+ vercel_request.assert_called_once()
+ self.installation.refresh_from_db()
+ self.assertEqual(self.installation.config, config_before)
+
@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]:
diff --git a/ee/api/vercel/vercel_resource.py b/ee/api/vercel/vercel_resource.py
index 08005e43273a..efb1efaaed28 100644
--- a/ee/api/vercel/vercel_resource.py
+++ b/ee/api/vercel/vercel_resource.py
@@ -168,6 +168,7 @@ class VercelResourceViewSet(VercelRegionProxyMixin, VercelErrorResponseMixin, vi
"destroy": ["user", "system"],
"retrieve": ["system"],
"rotate_secrets": ["system"],
+ "resource_plans": ["system"],
}
def _validate_resource_access(self, resource_id: str, installation_id: str) -> None:
@@ -230,6 +231,20 @@ class VercelResourceViewSet(VercelRegionProxyMixin, VercelErrorResponseMixin, vi
VercelIntegration.delete_resource(resource_id)
return Response(status=204)
+ @action(detail=True, methods=["GET"], url_path="plans")
+ def resource_plans(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """
+ https://vercel.com/docs/integrations/create-integration/marketplace-api/reference/partner/list-billing-plans-for-resource
+
+ The plans are the same for every resource, so the resource is not looked up.
+ The action is not named `plans`, because `VercelPermission` exempts actions with that name
+ from binding the token to the installation in the URL.
+ """
+ validate_resource_id(self.kwargs.get("resource_id"))
+ validate_installation_id(self.kwargs.get("parent_lookup_installation_id"))
+
+ return Response({"plans": VercelIntegration.get_vercel_plans()})
+
@action(detail=True, methods=["POST"], url_path="secrets/rotate")
def rotate_secrets(self, request: Request, *args: Any, **kwargs: Any) -> Response:
"""
diff --git a/ee/api/vercel/webhook_consumers.py b/ee/api/vercel/webhook_consumers.py
index 398c31a50174..f38c36ab5a94 100644
--- a/ee/api/vercel/webhook_consumers.py
+++ b/ee/api/vercel/webhook_consumers.py
@@ -42,9 +42,9 @@ def _run_vercel_event(delivery: WebhookDelivery) -> None:
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.
+ Every event type asks, because each is processed by the region that holds the installation:
+ only there does `BillingManager` find the `Organization` a billing call needs, only there is
+ there an installation to delete, and only there is the access token a transfer refresh needs.
"""
from ee.api.vercel.webhook_events import extract_config_id, installation_is_local # noqa: PLC0415 - as above
diff --git a/ee/api/vercel/webhook_events.py b/ee/api/vercel/webhook_events.py
index cfb26a601aef..e9ad73c6ea76 100644
--- a/ee/api/vercel/webhook_events.py
+++ b/ee/api/vercel/webhook_events.py
@@ -22,6 +22,7 @@ logger = structlog.get_logger(__name__)
BILLING_EVENT_PREFIX = "marketplace.invoice."
DEAUTHORIZATION_EVENT = "integration-configuration.removed"
+TRANSFER_EVENT = "integration-configuration.transferred"
# 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
@@ -58,6 +59,10 @@ def is_deauthorization_event(event_type: str | None) -> bool:
return event_type == DEAUTHORIZATION_EVENT
+def is_transfer_event(event_type: str | None) -> bool:
+ return event_type == TRANSFER_EVENT
+
+
def _get_integration(config_id: str) -> OrganizationIntegration | None:
try:
with bounded_statement_timeout(OWNERSHIP_LOOKUP_TIMEOUT_MS, models=[OrganizationIntegration]):
@@ -140,6 +145,29 @@ def _handle_deauthorization(config_id: str, in_receiving_region: bool) -> Vercel
return VercelEventOutcome.ACCEPTED
+def _handle_transfer(config_id: str, in_receiving_region: bool) -> VercelEventOutcome:
+ integration = _get_integration(config_id)
+ if not integration:
+ _log_unknown_config("vercel_webhook_transfer_unknown_config", config_id, TRANSFER_EVENT, in_receiving_region)
+ return VercelEventOutcome.UNKNOWN_CONFIG
+
+ # A linked account is billed through PostHog. Vercel account details stored on it would point
+ # its billing page at Vercel invoices and change who gets Owner on login.
+ if integration.config.get("type") == "connectable":
+ logger.info("vercel_webhook_transfer_connectable_ignored", config_id=config_id)
+ return VercelEventOutcome.ACCEPTED
+
+ try:
+ VercelIntegration.refresh_installation_account(integration)
+ except Exception as e:
+ logger.exception("vercel_webhook_transfer_refresh_failed", config_id=config_id)
+ capture_exception(e, {"config_id": config_id})
+ raise VercelEventProcessingError(str(e)) from e
+
+ logger.info("vercel_webhook_transferred", config_id=config_id, org_id=str(integration.organization_id))
+ return VercelEventOutcome.ACCEPTED
+
+
def _handle_billing(
event_type: str,
payload: dict[str, Any],
@@ -182,6 +210,12 @@ def handle_vercel_event(
return VercelEventOutcome.MISSING_CONFIG_ID
return _handle_deauthorization(config_id, in_receiving_region)
+ if is_transfer_event(event_type):
+ if not config_id:
+ logger.error("vercel_webhook_transfer_missing_config_id")
+ return VercelEventOutcome.MISSING_CONFIG_ID
+ return _handle_transfer(config_id, in_receiving_region)
+
if not is_billing_event(event_type):
logger.info("vercel_webhook_non_billing_event", event_type=event_type)
return VercelEventOutcome.IGNORED
diff --git a/ee/vercel/client.py b/ee/vercel/client.py
index 1a2d6f61d28c..7973ac2a8723 100644
--- a/ee/vercel/client.py
+++ b/ee/vercel/client.py
@@ -319,6 +319,10 @@ class VercelAPIClient:
error_description=str(e),
)
+ def get_installation_account(self, installation_id: str) -> dict[str, Any]:
+ response = self._request("GET", f"{self.base_url}/installations/{installation_id}/account")
+ return self._parse_json_response(response)
+
def check_installation_active(self, installation_id: str) -> bool:
"""Check if a Vercel installation is still active.
diff --git a/ee/vercel/integration.py b/ee/vercel/integration.py
index 38606f050d88..20f42ec11aff 100644
--- a/ee/vercel/integration.py
+++ b/ee/vercel/integration.py
@@ -480,6 +480,46 @@ class VercelIntegration:
)
return {"finalized": True}
+ @staticmethod
+ def _promote_mapped_contact_to_owner(installation: OrganizationIntegration, contact_email: str) -> None:
+ mapped_users = User.objects.filter(pk__in=list(installation.config.get("user_mappings", {}).values()))
+ memberships = OrganizationMembership.objects.filter(
+ organization_id=installation.organization_id,
+ user__in=EmailLookupHandler.users_matching_email(contact_email, mapped_users),
+ level__lt=OrganizationMembership.Level.OWNER,
+ )
+ for membership in memberships:
+ membership.level = OrganizationMembership.Level.OWNER
+ membership.save(update_fields=["level"])
+
+ @staticmethod
+ def refresh_installation_account(installation: OrganizationIntegration) -> None:
+ installation_id = installation.integration_id
+ access_token = VercelIntegration._get_access_token(installation)
+ if not installation_id or not access_token:
+ raise RuntimeError("Vercel installation has no installation ID or access token")
+
+ # A transfer webhook runs this inside its delivery. The short timeout keeps it well inside the
+ # ingress delivery budget (`DEFAULT_DELIVERY_BUDGET_SECONDS`), which also covers the forward
+ # to the region that holds the installation.
+ account = VercelAPIClient(bearer_token=access_token, timeout=5).get_installation_account(installation_id)
+
+ # SSO saves user mappings under a lock on this row. Take the same lock, so that a mapping
+ # saved while the request to Vercel was in flight is not overwritten.
+ with transaction.atomic():
+ locked = OrganizationIntegration.objects.select_for_update().get(pk=installation.pk)
+ live_contact = account.get("contact")
+ contact = live_contact or locked.config.get("account", {}).get("contact")
+ refreshed: dict[str, Any] = {"url": account["url"], "name": account.get("name")}
+ # The Owner check at SSO reads the contact with `.get`, which a stored None breaks.
+ if contact:
+ refreshed["contact"] = {"email": contact["email"], "name": contact.get("name")}
+ locked.config["account"] = refreshed
+ locked.save(update_fields=["config", "updated_at"])
+ if live_contact:
+ VercelIntegration._promote_mapped_contact_to_owner(locked, live_contact["email"])
+ logger.info("Refreshed Vercel installation account", installation_id=installation_id, integration="vercel")
+
@staticmethod
def get_product_plans(product_slug: str) -> dict[str, Any]:
if product_slug != "posthog":
diff --git a/posthog/ingress/vercel/README.md b/posthog/ingress/vercel/README.md
index 2ad032e92905..d86189e92f42 100644
--- a/posthog/ingress/vercel/README.md
+++ b/posthog/ingress/vercel/README.md
@@ -1,6 +1,6 @@
# Vercel
-Deliveries from the Vercel Marketplace integration: invoice lifecycle events and the deauthorization event.
+Deliveries from the Vercel Marketplace integration: invoice lifecycle events, the deauthorization event and the transfer event.
## Headers
@@ -26,7 +26,7 @@ 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.
+`integration-configuration.removed` and `integration-configuration.transferred` are passed through unchanged.
## Apps and secrets
@@ -38,7 +38,7 @@ The secret is the Django setting `VERCEL_CLIENT_INTEGRATION_SECRET`.
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.
+Every event type declares ownership, because each is processed by the region that holds the installation: only there does the billing manager find the `Organization` a billing call needs, only there is there an installation to delete, and only there is the access token a transfer refresh calls Vercel with.
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.
@@ -46,12 +46,12 @@ Both are what the endpoint answered before this moved onto ingress, and Vercel's
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.
+Vercel redelivers an event that gets a non-2xx answer for up to 24 hours with exponential backoff, then discards it ([webhooks API](https://vercel.com/docs/webhooks/webhooks-api#delivery-attempts-and-retries)).
+The status is also right 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 miss is still reported: the primary region, which looks last, logs `vercel_webhook_unknown_config`, `vercel_webhook_deauthorize_unknown_config` or `vercel_webhook_transfer_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
@@ -61,3 +61,4 @@ 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.
+A transfer goes to `VercelIntegration.refresh_installation_account`, which reads the installation's new team from Vercel's account endpoint and stores it, because Vercel does not call the installation endpoint during a transfer.
diff --git a/posthog/ingress/vercel/provider.py b/posthog/ingress/vercel/provider.py
index 6357acf2f70c..20afc14c5c7a 100644
--- a/posthog/ingress/vercel/provider.py
+++ b/posthog/ingress/vercel/provider.py
@@ -22,7 +22,8 @@ from posthog.ingress.verify.schemes import HmacSignature, SignatureScheme
# 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_TRANSFER_EVENT = "integration-configuration.transferred"
+VERCEL_EVENT_TYPES = frozenset({VERCEL_BILLING_EVENT, VERCEL_DEAUTHORIZATION_EVENT, VERCEL_TRANSFER_EVENT})
VERCEL_SIGNATURE_HEADER = "x-vercel-signature"