:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(vercel): keep the popup open through social login and fail dead links (#96904)
Matt Brooker3a1cf5335bdc
diff --git a/ee/api/vercel/test/test_vercel_connect.py b/ee/api/vercel/test/test_vercel_connect.pyindex de397a846f11..4385ae63bce4 100644--- a/ee/api/vercel/test/test_vercel_connect.py+++ b/ee/api/vercel/test/test_vercel_connect.py@@ -13,7 +13,12 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_integration import OrganizationIntegrationfrom posthog.models.team import Team-from ee.api.vercel.vercel_connect import _load_connect_session, _sign_connect_session, _validate_next_url+from ee.api.vercel.vercel_connect import (+ _delete_orphaned_integration,+ _load_connect_session,+ _sign_connect_session,+ _validate_next_url,+)from ee.vercel.client import OAuthTokenResponse, OperationResult# Hardcoded independently of ee.vercel.integration.CLIENT_ENV_PREFIXES so a dropped prefix fails these tests.@@ -200,6 +205,12 @@ class TestVercelConnectSessionInfo(VercelConnectTestBase):config={"credentials": {"access_token": "tok_dead"}},created_by=self.user,)+ Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.VERCEL,+ integration_id=str(self.team.pk),+ config={"type": "connectable"},+ )session_token = _seed_session()response = self.client.get(self.url, {"session": session_token})@@ -207,6 +218,7 @@ class TestVercelConnectSessionInfo(VercelConnectTestBase):assert response.status_code == status.HTTP_200_OKassert response.json()["organizations"][0]["already_linked"] is Falseassert not OrganizationIntegration.objects.filter(integration_id="icfg_orphaned").exists()+ assert not Integration.objects.filter(team=self.team, kind=Integration.IntegrationKind.VERCEL).exists()def test_excludes_orgs_where_user_is_member_not_admin(self):other_org = Organization.objects.create(name="Other Org")@@ -475,6 +487,12 @@ class TestVercelConnectComplete(VercelConnectTestBase):config={"credentials": {"access_token": "tok_stale"}},created_by=self.user,)+ stale_resource = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.VERCEL,+ integration_id=str(self.team.pk),+ config={"type": "connectable"},+ )session_token = _seed_session()response = self.client.post(@@ -495,6 +513,8 @@ class TestVercelConnectComplete(VercelConnectTestBase):kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,)assert new_integration.integration_id == "icfg_connect_test"+ assert not Integration.objects.filter(pk=stale_resource.pk).exists()+ assert Integration.objects.filter(team=self.team, kind=Integration.IntegrationKind.VERCEL).exists()def test_unauthenticated_returns_403(self):self.client.logout()@@ -587,6 +607,44 @@ class TestVercelConnectComplete(VercelConnectTestBase):kind=Integration.IntegrationKind.VERCEL,).exists()+ @parameterized.expand(+ [+ ("with_status", OperationResult(success=False, error="HTTP error", status_code=403), "HTTP 403"),+ ("without_status", OperationResult(success=False, error="Network error"), "Network error"),+ ]+ )+ @patch("ee.vercel.integration.VercelIntegration")+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")+ def test_failed_import_rolls_back_and_returns_400(+ self, _name, import_result, expected_detail, mock_client_class, mock_vercel_integration+ ):+ mock_client = MagicMock()+ mock_client_class.return_value = mock_client+ mock_client.import_resource.return_value = import_result+ session_token = _seed_session()++ response = self.client.post(+ self.url,+ {+ "session": session_token,+ "organization_id": str(self.organization.id),+ "environment_mapping": {"production": self.team.pk},+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert expected_detail in response.json()["detail"]+ assert not OrganizationIntegration.objects.filter(+ organization=self.organization,+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,+ ).exists()+ assert not Integration.objects.filter(+ team=self.team,+ kind=Integration.IntegrationKind.VERCEL,+ ).exists()+ mock_vercel_integration.bulk_sync_feature_flags_to_vercel.assert_not_called()+@override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")class TestVercelConnectEndToEnd(VercelConnectTestBase):@@ -816,6 +874,57 @@ class TestBackfillVercelConnectableResources(VercelConnectTestBase):mock_vercel_integration.bulk_sync_feature_flags_to_vercel.assert_not_called()+class TestDeleteOrphanedIntegration(VercelConnectTestBase):+ @parameterized.expand(+ [+ ("distinct_teams", ["own"], ["other"], {"other"}),+ ("shared_team", ["own"], ["own"], {"own"}),+ ("unmapped_orphan", None, ["other"], {"other"}),+ ("unmapped_sibling", ["own"], None, {"own", "other"}),+ ]+ )+ def test_keeps_only_resources_another_installation_claims(+ self, _name, orphan_teams, sibling_teams, surviving_teams+ ):+ teams = {"own": self.team, "other": Team.objects.create(organization=self.organization, name="Other project")}++ def config(team_keys: list[str] | None) -> dict:+ if team_keys is None:+ return {"type": "connectable"}+ return {"type": "connectable", "environment_mapping": {"production": teams[team_keys[0]].pk}}++ orphaned = OrganizationIntegration.objects.create(+ organization=self.organization,+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,+ integration_id="icfg_orphaned",+ config=config(orphan_teams),+ )+ OrganizationIntegration.objects.create(+ organization=self.organization,+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,+ integration_id="icfg_live",+ config=config(sibling_teams),+ )+ for team in teams.values():+ Integration.objects.create(+ team=team,+ kind=Integration.IntegrationKind.VERCEL,+ integration_id=str(team.pk),+ config={"type": "connectable"},+ )++ _delete_orphaned_integration(orphaned)++ assert not OrganizationIntegration.objects.filter(pk=orphaned.pk).exists()+ assert OrganizationIntegration.objects.filter(integration_id="icfg_live").exists()+ surviving_team_ids = set(+ Integration.objects.filter(+ team__organization=self.organization, kind=Integration.IntegrationKind.VERCEL+ ).values_list("team_id", flat=True)+ )+ assert surviving_team_ids == {teams[key].pk for key in surviving_teams}++class TestValidateNextUrl(TestCase):@parameterized.expand([diff --git a/ee/api/vercel/vercel_connect.py b/ee/api/vercel/vercel_connect.pyindex cc0a9cbf73fc..f482db01dcae 100644--- a/ee/api/vercel/vercel_connect.py+++ b/ee/api/vercel/vercel_connect.py@@ -1,9 +1,10 @@from typing import castfrom urllib.parse import quote, urlencode, urlparse+from uuid import UUIDfrom django.conf import settingsfrom django.core import signing-from django.db import transaction+from django.db import connection, transactionfrom django.http import HttpResponse, HttpResponseRedirectimport structlog@@ -85,6 +86,48 @@ def _is_installation_orphaned(integration: OrganizationIntegration) -> bool:return False+def _lock_vercel_links(organization_id: UUID) -> None:+ # Serializes orphan cleanup with link creation for one organization. The lock is transaction-scoped,+ # so call it inside `transaction.atomic()` and never around the Vercel network call.+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"vercel-connect:{organization_id}"])+++def _mapped_team_ids(integration: OrganizationIntegration) -> set[int] | None:+ mapping = integration.config.get("environment_mapping")+ if not mapping:+ return None+ return {team_id for team_id in mapping.values() if isinstance(team_id, int)}+++def _delete_orphaned_integration(integration: OrganizationIntegration) -> None:+ with transaction.atomic():+ _lock_vercel_links(integration.organization_id)+ if not OrganizationIntegration.objects.filter(pk=integration.pk).exists():+ return++ # A resource records its team, not its installation, so a resource is safe to delete only when no+ # other installation claims its team. A resource left behind blocks the next link attempt, because+ # `complete` rejects a team that still has one.+ claimed_team_ids: set[int] = set()+ for sibling in OrganizationIntegration.objects.filter(+ organization_id=integration.organization_id,+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,+ ).exclude(pk=integration.pk):+ sibling_team_ids = _mapped_team_ids(sibling)+ if sibling_team_ids is None:+ # A sibling without a mapping may own any team, so no resource is safe to delete.+ integration.delete()+ return+ claimed_team_ids |= sibling_team_ids++ Integration.objects.filter(+ team__organization_id=integration.organization_id,+ kind=Integration.IntegrationKind.VERCEL,+ ).exclude(team_id__in=claimed_team_ids).delete()+ integration.delete()++class VercelConnectCallbackViewSet(viewsets.GenericViewSet):"""Handles the Vercel connectable account (Link Existing Account) flow.@@ -219,7 +262,7 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):organization_id=str(organization_id),integration="vercel",)- existing.delete()+ _delete_orphaned_integration(existing)else:raise exceptions.ValidationError("This organization already has a Vercel integration. "@@ -241,7 +284,8 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):production_team = teams_by_id[production_team_id]with transaction.atomic():- OrganizationIntegration.objects.create(+ _lock_vercel_links(organization.id)+ org_integration = OrganizationIntegration.objects.create(organization=organization,kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,integration_id=installation_id,@@ -295,10 +339,23 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):logger.error("Failed to import resource to Vercel",error=import_result.error,+ status_code=import_result.status_code,+ error_detail=import_result.error_detail,installation_id=installation_id,resource_id=str(production_resource.pk),integration="vercel",)+ with transaction.atomic():+ org_integration.delete()+ for resource in resources.values():+ resource.delete()+ if import_result.status_code is not None:+ raise exceptions.ValidationError(+ f"Vercel rejected the link (HTTP {import_result.status_code}). Start the link again from Vercel."+ )+ raise exceptions.ValidationError(+ f"Vercel did not accept the link ({import_result.error}). Start the link again from Vercel."+ )VercelIntegration.bulk_sync_feature_flags_to_vercel(production_team)@@ -395,7 +452,7 @@ class VercelConnectLinkViewSet(viewsets.GenericViewSet):organization_id=str(org_id),integration="vercel",)- integration.delete()+ _delete_orphaned_integration(integration)orphaned_org_ids.add(org_id)teams_by_org: dict = {}diff --git a/ee/vercel/client.py b/ee/vercel/client.pyindex 4ff534047a0d..f1a5680adda9 100644--- a/ee/vercel/client.py+++ b/ee/vercel/client.py@@ -121,8 +121,8 @@ class VercelAPIClient:logger.exception("Request timeout", method=method, url=url, integration="vercel")raise APIError("Request timed out", detail=str(e))except HTTPError as e:- status_code = e.response.status_code if e.response else None- detail = e.response.text if e.response else str(e)+ status_code = e.response.status_code if e.response is not None else None+ detail = e.response.text if e.response is not None else str(e)logger.exception("HTTP error", method=method, url=url, status_code=status_code, integration="vercel")raise APIError("HTTP error", status_code=status_code, detail=detail)except RequestException as e:diff --git a/ee/vercel/integration.py b/ee/vercel/integration.pyindex be712c9adaa8..7994354e065b 100644--- a/ee/vercel/integration.py+++ b/ee/vercel/integration.py@@ -114,6 +114,10 @@ class InstallationConfig:account: InstallationAccount+class VercelSecretPushError(Exception):+ pass++@dataclassclass VercelSetupResult:client: VercelAPIClient@@ -1246,31 +1250,39 @@ class VercelIntegration:secrets = VercelIntegration._build_secrets(team)+ log_context = {+ "team_id": team.id,+ "integration_config_id": setup_result.integration_config_id,+ "resource_id": setup_result.resource_id,+ "integration": "vercel",+ }try:result = setup_result.client.update_resource_secrets(integration_config_id=setup_result.integration_config_id,resource_id=setup_result.resource_id,secrets=secrets,)- if not result.success:- raise Exception(f"Failed to push secrets to Vercel: {result.error}")-- logger.info(- "Pushed secrets to Vercel",- team_id=team.id,- integration_config_id=setup_result.integration_config_id,- resource_id=setup_result.resource_id,- integration="vercel",- )except Exception as e:- logger.exception(- "Error pushing secrets to Vercel",- team_id=team.id,- integration_config_id=setup_result.integration_config_id,- resource_id=setup_result.resource_id,- integration="vercel",- )+ logger.exception("Error pushing secrets to Vercel", **log_context)capture_exception(e, {"team_id": team.id, "resource_id": setup_result.resource_id})+ return++ if result.success:+ logger.info("Pushed secrets to Vercel", **log_context)+ return++ logger.error(+ "Error pushing secrets to Vercel", status_code=result.status_code, error=result.error, **log_context+ )+ capture_exception(+ VercelSecretPushError(f"Failed to push secrets to Vercel: {result.error} (status: {result.status_code})"),+ {+ "team_id": team.id,+ "resource_id": setup_result.resource_id,+ "status_code": result.status_code,+ "error_detail": result.error_detail,+ },+ )def _safe_vercel_sync(diff --git a/ee/vercel/test/test_integration.py b/ee/vercel/test/test_integration.pyindex 598d9e7b4472..251da98a02e2 100644--- a/ee/vercel/test/test_integration.py+++ b/ee/vercel/test/test_integration.py@@ -1413,12 +1413,18 @@ class TestPushSecretsToVercel(TestCase):@patch("ee.vercel.integration.VercelAPIClient")def test_push_secrets_handles_api_error_gracefully(self, mock_client_class, mock_capture):mock_client = Mock()- mock_client.update_resource_secrets.return_value = Mock(success=False, error="API error")+ mock_client.update_resource_secrets.return_value = Mock(+ success=False, error="HTTP error", status_code=403, error_detail="Forbidden"+ )mock_client_class.return_value = mock_clientVercelIntegration.push_secrets_to_vercel(self.team)mock_capture.assert_called_once()+ exception, properties = mock_capture.call_args[0]+ assert "403" in str(exception)+ assert properties["status_code"] == 403+ assert properties["resource_id"] == str(self.resource.pk)@patch("ee.vercel.integration.capture_exception")@patch("ee.vercel.integration.VercelAPIClient")diff --git a/ee/vercel/test/test_vercel_client.py b/ee/vercel/test/test_vercel_client.pyindex c744829e1fc7..7cc1c14c8a98 100644--- a/ee/vercel/test/test_vercel_client.py+++ b/ee/vercel/test/test_vercel_client.py@@ -33,6 +33,15 @@ class TestVercelAPIClient:mock_response.json.side_effect = json.JSONDecodeError("Invalid JSON", "", 0)return mock_response+ @staticmethod+ def real_response(status_code: int, text: str) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response.reason = text+ response._content = text.encode()+ response.url = "https://api.vercel.com/v1/test"+ return response+@pytest.fixturedef client(self):return VercelAPIClient("test_token")@@ -149,6 +158,24 @@ class TestVercelAPIClient:assert result.error == "HTTP error"assert result.status_code == 400+ @patch("ee.vercel.client.requests.Session.request")+ def test_http_error_status_code_survives_falsy_response(self, mock_request, client, test_ids):+ mock_request.return_value = self.real_response(403, "Forbidden")++ result = client.update_resource_secrets(+ test_ids["integration_config_id"], test_ids["resource_id"], [{"name": "A", "value": "b"}]+ )++ assert not result.success+ assert result.status_code == 403+ assert result.error_detail == "Forbidden"++ @patch("ee.vercel.client.requests.Session.request")+ def test_check_installation_active_false_on_real_404(self, mock_request, client):+ mock_request.return_value = self.real_response(404, "Not Found")++ assert client.check_installation_active("icfg_x") is False+@pytest.mark.parametrize("method_name,args_func,error_setup,expected_error,expected_status",[diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 672b0a836f7a..ff343d25ae39 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -35,6 +35,7 @@ from django_prometheus.middleware import Metricsfrom loginas.utils import is_impersonated_session, restore_original_loginfrom opentelemetry import tracefrom prometheus_client import Counter, Histogram+from social_core.backends.utils import load_backendsfrom social_core.exceptions import AuthCanceled, AuthException, AuthFailedfrom statshog.defaults.django import statsd@@ -1206,8 +1207,8 @@ class OAuthCoopMiddleware:window.opener when a cross-origin popup navigates to our pages — breakingpopup-based OAuth flows that rely on the opener reference to detect completion.- We set COOP to "unsafe-none" on all OAuth-related paths so the opener- reference is preserved.+ We set COOP to "unsafe-none" on OAuth paths, and on the social-auth and signup+ pages that an OAuth flow passes through, so the opener reference is preserved."""OAUTH_PATH_PREFIXES = (@@ -1229,15 +1230,37 @@ class OAuthCoopMiddleware:return Truereturn False+ @staticmethod+ def _is_social_auth_path(path: str) -> bool:+ parts = path.strip("/").split("/")+ if len(parts) != 2 or parts[0] not in ("login", "complete"):+ return False+ return parts[1] in load_backends(settings.AUTHENTICATION_BACKENDS)++ def _targets_oauth_flow(self, next_url: str) -> bool:+ if not next_url:+ return False+ normalized = posixpath.normpath(next_url) if next_url.startswith("/") else next_url+ return self._matches_oauth_prefix(normalized, self.OAUTH_PATH_PREFIXES)++ def _needs_opener_reference(self, request) -> bool:+ path = request.path+ if self._matches_oauth_prefix(path, self.OAUTH_PATH_PREFIXES):+ return True+ if self._is_social_auth_path(path):+ # The provider redirects back to /complete/ without a next parameter, so read the destination+ # that social-auth stored in the session at /login/.+ session = getattr(request, "session", None)+ session_next = session.get("next", "") if session is not None else ""+ return self._targets_oauth_flow(request.GET.get("next", "")) or self._targets_oauth_flow(session_next)+ if path in ("/login", "/login/", "/signup", "/signup/"):+ return self._targets_oauth_flow(request.GET.get("next", ""))+ return False+def __call__(self, request):response = self.get_response(request)- if self._matches_oauth_prefix(request.path, self.OAUTH_PATH_PREFIXES):+ if self._needs_opener_reference(request):response["Cross-Origin-Opener-Policy"] = "unsafe-none"- elif request.path == "/login" or request.path == "/login/":- next_url = request.GET.get("next", "")- normalized = posixpath.normpath(next_url) if next_url.startswith("/") else next_url- if self._matches_oauth_prefix(normalized, self.OAUTH_PATH_PREFIXES):- response["Cross-Origin-Opener-Policy"] = "unsafe-none"return responsediff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 24cdcbec0cc9..5bce9d089c40 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -2562,16 +2562,28 @@ class TestSocialAuthExceptionMiddleware(APIBaseTest):@pytest.mark.parametrize(- "path,query_string,expected_coop",+ "path,query_string,session_next,expected_coop",[- ("/connect/vercel/link", "", "unsafe-none"),- ("/oauth/callback", "", "unsafe-none"),- ("/login", "next=/connect/vercel/link", "unsafe-none"),- ("/login", "next=/connect/vercel/link?session=abc", "unsafe-none"),- ("/login", "", "same-origin"),- ("/login", "next=/dashboard", "same-origin"),- ("/login", "next=/connect/vercel/../../admin", "same-origin"),- ("/some/other/path", "", "same-origin"),+ ("/connect/vercel/link", "", None, "unsafe-none"),+ ("/oauth/callback", "", None, "unsafe-none"),+ ("/login", "next=/connect/vercel/link", None, "unsafe-none"),+ ("/login", "next=/connect/vercel/link?session=abc", None, "unsafe-none"),+ ("/login", "", None, "same-origin"),+ ("/login", "next=/dashboard", None, "same-origin"),+ ("/login", "next=/connect/vercel/../../admin", None, "same-origin"),+ ("/some/other/path", "", None, "same-origin"),+ ("/login/google-oauth2/", "next=/connect/vercel/link", None, "unsafe-none"),+ ("/login/github/", "", None, "same-origin"),+ ("/login/github/", "next=/dashboard", None, "same-origin"),+ ("/complete/google-oauth2/", "code=x&state=y", "/connect/vercel/link", "unsafe-none"),+ ("/complete/google-oauth2/", "code=x&state=y", None, "same-origin"),+ ("/complete/google-oauth2/", "code=x&state=y", "/dashboard", "same-origin"),+ ("/signup", "next=/connect/vercel/link", None, "unsafe-none"),+ ("/signup", "", None, "same-origin"),+ ("/signup", "next=/dashboard", None, "same-origin"),+ ("/complete/github-link/", "", None, "same-origin"),+ ("/complete/slack-link/", "", None, "same-origin"),+ ("/login/not-a-backend/", "", None, "same-origin"),],ids=["direct-oauth-vercel",@@ -2582,9 +2594,22 @@ class TestSocialAuthExceptionMiddleware(APIBaseTest):"login-next-non-oauth","login-next-path-traversal","unrelated-path",+ "social-login-start-with-next",+ "social-login-start-plain",+ "social-login-start-non-oauth-next",+ "social-complete-session-oauth",+ "social-complete-no-session",+ "social-complete-session-non-oauth",+ "signup-next-oauth",+ "signup-no-next",+ "signup-next-non-oauth",+ "linking-complete-github",+ "linking-complete-slack",+ "login-unknown-backend",],)-def test_oauth_coop_middleware(path, query_string, expected_coop):+def test_oauth_coop_middleware(path, query_string, session_next, expected_coop):+ from django.contrib.sessions.backends.signed_cookies import SessionStorefrom django.http import HttpResponsefrom django.test import RequestFactory@@ -2592,6 +2617,10 @@ def test_oauth_coop_middleware(path, query_string, expected_coop):factory = RequestFactory()request = factory.get(path + ("?" + query_string if query_string else ""))+ if session_next is not None:+ session = SessionStore()+ session["next"] = session_next+ request.session = sessiondef get_response(req):resp = HttpResponse("ok")