: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
from datetime import UTC, datetime
from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
from unittest.mock import Mock, patch
from django.contrib.auth import SESSION_KEY
from django.contrib.sessions.middleware import SessionMiddleware
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.test import RequestFactory, TestCase, override_settings
from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice
from parameterized import parameterized
from rest_framework import exceptions
from rest_framework.exceptions import NotFound, ValidationError
from posthog.integrations import IntegrationConflict, IntegrationReader
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.organization_integration import OrganizationIntegration
from posthog.models.organization_provisioning import OrganizationProvisioning
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.utils import absolute_uri
from products.experiments.backend.facade.contracts import ExperimentChanged
from products.experiments.backend.facade.testing import create_experiment, delete_experiment, update_experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from ee.api.vercel.types import VercelUserClaims
from ee.vercel.integration import (
RequiresExistingUserLogin,
SSOParams,
VercelIntegration,
_safe_vercel_sync,
get_or_create_connectable_resource,
)
# Hardcoded independently of ee.vercel.integration.CLIENT_ENV_PREFIXES so a dropped prefix fails these tests.
EXPECTED_PREFIXES = ["NEXT_PUBLIC_", "VITE_", "NUXT_PUBLIC_", "PUBLIC_"]
class TestVercelIntegration(TestCase):
TEST_INSTALLATION_ID = "icfg_9bceb8ccT32d3U417ezb5c8p"
NONEXISTENT_INSTALLATION_ID = "icfg_nonexistent123456789012"
NEW_INSTALLATION_ID = "icfg_987654321abcdef123456789"
DIFFERENT_INSTALLATION_ID = "icfg_different123456789012345"
def make_team_with_vercel(self, org, user):
team = Team.objects.create(organization=org, name="Test Team")
resource = Integration.objects.create(
team=team,
kind=Integration.IntegrationKind.VERCEL,
integration_id=str(team.pk),
config={"productId": "posthog", "name": "Test Resource"},
created_by=user,
)
return team, resource
def make_feature_flag(self, team, name, description, archived):
# archived maps to the deleted field in FeatureFlag model
return FeatureFlag.objects.create(
team=team,
key=name,
name=description,
deleted=archived,
)
def assert_vercel_item(
self, item, result, category, is_archived, slug=None, expected_name=None, expected_description=None
):
assert result["id"] == f"{category}_{item.pk}"
assert result["slug"] == slug or item.name.lower().replace(" ", "-")
assert result["name"] == expected_name or getattr(item, "key", item.name)
assert result["description"] == expected_description or getattr(item, "description", item.name)
assert result["category"] == category
assert result["isArchived"] == is_archived
assert "origin" in result
assert "createdAt" in result
assert "updatedAt" in result
# Verify createdAt is in milliseconds (should be > 1 billion ms since epoch)
assert result["createdAt"] > 1_000_000_000_000, (
f"createdAt should be in milliseconds, got {result['createdAt']}"
)
assert isinstance(result["createdAt"], int), f"createdAt should be int, got {type(result['createdAt'])}"
# Verify updatedAt is in milliseconds
assert result["updatedAt"] > 1_000_000_000_000, (
f"updatedAt should be in milliseconds, got {result['updatedAt']}"
)
assert isinstance(result["updatedAt"], int), f"updatedAt should be int, got {type(result['updatedAt'])}"
def make_vercel_item(self, **overrides):
base = {
"id": "test_id",
"slug": "test-slug",
"origin": "https://example.com",
"name": "Test Item",
"category": "test",
"description": "Test Description",
"isArchived": False,
}
base.update(overrides)
return base
def setUp(self):
self.installation_id = self.TEST_INSTALLATION_ID
self.user = User.objects.create_user(email="[email protected]", password="testpass", first_name="Test")
self.organization = Organization.objects.create(name="Test Org")
self.user.join(organization=self.organization, level=OrganizationMembership.Level.OWNER)
self.installation = OrganizationIntegration.objects.create(
organization=self.organization,
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id=self.installation_id,
config={"billing_plan_id": "posthog-usage-based", "scopes": ["read"]},
created_by=self.user,
)
self.payload: dict[str, Any] = {
"scopes": ["read", "write"],
"acceptedPolicies": {"toc": "2024-02-28T10:00:00Z"},
"credentials": {"access_token": "token", "token_type": "Bearer"},
"account": {
"name": "Test Account",
"url": "https://example.com",
"contact": {"email": "[email protected]", "name": "John Doe"},
},
}
# Create mock user claims for tests
self.user_claims = self._create_user_claims("test_user_123")
def _create_user_claims(self, user_id: str) -> VercelUserClaims:
return VercelUserClaims(
iss="https://marketplace.vercel.com",
sub="account:test:user:test",
aud="test_audience",
account_id="test_account",
installation_id=self.installation_id,
user_id=user_id,
user_role="ADMIN",
type=None,
user_avatar_url=None,
user_email=self.payload["account"]["contact"]["email"],
user_name=self.payload["account"]["contact"].get("name"),
user_email_verified=True,
)
def test_get_installation_exists(self):
installation = VercelIntegration._get_installation(self.installation_id)
assert installation.integration_id == self.installation_id
assert installation.organization == self.organization
def test_get_installation_not_found(self):
with self.assertRaises(NotFound) as context:
VercelIntegration._get_installation(self.NONEXISTENT_INSTALLATION_ID)
assert str(context.exception) == "Installation not found"
def test_get_vercel_plans_structure(self):
plans = VercelIntegration.get_vercel_plans()
assert len(plans) > 0
assert plans[0]["id"]
assert plans[0]["paymentMethodRequired"] is True
def test_get_installation_billing_plan(self):
result = VercelIntegration.get_installation_billing_plan(self.installation_id)
# Returns empty dict - billing handled through PostHog, not Vercel
assert result == {}
def test_update_installation_not_found(self):
VercelIntegration.update_installation(self.NONEXISTENT_INSTALLATION_ID, "pro200")
@patch("ee.billing.billing_manager.BillingManager")
@patch("ee.vercel.integration.get_cached_instance_license")
def test_delete_installation(self, mock_license, mock_billing_manager):
mock_license.return_value = Mock()
mock_billing_manager.return_value = Mock()
result = VercelIntegration.delete_installation(self.installation_id)
assert result["finalized"]
assert not OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()
@patch("ee.vercel.integration.get_cached_instance_license")
def test_delete_installation_aborts_without_license(self, mock_license):
mock_license.return_value = None
with self.assertRaises(RuntimeError):
VercelIntegration.delete_installation(self.installation_id)
assert OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()
@patch("ee.billing.billing_manager.BillingManager")
@patch("ee.vercel.integration.get_cached_instance_license")
def test_delete_installation_calls_billing_deauthorize(self, mock_license, mock_billing_manager):
"""Deleting installation should notify billing service to cancel subscription."""
from ee.billing.billing_types import BillingProvider
mock_license.return_value = Mock()
mock_manager_instance = Mock()
mock_billing_manager.return_value = mock_manager_instance
result = VercelIntegration.delete_installation(self.installation_id)
assert result["finalized"]
mock_billing_manager.assert_called_once_with(mock_license.return_value, user=self.user)
mock_manager_instance.deauthorize.assert_called_once_with(
self.organization, billing_provider=BillingProvider.VERCEL
)
@patch("ee.billing.billing_manager.BillingManager")
@patch("ee.vercel.integration.get_cached_instance_license")
def test_delete_installation_aborts_on_billing_failure(self, mock_license, mock_billing_manager):
"""Deletion should not proceed if billing deauthorization fails, so Vercel retries the webhook."""
mock_license.return_value = Mock()
mock_manager_instance = Mock()
mock_manager_instance.deauthorize.side_effect = Exception("Billing service error")
mock_billing_manager.return_value = mock_manager_instance
with self.assertRaises(Exception) as context:
VercelIntegration.delete_installation(self.installation_id)
assert "Billing service error" in str(context.exception)
assert OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()
@patch("ee.billing.billing_manager.BillingManager")
@patch("ee.vercel.integration.get_cached_instance_license")
def test_delete_installation_blocked_by_open_invoices(self, mock_license, mock_billing_manager):
from ee.billing.billing_manager import BillingServiceOpenInvoicesError
mock_license.return_value = Mock()
mock_manager_instance = Mock()
mock_manager_instance.deauthorize.side_effect = BillingServiceOpenInvoicesError(
"Cannot uninstall billing provider: 1 unpaid invoice must be resolved first."
)
mock_billing_manager.return_value = mock_manager_instance
with self.assertRaises(BillingServiceOpenInvoicesError):
VercelIntegration.delete_installation(self.installation_id)
assert OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()
def test_delete_installation_not_found(self):
with self.assertRaises(NotFound):
VercelIntegration.delete_installation(self.NONEXISTENT_INSTALLATION_ID)
def test_get_product_plans_posthog(self):
result = VercelIntegration.get_product_plans("posthog")
assert "plans" in result
assert len(result["plans"]) == 1
assert result["plans"][0]["id"] == "posthog-usage-based"
def test_get_product_plans_invalid_product(self):
with self.assertRaises(NotFound) as context:
VercelIntegration.get_product_plans("invalid_product")
assert str(context.exception) == "Product not found"
def test_upsert_installation_existing_installation(self):
original_config = self.installation.config.copy()
VercelIntegration.upsert_installation(self.installation_id, self.payload, self.user_claims)
self.installation.refresh_from_db()
expected_config = {k: v for k, v in self.payload.items() if k != "credentials"}
assert self.installation.config == expected_config
assert self.installation.config != original_config
assert self.installation.sensitive_config["credentials"] == self.payload["credentials"]
@patch("ee.vercel.integration.report_user_signed_up")
def test_upsert_installation_new_user_new_org(self, mock_report):
new_installation_id = self.NEW_INSTALLATION_ID
new_user_claims = self._create_user_claims("new_user_456")
new_user_claims.installation_id = new_installation_id
new_user_claims.sub = "account:test:user:new"
VercelIntegration.upsert_installation(new_installation_id, self.payload, new_user_claims)
new_installation = OrganizationIntegration.objects.get(integration_id=new_installation_id)
expected_config = self.payload.copy()
expected_config["user_mappings"] = {"new_user_456": mock.ANY}
# Check that user mapping was created
assert "user_mappings" in new_installation.config
assert "new_user_456" in new_installation.config["user_mappings"]
assert new_installation.config["user_mappings"]["new_user_456"] is not None
# Check all other config fields match (credentials are in sensitive_config)
for key, value in self.payload.items():
if key == "credentials":
assert new_installation.sensitive_config["credentials"] == value
else:
assert new_installation.config[key] == value
new_user = User.objects.get(email=self.payload["account"]["contact"]["email"])
assert new_user.first_name == "John"
assert not new_user.is_email_verified
new_org = new_installation.organization
assert new_org.name == self.payload["account"]["name"]
record = OrganizationProvisioning.objects.get(organization=new_org)
assert (record.partner, record.application_id) == ("vercel", None)
membership = OrganizationMembership.objects.get(user=new_user, organization=new_org)
assert membership.level == OrganizationMembership.Level.OWNER
mock_report.assert_called_once()
@patch("ee.vercel.integration.report_user_signed_up")
def test_upsert_installation_existing_user_new_org(self, mock_report):
"""Test: External user (no Vercel mapping) installs - added to org but no mapping until SSO."""
existing_user = User.objects.create_user(
email=self.payload["account"]["contact"]["email"], password="existing", first_name="Existing"
)
new_installation_id = self.NEW_INSTALLATION_ID
existing_user_claims = self._create_user_claims("existing_user_789")
existing_user_claims.installation_id = new_installation_id
existing_user_claims.sub = "account:test:user:existing"
VercelIntegration.upsert_installation(new_installation_id, self.payload, existing_user_claims)
new_installation = OrganizationIntegration.objects.get(integration_id=new_installation_id)
assert new_installation.created_by == existing_user
# User mapping is NOT created - user must prove ownership via SSO login first
assert "user_mappings" not in new_installation.config or "existing_user_789" not in new_installation.config.get(
"user_mappings", {}
)
# Check all other config fields match (credentials are in sensitive_config)
for key, value in self.payload.items():
if key == "credentials":
assert new_installation.sensitive_config["credentials"] == value
else:
assert new_installation.config[key] == value
# Existing user IS added to the organization - they are installing so they should be a member
new_org = new_installation.organization
membership = OrganizationMembership.objects.get(user=existing_user, organization=new_org)
assert membership.level == OrganizationMembership.Level.OWNER
assert OrganizationProvisioning.objects.get(organization=new_org).partner == "vercel"
mock_report.assert_not_called()
@patch("ee.vercel.integration.report_user_signed_up")
def test_upsert_installation_does_not_trust_prior_mapping_from_another_installation(self, mock_report):
from ee.vercel.integration import RequiresExistingUserLogin
trusted_user = User.objects.create_user(
email=self.payload["account"]["contact"]["email"], password="existing", first_name="Trusted"
)
self.installation.config["user_mappings"] = {"prior_vercel_id": trusted_user.pk}
self.installation.save(update_fields=["config"])
new_installation_id = self.NEW_INSTALLATION_ID
claims = self._create_user_claims("new_vercel_id")
claims.installation_id = new_installation_id
VercelIntegration.upsert_installation(new_installation_id, self.payload, claims)
new_installation = OrganizationIntegration.objects.get(integration_id=new_installation_id)
assert "new_vercel_id" not in new_installation.config.get("user_mappings", {})
mock_report.assert_not_called()
claims.user_email_verified = False
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._find_sso_user(claims)
def test_upsert_installation_logs_contact_email_mismatch_with_token(self):
new_installation_id = self.NEW_INSTALLATION_ID
claims = self._create_user_claims("mismatch_vercel_id")
claims.installation_id = new_installation_id
claims.user_email = "[email protected]"
claims.user_email_verified = True
with patch("ee.vercel.integration.logger") as mock_logger:
VercelIntegration.upsert_installation(new_installation_id, self.payload, claims)
mock_logger.warning.assert_called_once_with(
"Vercel installation contact email differs from token email",
installation_id=new_installation_id,
vercel_user_id="mismatch_vercel_id",
integration="vercel",
)
args, kwargs = mock_logger.warning.call_args
for value in (*args, *kwargs.values()):
assert "[email protected]" not in str(value)
assert self.payload["account"]["contact"]["email"] not in str(value)
mock_logger.info.assert_any_call(
"Starting Vercel installation upsert process",
installation_id=new_installation_id,
integration="vercel",
token_email_verified=True,
contact_email_matches_token=False,
)
def test_upsert_installation_logs_contact_email_match_with_token(self):
new_installation_id = self.NEW_INSTALLATION_ID
claims = self._create_user_claims("match_vercel_id")
claims.installation_id = new_installation_id
claims.user_email_verified = False
with patch("ee.vercel.integration.logger") as mock_logger:
VercelIntegration.upsert_installation(new_installation_id, self.payload, claims)
mock_logger.warning.assert_not_called()
mock_logger.info.assert_any_call(
"Starting Vercel installation upsert process",
installation_id=new_installation_id,
integration="vercel",
token_email_verified=False,
contact_email_matches_token=True,
)
@patch("ee.vercel.integration.report_user_signed_up")
def test_sso_requires_login_for_unverified_existing_email(self, mock_report):
from ee.vercel.integration import RequiresExistingUserLogin
# Create an existing PostHog user (not through Vercel)
existing_user = User.objects.create_user(
email="[email protected]", password="external", first_name="External"
)
# Now install Vercel integration with that email
installation_id = self.NEW_INSTALLATION_ID
payload = {
**self.payload,
"account": {
**self.payload["account"],
"contact": {"email": "[email protected]", "name": "External User"},
},
}
user_claims = self._create_user_claims("vercel_external_user")
user_claims.installation_id = installation_id
user_claims.user_email = "[email protected]"
VercelIntegration.upsert_installation(installation_id, payload, user_claims)
installation = OrganizationIntegration.objects.get(integration_id=installation_id)
# User mapping is NOT created - they need to prove ownership via SSO login
assert "user_mappings" not in installation.config or "vercel_external_user" not in installation.config.get(
"user_mappings", {}
)
# User IS added to org - they are installing so they should be a member
membership = OrganizationMembership.objects.get(user=existing_user, organization=installation.organization)
assert membership.level == OrganizationMembership.Level.OWNER
sso_claims = self._create_user_claims("vercel_external_user")
sso_claims.installation_id = installation_id
sso_claims.user_email = "[email protected]"
sso_claims.user_email_verified = False
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._find_sso_user(sso_claims)
def test_sso_requires_login_and_does_not_reactivate_inactive_user(self):
from ee.vercel.integration import RequiresExistingUserLogin
inactive_user = User.objects.create_user(
email="[email protected]", password="inactive", first_name="Inactive", is_active=False
)
installation_id = self.NEW_INSTALLATION_ID
installation = OrganizationIntegration.objects.create(
organization=self.organization,
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id=installation_id,
config={"scopes": ["read"]},
created_by=self.user,
)
claims = self._create_user_claims("vercel_inactive_user")
claims.installation_id = installation_id
claims.user_email = "[email protected]"
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._find_sso_user(claims)
inactive_user.refresh_from_db()
assert inactive_user.is_active is False
installation.refresh_from_db()
assert "vercel_inactive_user" not in installation.config.get("user_mappings", {})
@parameterized.expand(
[
("matching_verified_email", None, True, True),
("matching_unverified_email", None, False, False),
("different_verified_email", "[email protected]", True, False),
]
)
@patch("ee.vercel.integration.report_user_signed_up")
def test_sso_login_through_a_mapping_needs_the_mapped_users_verified_email(
self,
_name: str,
claim_email: str | None,
claim_email_verified: bool,
expect_login: bool,
mock_report: Mock,
) -> None:
installation_id = self.NEW_INSTALLATION_ID
claims = self._create_user_claims("vercel_mapped_user")
claims.installation_id = installation_id
VercelIntegration.upsert_installation(installation_id, self.payload, claims)
user = User.objects.get(email=self.payload["account"]["contact"]["email"])
claims.user_email = claim_email or user.email
claims.user_email_verified = claim_email_verified
request = RequestFactory().get("/")
SessionMiddleware(lambda request: HttpResponse()).process_request(request)
if expect_login:
VercelIntegration._authenticate_and_login_user(request, claims, None)
else:
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._authenticate_and_login_user(request, claims, None)
user.refresh_from_db()
assert user.is_email_verified is expect_login
assert (request.session.get(SESSION_KEY) == str(user.pk)) is expect_login
@parameterized.expand([("verified_claim", True), ("unverified_claim", False)])
@patch("ee.vercel.integration.report_user_signed_up")
def test_sso_login_verifies_a_new_users_email_only_from_a_verified_claim(
self, _name: str, claim_email_verified: bool, mock_report: Mock
) -> None:
claims = self._create_user_claims("vercel_new_user")
claims.user_email = "[email protected]"
claims.user_email_verified = claim_email_verified
request = RequestFactory().get("/")
SessionMiddleware(lambda request: HttpResponse()).process_request(request)
user = VercelIntegration._authenticate_and_login_user(request, claims, None)
assert user.email == "[email protected]"
assert user.is_email_verified is claim_email_verified
@parameterized.expand(
[
(f"{policy}_{mapped}", policy, mapped)
for policy in ("totp", "passkey", "sso", "inactive", "domain")
for mapped in (False, True)
]
)
@override_settings(
CLOUD_DEPLOYMENT="US",
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY="synthetic-client",
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET="synthetic-secret",
)
def test_sso_preserves_account_login_requirements(self, _name: str, policy: str, mapped: bool) -> None:
claims = self._create_user_claims("protected_user")
claims.user_email = self.user.email
if mapped:
self.installation.config["user_mappings"] = {claims.user_id: self.user.pk}
self.installation.save()
if policy == "totp":
TOTPDevice.objects.create(user=self.user, name="default", confirmed=True)
elif policy == "passkey":
self.user.passkeys_enabled_for_2fa = True
self.user.save()
WebauthnCredential.objects.create(
user=self.user,
credential_id=b"synthetic-credential",
public_key=b"synthetic-public-key",
algorithm=-7,
verified=True,
)
elif policy == "sso":
self.organization.available_product_features = [{"key": "sso_enforcement"}]
self.organization.save()
OrganizationDomain.objects.create(
organization=self.organization,
domain="example.com",
verified_at=timezone.now(),
sso_enforcement="google-oauth2",
)
elif policy == "inactive":
self.user.is_active = False
self.user.save()
elif policy == "domain":
self.organization.enforce_verified_domains = True
self.organization.save()
request = RequestFactory().get("/")
SessionMiddleware(lambda request: HttpResponse()).process_request(request)
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._authenticate_and_login_user(request, claims, None)
assert SESSION_KEY not in request.session
self.installation.refresh_from_db()
assert self.installation.config.get("user_mappings", {}).get(claims.user_id) == (
self.user.pk if mapped else None
)
def test_sso_does_not_replace_an_inactive_users_mapping(self) -> None:
inactive_user = User.objects.create_user(
email="[email protected]", password=None, first_name="Inactive", is_active=False
)
claims = self._create_user_claims("inactive_mapping")
claims.user_email = self.user.email
self.installation.config["user_mappings"] = {claims.user_id: inactive_user.pk}
self.installation.save()
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._find_sso_user(claims)
self.installation.refresh_from_db()
assert self.installation.config["user_mappings"][claims.user_id] == inactive_user.pk
@parameterized.expand(
[
("mapped_user_with_a_different_email", "self", "[email protected]", True, True, True),
("unmapped_user_with_a_different_email", None, "[email protected]", True, True, False),
("mapping_to_another_user", "other", "[email protected]", True, True, False),
("unverified_matching_email", None, "[email protected]", False, True, False),
("matching_email_cannot_take_another_users_mapping", "other", "[email protected]", True, True, False),
("mapped_user_removed_from_the_organization", "self", "[email protected]", True, False, False),
]
)
def test_sso_continue_links_only_a_proven_or_already_mapped_user(
self,
_name: str,
mapping_owner: str | None,
claim_email: str,
claim_email_verified: bool,
still_a_member: bool,
expect_linked: bool,
) -> None:
other_user = User.objects.create_user(email="[email protected]", password="other", first_name="Other")
owners = {"self": self.user.pk, "other": other_user.pk}
if mapping_owner:
self.installation.config["user_mappings"] = {"vercel_login_user": owners[mapping_owner]}
self.installation.save()
if not still_a_member:
OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()
claims = self._create_user_claims("vercel_login_user")
claims.user_email = claim_email
claims.user_email_verified = claim_email_verified
code = f"continue_code_{_name}"
VercelIntegration.set_cached_claims(code, claims, timeout=300)
request = RequestFactory().get("/")
SessionMiddleware(lambda request: HttpResponse()).process_request(request)
request.user = self.user
redirect_url = VercelIntegration.complete_sso_for_logged_in_user(
request, SSOParams(mode="login", code=code, state="test_state")
)
self.installation.refresh_from_db()
assert ("/integrations/vercel/link-error" in redirect_url) is not expect_linked
expected_mapping = self.user.pk if expect_linked else owners.get(mapping_owner or "")
assert self.installation.config.get("user_mappings", {}).get("vercel_login_user") == expected_mapping
names_an_account = "expected_email" in parse_qs(urlparse(redirect_url).query)
assert names_an_account is (not expect_linked and mapping_owner is None)
assert OrganizationMembership.objects.filter(user=self.user, organization=self.organization).exists() is (
still_a_member or expect_linked
)
@patch("ee.vercel.integration.report_user_signed_up")
def test_sso_works_for_trusted_vercel_user_second_installation(self, mock_report):
# First installation - creates user with mapping
first_installation_id = self.NEW_INSTALLATION_ID
first_user_claims = self._create_user_claims("vercel_user_abc")
first_user_claims.installation_id = first_installation_id
VercelIntegration.upsert_installation(first_installation_id, self.payload, first_user_claims)
user = User.objects.get(email=self.payload["account"]["contact"]["email"])
# Second installation - same email, different installation
second_installation_id = "icfg_second_install_12345678"
second_payload = {**self.payload, "account": {**self.payload["account"], "name": "Second Org"}}
second_user_claims = self._create_user_claims("vercel_user_xyz")
second_user_claims.installation_id = second_installation_id
VercelIntegration.upsert_installation(second_installation_id, second_payload, second_user_claims)
# No mapping is created on the second installation until the user proves ownership
second_installation = OrganizationIntegration.objects.get(integration_id=second_installation_id)
assert "vercel_user_xyz" not in second_installation.config.get("user_mappings", {})
membership = OrganizationMembership.objects.get(user=user, organization=second_installation.organization)
assert membership.level == OrganizationMembership.Level.OWNER
sso_claims = self._create_user_claims("vercel_user_xyz")
sso_claims.installation_id = second_installation_id
request = RequestFactory().get("/")
SessionMiddleware(lambda request: HttpResponse()).process_request(request)
authenticated_user = VercelIntegration._authenticate_and_login_user(request, sso_claims, None)
second_installation.refresh_from_db()
assert authenticated_user.pk == user.pk
assert request.session[SESSION_KEY] == str(user.pk)
assert second_installation.config["user_mappings"]["vercel_user_xyz"] == user.pk
user.refresh_from_db()
assert user.current_organization == second_installation.organization
@patch("ee.vercel.integration.report_user_signed_up")
@patch("ee.billing.billing_manager.BillingManager")
@patch("ee.vercel.integration.get_cached_instance_license")
def test_billing_failure_does_not_delete_existing_user(self, mock_license, mock_billing, mock_report):
"""Billing failure should NOT delete existing users (only newly created ones)."""
# First installation - creates user with mapping
first_installation_id = self.NEW_INSTALLATION_ID
first_user_claims = self._create_user_claims("vercel_user_billing")
first_user_claims.installation_id = first_installation_id
VercelIntegration.upsert_installation(first_installation_id, self.payload, first_user_claims)
user = User.objects.get(email=self.payload["account"]["contact"]["email"])
user_pk = user.pk
# Second installation - billing will fail
second_installation_id = "icfg_billing_fail_123456789"
second_payload = {**self.payload, "account": {**self.payload["account"], "name": "Second Org"}}
second_user_claims = self._create_user_claims("vercel_user_billing_2")
second_user_claims.installation_id = second_installation_id
# Make billing fail
mock_license.return_value = Mock()
mock_billing.return_value.authorize.side_effect = Exception("Billing failed")
with self.assertRaises(Exception):
VercelIntegration.upsert_installation(second_installation_id, second_payload, second_user_claims)
# User should NOT be deleted - they existed before this installation
assert User.objects.filter(pk=user_pk).exists(), "Trusted Vercel user should NOT be deleted on billing failure"
@patch("ee.vercel.integration.capture_exception")
def test_upsert_installation_integrity_error(self, mock_capture):
error_user_claims = self._create_user_claims("error_user_999")
error_user_claims.installation_id = self.NEW_INSTALLATION_ID
error_user_claims.sub = "account:test:user:error"
with patch("ee.vercel.integration.OrganizationIntegration.objects.update_or_create") as mock_update_or_create:
mock_update_or_create.side_effect = IntegrityError("Duplicate key")
with self.assertRaises(ValidationError) as context:
VercelIntegration.upsert_installation(self.NEW_INSTALLATION_ID, self.payload, error_user_claims)
detail = context.exception.detail
if isinstance(detail, dict):
assert detail.get("validation_error") == "Something went wrong."
mock_capture.assert_called_once()
def test_upsert_installation_creates_org_with_fallback_name(self):
new_installation_id = self.NEW_INSTALLATION_ID
payload_without_name = self.payload.copy()
del payload_without_name["account"]["name"]
fallback_user_claims = self._create_user_claims("fallback_user_111")
fallback_user_claims.installation_id = new_installation_id
fallback_user_claims.sub = "account:test:user:fallback"
fallback_user_claims.user_email = payload_without_name["account"]["contact"]["email"]
fallback_user_claims.user_name = payload_without_name["account"]["contact"]["name"]
VercelIntegration.upsert_installation(new_installation_id, payload_without_name, fallback_user_claims)
new_installation = OrganizationIntegration.objects.get(integration_id=new_installation_id)
assert new_installation.organization.name == f"Vercel Installation {new_installation_id}"
def test_upsert_installation_creates_user_with_fallback_name(self):
new_installation_id = self.NEW_INSTALLATION_ID
payload_without_name = self.payload.copy()
del payload_without_name["account"]["contact"]["name"]
no_name_user_claims = self._create_user_claims("noname_user_222")
no_name_user_claims.installation_id = new_installation_id
no_name_user_claims.sub = "account:test:user:noname"
no_name_user_claims.user_email = payload_without_name["account"]["contact"]["email"]
no_name_user_claims.user_name = None
VercelIntegration.upsert_installation(new_installation_id, payload_without_name, no_name_user_claims)
new_user = User.objects.get(email=payload_without_name["account"]["contact"]["email"])
assert new_user.first_name == payload_without_name["account"]["contact"]["email"].split("@")[0]
@patch("ee.vercel.integration.signup_refused", return_value=True)
@patch("ee.vercel.integration.report_user_signed_up")
def test_upsert_installation_refused_by_an_access_rule_creates_no_user(self, mock_report, _refused):
new_user_claims = self._create_user_claims("refused_user_789")
new_user_claims.installation_id = self.NEW_INSTALLATION_ID
new_user_claims.sub = "account:test:user:refused"
with pytest.raises(exceptions.PermissionDenied) as raised:
VercelIntegration.upsert_installation(self.NEW_INSTALLATION_ID, self.payload, new_user_claims)
assert raised.value.get_codes() == "access_blocked"
assert not User.objects.filter(email=self.payload["account"]["contact"]["email"]).exists()
@patch("ee.vercel.integration.report_user_signed_up")
def test_upsert_installation_does_not_reactivate_inactive_user(self, mock_report):
new_installation_id = self.NEW_INSTALLATION_ID
inactive_email = "[email protected]"
inactive_user = User.objects.create_user(
email=inactive_email, password="testpass", first_name="Inactive", is_active=False
)
payload = self.payload.copy()
payload["account"]["contact"]["email"] = inactive_email
user_claims = self._create_user_claims("inactive_user_123")
user_claims.installation_id = new_installation_id
user_claims.user_email = inactive_email
VercelIntegration.upsert_installation(new_installation_id, payload, user_claims)
inactive_user.refresh_from_db()
assert inactive_user.is_active is False
org_integration = OrganizationIntegration.objects.get(integration_id=new_installation_id)
assert org_integration.created_by == inactive_user
assert "inactive_user_123" not in org_integration.config.get("user_mappings", {})
mock_report.assert_not_called()
def test_get_resource_not_found(self):
with self.assertRaises(NotFound):
VercelIntegration.get_resource("999999")
def test_create_resource(self):
resource_data = {
"productId": "posthog",
"name": "New Resource",
"metadata": {"key": "value"},
"billingPlanId": "posthog-usage-based",
}
result = VercelIntegration.create_resource(self.installation_id, resource_data)
assert "id" in result
assert result["productId"] == "posthog"
assert result["name"] == "New Resource"
assert result["metadata"] == {"key": "value"}
assert result["status"] == "ready"
assert "secrets" in result
assert "billingPlan" in result
resource = Integration.objects.get(pk=result["id"])
expected_config = {**resource_data, "externalId": None, "protocolSettings": None}
assert resource.config == expected_config
assert resource.team.organization == self.organization
assert resource.created_by == self.installation.created_by
def test_get_resource(self):
team, resource = self.make_team_with_vercel(self.organization, self.user)
resource.config["metadata"] = {}
resource.save()
result = VercelIntegration.get_resource(str(resource.pk))
assert result["id"] == str(resource.pk)
assert result["productId"] == "posthog"
assert result["name"] == "Test Resource"
assert result["status"] == "ready"
assert "secrets" in result
assert "billingPlan" in result
def test_update_resource(self):
team, resource = self.make_team_with_vercel(self.organization, self.user)
resource.config.update(
{
"name": "Original Name",
"metadata": {"old": "value"},
"billingPlanId": "posthog-usage-based",
}
)
resource.save()
update_data = {"name": "Updated Name", "metadata": {"new": "value"}}
result = VercelIntegration.update_resource(str(resource.pk), update_data)
resource.refresh_from_db()
assert resource.config["name"] == "Updated Name"
assert resource.config["metadata"] == {"new": "value"}
assert resource.config["productId"] == "posthog"
assert result["name"] == "Updated Name"
assert result["metadata"] == {"new": "value"}
def test_delete_resource(self):
team, resource = self.make_team_with_vercel(self.organization, self.user)
resource_id = str(resource.pk)
VercelIntegration.delete_resource(resource_id)
assert not Integration.objects.filter(pk=resource_id).exists()
def test_delete_resource_not_found(self):
with self.assertRaises(NotFound):
VercelIntegration.delete_resource("999999")
def test_create_resource_missing_name(self):
resource_data = {
"productId": "posthog",
"metadata": {"key": "value"},
"billingPlanId": "posthog-usage-based",
}
with self.assertRaises(exceptions.ValidationError) as context:
VercelIntegration.create_resource(self.installation_id, resource_data)
assert "name" in str(context.exception.detail)
def test_build_secrets_leads_with_the_next_public_names(self):
team = Team.objects.create(organization=self.organization, name="Test Team", api_token="test_api_token")
secrets = VercelIntegration._build_secrets(team)
assert secrets[0]["name"] == "NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN"
assert secrets[0]["value"] == "test_api_token"
assert secrets[1]["name"] == "NEXT_PUBLIC_POSTHOG_HOST"
assert secrets[1]["value"].startswith(("https://", "http://"))
@parameterized.expand([(prefix,) for prefix in EXPECTED_PREFIXES])
def test_build_secrets_injects_framework_prefixed_aliases(self, prefix: str):
team = Team.objects.create(organization=self.organization, name="Test Team", api_token="test_api_token")
secrets = {secret["name"]: secret["value"] for secret in VercelIntegration._build_secrets(team)}
assert secrets[f"{prefix}POSTHOG_PROJECT_TOKEN"] == "test_api_token"
assert secrets[f"{prefix}POSTHOG_HOST"].startswith(("https://", "http://"))
def test_build_secrets_covers_every_prefix_exactly_once(self):
team = Team.objects.create(organization=self.organization, name="Test Team", api_token="test_api_token")
secrets = VercelIntegration._build_secrets(team)
names = [secret["name"] for secret in secrets]
assert len(names) == len(set(names)) == 2 * len(EXPECTED_PREFIXES)
@parameterized.expand(
[
("exists", lambda self: self.make_team_with_vercel(self.organization, self.user)[0], True),
(
"not_found",
lambda self: Team.objects.create(organization=self.organization, name="No Vercel Team"),
False,
),
]
)
def test_get_vercel_resource_for_team(self, _, team_factory, should_exist):
team = team_factory(self)
result = VercelIntegration._get_vercel_resource_for_team(team)
assert (result is not None) == should_exist
@parameterized.expand(
[
("exists", lambda self: self.organization, True),
("not_found", lambda self: Organization.objects.create(name="Other Org"), False),
]
)
def test_get_installation_for_organization(self, _, org_factory, should_exist):
org = org_factory(self)
result = VercelIntegration._get_installation_for_organization(org)
assert (result == self.installation) if should_exist else (result is None)
@parameterized.expand(
[
("success", {"access_token": "test_token"}, "test_token"),
("missing", {}, None),
]
)
def test_get_access_token(self, _, credentials, expected):
self.installation.sensitive_config["credentials"] = credentials
self.installation.save()
result = VercelIntegration._get_access_token(self.installation)
assert result == expected
def test_get_access_token_fallback_from_config(self):
"""Pre-migration installations store credentials in config — fallback should find them."""
self.installation.config["credentials"] = {"access_token": "legacy_token", "token_type": "Bearer"}
self.installation.sensitive_config = {}
self.installation.save()
result = VercelIntegration._get_access_token(self.installation)
assert result == "legacy_token"
@parameterized.expand(
[
("success", False),
("failure", True),
]
)
@patch("ee.vercel.integration.VercelAPIClient")
@patch("ee.vercel.integration.capture_exception")
def test_create_vercel_client(self, _, should_fail, mock_capture, mock_client_class):
token = "bad_token" if should_fail else "good_token"
if should_fail:
mock_client_class.side_effect = ValueError("Invalid token")
assert VercelIntegration._create_vercel_client(token) is None
mock_capture.assert_called_once()
else:
mock_client = Mock()
mock_client_class.return_value = mock_client
assert VercelIntegration._create_vercel_client(token) == mock_client
mock_client_class.assert_called_once_with(bearer_token=token)
@parameterized.expand(
[
("flag", "test_flag", "Test Feature Flag", False, "test-flag"),
("flag_deleted", "deleted_flag", "Deleted Flag", True, "deleted-flag"),
]
)
def test_convert_feature_flag_to_vercel_item(self, _, name, desc, archived, expected_slug):
team, _ = self.make_team_with_vercel(self.organization, self.user)
item = self.make_feature_flag(team, name, desc, archived)
result = VercelIntegration._convert_feature_flag_to_vercel_item(item, created=True)
self.assert_vercel_item(item, result, "flag", archived, expected_slug, name, desc)
@parameterized.expand(
[
("created", True, False, False, {"id": "experiment_7", "isArchived": False}),
("archived", False, True, False, {"isArchived": True}),
("deleted", False, False, True, {"isArchived": True}),
]
)
def test_convert_experiment_to_vercel_item(
self, _name: str, created: bool, archived: bool, deleted: bool, expected_fields: dict[str, Any]
) -> None:
change = ExperimentChanged(
team_id=3,
experiment_id=7,
created=created,
deleted=deleted,
name="Checkout Test",
description=None,
archived=archived,
created_at=datetime(2026, 9, 1, tzinfo=UTC),
updated_at=datetime(2026, 9, 2, 12, tzinfo=UTC),
)
assert VercelIntegration._convert_experiment_to_vercel_item(change) == {
**expected_fields,
"slug": "checkout-test",
"origin": absolute_uri("/project/3/experiments/7"),
"category": "experiment",
"name": "Checkout Test",
"description": "",
"createdAt": 1788220800000,
"updatedAt": 1788350400000,
}
@parameterized.expand(
[
("sync_create", "sync", "create_experimentation_items", {"created": True}),
("sync_update", "sync", "update_experimentation_item", {"created": False}),
("sync_no_client", "sync", None, {"created": True, "has_client": False}),
("delete", "delete", "delete_experimentation_item", {}),
]
)
@patch("ee.vercel.integration.VercelIntegration._setup_vercel_client_for_team")
def test_vercel_item_operations(self, _, operation_type, client_method, params, mock_setup):
team, _ = self.make_team_with_vercel(self.organization, self.user)
has_client = params.get("has_client", True)
if has_client:
mock_client = Mock()
mock_api_result = Mock(success=True)
getattr(mock_client, client_method).return_value = mock_api_result
mock_result = Mock(client=mock_client, integration_config_id="config_id", resource_id="resource_id")
mock_setup.return_value = mock_result
else:
mock_setup.return_value = None
if operation_type == "sync":
vercel_item = self.make_vercel_item()
VercelIntegration._sync_item_to_vercel(
team=team,
item_type="flag",
item_pk="123",
vercel_item=vercel_item,
created=params.get("created", True),
)
else:
VercelIntegration._delete_item_from_vercel(
team=team,
item_type="flag",
item_id="test_id",
)
if has_client:
getattr(mock_client, client_method).assert_called_once()
else:
mock_setup.assert_called_once_with(team)
@patch("ee.vercel.integration.VercelIntegration._sync_item_to_vercel")
def test_sync_feature_flag_to_vercel(self, mock_sync):
team, _ = self.make_team_with_vercel(self.organization, self.user)
feature_flag = self.make_feature_flag(team, "test_flag", "Test Flag", False)
VercelIntegration.sync_feature_flag_to_vercel(feature_flag, created=True)
assert mock_sync.call_count >= 1
@patch("ee.vercel.integration.VercelIntegration._delete_item_from_vercel")
def test_delete_feature_flag_from_vercel(self, mock_delete):
team, _ = self.make_team_with_vercel(self.organization, self.user)
feature_flag = self.make_feature_flag(team, "test_flag", "Test Flag", False)
VercelIntegration.delete_feature_flag_from_vercel(feature_flag)
mock_delete.assert_called_once_with(
team=team,
item_type="flag",
item_id=f"flag_{feature_flag.pk}",
)
@patch("ee.vercel.integration.VercelIntegration.delete_feature_flag_from_vercel")
def test_feature_flag_post_save_signal_deletes_when_marked_deleted(self, mock_delete):
team, _ = self.make_team_with_vercel(self.organization, self.user)
feature_flag = FeatureFlag.objects.create(
team=team,
key="test_flag",
name="Test Flag",
deleted=False,
)
mock_delete.reset_mock()
feature_flag.deleted = True
feature_flag.save()
mock_delete.assert_called_once_with(feature_flag)
@patch("ee.vercel.integration.VercelIntegration.sync_feature_flag_to_vercel")
def test_feature_flag_post_save_signal_syncs_when_not_deleted(self, mock_sync):
"""Test that post_save signal triggers sync when feature flag is not deleted"""
team, _ = self.make_team_with_vercel(self.organization, self.user)
feature_flag = FeatureFlag.objects.create(
team=team,
key="test_flag",
name="Test Flag",
deleted=False,
)
mock_sync.assert_called_with(feature_flag, True)
mock_sync.reset_mock()
feature_flag.name = "Updated Test Flag"
feature_flag.save()
mock_sync.assert_called_once_with(feature_flag, False)
@parameterized.expand([("soft_delete", False), ("hard_delete", True)])
@patch("ee.vercel.integration.VercelIntegration.delete_experiment_from_vercel")
def test_experiment_delete_removes_the_item_from_vercel(self, _name, hard_delete, mock_delete):
team, _ = self.make_team_with_vercel(self.organization, self.user)
feature_flag = FeatureFlag.objects.create(team=team, key="exp-flag")
experiment_id = create_experiment(team_id=team.id, feature_flag_id=feature_flag.id, name="test_experiment")
mock_delete.reset_mock()
if hard_delete:
delete_experiment(team_id=team.id, experiment_id=experiment_id)
else:
update_experiment(team_id=team.id, experiment_id=experiment_id, deleted=True)
mock_delete.assert_called_once_with(team, experiment_id)
@patch("ee.vercel.integration.VercelIntegration.sync_experiment_to_vercel")
def test_experiment_post_save_signal_syncs_when_not_deleted(self, mock_sync):
"""Test that post_save signal triggers sync when experiment is not deleted"""
team, _ = self.make_team_with_vercel(self.organization, self.user)
feature_flag = FeatureFlag.objects.create(team=team, key="exp-flag")
experiment_id = create_experiment(team_id=team.id, feature_flag_id=feature_flag.id, name="test_experiment")
mock_sync.assert_called_with(team, mock.ANY)
assert mock_sync.call_args.args[1].created is True
mock_sync.reset_mock()
update_experiment(team_id=team.id, experiment_id=experiment_id, name="Updated Test Experiment")
mock_sync.assert_called_once_with(team, mock.ANY)
change = mock_sync.call_args.args[1]
assert (change.experiment_id, change.created, change.name) == (experiment_id, False, "Updated Test Experiment")
@parameterized.expand([("member", True), ("not_a_member", False)])
def test_sso_redirect_url_for_an_experiment(self, _name, is_member):
organization = self.organization if is_member else Organization.objects.create(name="Other Org")
team = Team.objects.create(organization=organization, name="Experiment Team")
feature_flag = FeatureFlag.objects.create(team=team, key="exp-flag")
experiment_id = create_experiment(team_id=team.id, feature_flag_id=feature_flag.id)
url = VercelIntegration._get_sso_experimentation_url(f"experiment_{experiment_id}", self.user)
assert url == (f"/project/{team.id}/experiments/{experiment_id}" if is_member else None)
@parameterized.expand(
[
("delete_skips_autocreate", True, False, 0),
("sync_autocreates", False, True, 1),
]
)
def test_safe_vercel_sync_only_autocreates_resource_on_sync(
self, _name, is_delete, should_create, expected_sync_calls
):
team = Team.objects.create(organization=self.organization, name="No Resource Team")
sync_func = Mock()
_safe_vercel_sync("op", "item_1", team, sync_func, is_delete=is_delete)
created = Integration.objects.filter(team=team, kind=Integration.IntegrationKind.VERCEL).exists()
assert created is should_create
assert sync_func.call_count == expected_sync_calls
@patch("ee.vercel.integration.VercelAPIClient")
def test_feature_flag_post_delete_does_not_recreate_vercel_resource(self, _mock_client):
# Regression: project deletion looped forever. During the team-deletion cascade the team's Vercel
# resource is deleted before its feature flags, so each flag's post_delete auto-created a connectable
# Integration row for the team being deleted in the same atomic transaction — orphaning it and failing
# COMMIT with an IntegrityError on the team FK. The delete path must never auto-create a resource.
team = Team.objects.create(organization=self.organization, name="Doomed Team")
flag = FeatureFlag.objects.create(team=team, key="doomed-flag")
Integration.objects.filter(team=team, kind=Integration.IntegrationKind.VERCEL).delete()
flag.delete()
assert not Integration.objects.filter(team=team, kind=Integration.IntegrationKind.VERCEL).exists()
class TestVercelInstallationRegressions(TestCase):
"""
Regression tests for Vercel installation bugs.
These tests document specific bugs that were fixed and ensure they don't regress.
Each test includes a description of the original bug and the fix.
"""
NEW_INSTALLATION_ID = "icfg_regression_test_123456789"
def setUp(self):
self.payload: dict[str, Any] = {
"scopes": ["read", "write"],
"acceptedPolicies": {"toc": "2024-02-28T10:00:00Z"},
"credentials": {"access_token": "token", "token_type": "Bearer"},
"account": {
"name": "Regression Test Org",
"url": "https://example.com",
"contact": {"email": "[email protected]", "name": "Regression Test"},
},
}
self.user_claims = VercelUserClaims(
iss="https://marketplace.vercel.com",
sub="account:test:user:regression",
aud="test_audience",
account_id="test_account",
installation_id=self.NEW_INSTALLATION_ID,
user_id="regression_user",
user_role="ADMIN",
type=None,
user_avatar_url=None,
user_email=self.payload["account"]["contact"]["email"],
user_name=self.payload["account"]["contact"].get("name"),
)
@patch("ee.vercel.integration.report_user_signed_up")
def test_regression_existing_user_without_vercel_mapping_added_to_org(self, mock_report):
"""
Regression test for: https://github.com/PostHog/posthog/pull/46107
Bug: When an existing PostHog user (without any prior Vercel mappings) installed
the Vercel integration, they were NOT added to the newly created organization.
This caused the installation to fail from Vercel's perspective.
Fix: Always add existing users to the org during installation. They are the ones
installing, so they should be a member regardless of whether they have prior
Vercel mappings.
Security note: User mapping is still only created for trusted users (those with
existing Vercel mappings). External users must prove ownership via SSO login.
"""
# Create a PostHog user who has never used Vercel before
existing_user = User.objects.create_user(
email=self.payload["account"]["contact"]["email"],
password="existing_password",
first_name="Existing",
)
# This user has NO Vercel mappings anywhere
vercel_integrations = OrganizationIntegration.objects.filter(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL
)
for integration in vercel_integrations:
user_mappings = integration.config.get("user_mappings", {})
assert existing_user.pk not in user_mappings.values(), "Test setup error: user should have no mappings"
# Install Vercel integration
VercelIntegration.upsert_installation(self.NEW_INSTALLATION_ID, self.payload, self.user_claims)
# CRITICAL: User must be added to the organization
installation = OrganizationIntegration.objects.get(integration_id=self.NEW_INSTALLATION_ID)
membership = OrganizationMembership.objects.filter(
user=existing_user, organization=installation.organization
).first()
assert membership is not None, "REGRESSION: Existing user was not added to org during installation"
assert membership.level == OrganizationMembership.Level.OWNER
# User mapping should NOT be created (security: they need to prove ownership via SSO)
user_mappings = installation.config.get("user_mappings", {})
assert "regression_user" not in user_mappings, "User mapping should not be created for external users"
@patch("ee.vercel.integration.report_user_signed_up")
def test_regression_installation_succeeds_for_external_user(self, mock_report):
"""
Regression test: Installation must succeed even for external users.
The installation should complete successfully and create:
- Organization
- OrganizationIntegration record
- User added as member
The installation should NOT fail just because the user doesn't have prior Vercel mappings.
"""
external_user = User.objects.create_user(
email=self.payload["account"]["contact"]["email"],
password="external_password",
first_name="External",
)
# Installation should not raise any exceptions
VercelIntegration.upsert_installation(self.NEW_INSTALLATION_ID, self.payload, self.user_claims)
# Verify installation was created
installation = OrganizationIntegration.objects.filter(integration_id=self.NEW_INSTALLATION_ID).first()
assert installation is not None, "REGRESSION: Installation was not created"
assert installation.organization is not None, "REGRESSION: Organization was not created"
assert installation.created_by == external_user, "REGRESSION: created_by not set correctly"
class TestAddUserToOrganization(TestCase):
"""Unit tests for _add_user_to_organization helper."""
def setUp(self):
self.user = User.objects.create_user(email="[email protected]", password="test", first_name="Test")
self.organization = Organization.objects.create(name="Test Org")
def test_adds_user_as_owner(self):
"""User is added with correct membership level."""
membership, created = VercelIntegration._add_user_to_organization(
self.user, self.organization, OrganizationMembership.Level.OWNER
)
assert created is True
assert membership.user == self.user
assert membership.organization == self.organization
assert membership.level == OrganizationMembership.Level.OWNER
def test_adds_user_as_member(self):
"""User can be added as member level."""
membership, created = VercelIntegration._add_user_to_organization(
self.user, self.organization, OrganizationMembership.Level.MEMBER
)
assert created is True
assert membership.level == OrganizationMembership.Level.MEMBER
def test_idempotent_does_not_duplicate(self):
"""Calling twice doesn't create duplicate membership."""
membership1, created1 = VercelIntegration._add_user_to_organization(
self.user, self.organization, OrganizationMembership.Level.OWNER
)
membership2, created2 = VercelIntegration._add_user_to_organization(
self.user, self.organization, OrganizationMembership.Level.OWNER
)
assert created1 is True
assert created2 is False
assert membership1.pk == membership2.pk
assert OrganizationMembership.objects.filter(user=self.user, organization=self.organization).count() == 1
def test_upgrades_membership_level_if_higher(self):
"""Existing membership is upgraded if new level is higher."""
# First add as member
VercelIntegration._add_user_to_organization(self.user, self.organization, OrganizationMembership.Level.MEMBER)
# Add as owner - should upgrade
membership, created = VercelIntegration._add_user_to_organization(
self.user, self.organization, OrganizationMembership.Level.OWNER
)
assert created is False
assert membership.level == OrganizationMembership.Level.OWNER
def test_does_not_downgrade_membership_level(self):
"""Existing membership is not downgraded if new level is lower."""
# First add as owner
VercelIntegration._add_user_to_organization(self.user, self.organization, OrganizationMembership.Level.OWNER)
# Try to add as member - should not downgrade
membership, created = VercelIntegration._add_user_to_organization(
self.user, self.organization, OrganizationMembership.Level.MEMBER
)
assert created is False
assert membership.level == OrganizationMembership.Level.OWNER
class TestInstallationUserHandlingLogic(TestCase):
"""
Unit tests for the user handling decision logic in upsert_installation.
Tests the core logic: when to add users to orgs and when to create mappings.
"""
def setUp(self):
self.payload: dict[str, Any] = {
"scopes": ["read", "write"],
"acceptedPolicies": {"toc": "2024-02-28T10:00:00Z"},
"credentials": {"access_token": "token", "token_type": "Bearer"},
"account": {
"name": "Test Org",
"url": "https://example.com",
"contact": {"email": "[email protected]", "name": "Test User"},
},
}
def _create_claims(self, installation_id: str, user_id: str) -> VercelUserClaims:
return VercelUserClaims(
iss="https://marketplace.vercel.com",
sub=f"account:test:user:{user_id}",
aud="test_audience",
account_id="test_account",
installation_id=installation_id,
user_id=user_id,
user_role="ADMIN",
type=None,
user_avatar_url=None,
user_email=self.payload["account"]["contact"]["email"],
user_name=self.payload["account"]["contact"].get("name"),
)
@parameterized.expand(
[
("new_user", False, True, True), # New user: added to org, mapping created
("trusted_user", True, True, False), # Trusted user: added to org, NO mapping until SSO login
("external_user", False, True, False), # External user: added to org, NO mapping
]
)
@patch("ee.vercel.integration.report_user_signed_up")
def test_user_handling_matrix(self, name, has_prior_mapping, expect_membership, expect_mapping, mock_report):
"""
Test matrix for user handling during installation.
| User Type | Has Prior Mapping | Added to Org | Mapping Created |
|---------------|-------------------|--------------|-----------------|
| New user | N/A | Yes | Yes |
| Trusted user | Yes | Yes | No |
| External user | No | Yes | No |
"""
installation_id = f"icfg_matrix_{name}_123456789"
if name == "new_user":
# No existing user
pass
else:
# Create existing user
user = User.objects.create_user(
email=self.payload["account"]["contact"]["email"],
password="test",
first_name="Existing",
)
if has_prior_mapping:
# Create a prior Vercel installation with mapping
prior_org = Organization.objects.create(name="Prior Org")
OrganizationIntegration.objects.create(
organization=prior_org,
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id="icfg_prior_installation",
config={"user_mappings": {"prior_vercel_id": user.pk}},
created_by=user,
)
claims = self._create_claims(installation_id, "test_vercel_id")
VercelIntegration.upsert_installation(installation_id, self.payload, claims)
installation = OrganizationIntegration.objects.get(integration_id=installation_id)
user = User.objects.get(email=self.payload["account"]["contact"]["email"])
# Check membership
has_membership = OrganizationMembership.objects.filter(
user=user, organization=installation.organization
).exists()
assert has_membership == expect_membership, f"{name}: membership mismatch"
# Check mapping
user_mappings = installation.config.get("user_mappings", {})
has_mapping = "test_vercel_id" in user_mappings
assert has_mapping == expect_mapping, f"{name}: mapping mismatch"
class TestPushSecretsToVercel(TestCase):
"""Tests for pushing secrets to Vercel when API token is rotated."""
def setUp(self):
self.user = User.objects.create_user(email="[email protected]", password="test", first_name="Test")
self.organization = Organization.objects.create(name="Secrets Test Org")
self.user.join(organization=self.organization, level=OrganizationMembership.Level.OWNER)
self.team = Team.objects.create(organization=self.organization, name="Test Team")
self.resource = Integration.objects.create(
team=self.team,
kind=Integration.IntegrationKind.VERCEL,
integration_id=str(self.team.pk),
config={"productId": "posthog", "name": "Test Resource"},
created_by=self.user,
)
self.installation = OrganizationIntegration.objects.create(
organization=self.organization,
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id="icfg_secrets_test_123456789",
config={
"billing_plan_id": "posthog-usage-based",
},
sensitive_config={
"credentials": {"access_token": "test_token", "token_type": "Bearer"},
},
created_by=self.user,
)
@patch("ee.vercel.integration.VercelAPIClient")
def test_push_secrets_to_vercel_calls_api(self, mock_client_class):
mock_client = Mock()
mock_client.update_resource_secrets.return_value = Mock(success=True)
mock_client_class.return_value = mock_client
VercelIntegration.push_secrets_to_vercel(self.team)
mock_client.update_resource_secrets.assert_called_once()
call_args = mock_client.update_resource_secrets.call_args
assert call_args[1]["integration_config_id"] == self.installation.integration_id
assert call_args[1]["resource_id"] == str(self.resource.pk)
secrets = call_args[1]["secrets"]
assert len(secrets) == 2 * len(EXPECTED_PREFIXES)
for prefix in EXPECTED_PREFIXES:
assert any(s["name"] == f"{prefix}POSTHOG_PROJECT_TOKEN" for s in secrets)
assert any(s["name"] == f"{prefix}POSTHOG_HOST" for s in secrets)
@patch("ee.vercel.integration.VercelAPIClient")
def test_push_secrets_sends_current_api_token(self, mock_client_class):
mock_client = Mock()
mock_client.update_resource_secrets.return_value = Mock(success=True)
mock_client_class.return_value = mock_client
VercelIntegration.push_secrets_to_vercel(self.team)
call_args = mock_client.update_resource_secrets.call_args
secrets = call_args[1]["secrets"]
api_key_secret = next(s for s in secrets if s["name"] == "NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN")
assert api_key_secret["value"] == self.team.api_token
@patch("ee.vercel.integration.VercelAPIClient")
def test_push_secrets_does_nothing_without_vercel_resource(self, mock_client_class):
team_without_vercel = Team.objects.create(organization=self.organization, name="No Vercel Team")
VercelIntegration.push_secrets_to_vercel(team_without_vercel)
mock_client_class.assert_not_called()
@patch("ee.vercel.integration.capture_exception")
@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="HTTP error", status_code=403, error_detail="Forbidden"
)
mock_client_class.return_value = mock_client
VercelIntegration.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")
def test_push_secrets_handles_exception_gracefully(self, mock_client_class, mock_capture):
mock_client = Mock()
mock_client.update_resource_secrets.side_effect = Exception("Network error")
mock_client_class.return_value = mock_client
VercelIntegration.push_secrets_to_vercel(self.team)
mock_capture.assert_called_once()
class TestGetOrCreateConnectableResource(TestCase):
def setUp(self):
self.organization = Organization.objects.create(name="Connectable Org")
self.team = Team.objects.create(organization=self.organization, name="Connectable Team")
def _vercel_row(self, config: dict[str, Any]) -> Integration:
return Integration.objects.create(
team=self.team, kind=Integration.IntegrationKind.VERCEL, integration_id=str(self.team.pk), config=config
)
def test_creates_a_connectable_resource_when_the_team_has_none(self):
resource, created = get_or_create_connectable_resource(self.team)
assert created
assert (resource.team_id, resource.integration_id, resource.config) == (
self.team.pk,
str(self.team.pk),
{"type": "connectable"},
)
@parameterized.expand([("found_on_first_read", False), ("created_by_a_concurrent_request", True)])
def test_returns_the_existing_resource(self, _name: str, hidden_from_first_read: bool):
existing = self._vercel_row({"type": "connectable"})
real_find = IntegrationReader.find
calls = 0
def find(reader, *args, **kwargs):
nonlocal calls
calls += 1
# A concurrent request inserts the row after this request's first read.
if hidden_from_first_read and calls == 1:
return None
return real_find(reader, *args, **kwargs)
with transaction.atomic(), patch.object(IntegrationReader, "find", autospec=True, side_effect=find):
resource, created = get_or_create_connectable_resource(self.team)
# The failed insert must leave the caller's transaction usable.
assert Integration.objects.filter(pk=existing.pk).exists()
assert (resource.id, created) == (existing.id, False)
def test_a_conflicting_row_outside_the_accessor_scope_raises(self):
self._vercel_row({"type": "connectable", "warehouse_source_type": "Vercel"})
with pytest.raises(IntegrationConflict):
get_or_create_connectable_resource(self.team)