: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
import copy
import hmac
import hashlib
from collections.abc import Callable
from dataclasses import asdict, dataclass, field
from typing import Any, Literal
from urllib.parse import quote, urlencode
from django.conf import settings
from django.contrib.auth import login
from django.core.cache import cache
from django.db import IntegrityError, transaction
from django.utils import timezone
from django.utils.text import slugify
import structlog
from rest_framework import exceptions
from two_factor.utils import default_device
from posthog.api.signup import SIGNUP_BLOCKED_DETAIL, signup_refused
from posthog.auth import ACCOUNT_BLOCKED_LOGIN_URL, account_refused
from posthog.cloud_utils import get_cached_instance_license
from posthog.dataclasses import frozen
from posthog.event_usage import report_user_signed_up
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import EmailLookupHandler
from posthog.helpers.two_factor_session import has_passkeys
from posthog.integrations import IntegrationConflict, IntegrationManager, IntegrationRecord
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.product_intent import ProductIntent
from posthog.models.team import Team
from posthog.models.user import User
from posthog.schema_enums import ProductIntentContext, ProductKey
from posthog.utils import absolute_uri
from products.experiments.backend.facade.api import get_experiment_team_id
from products.experiments.backend.facade.contracts import ExperimentChanged
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.security.backend.facade.api import REFUSAL_CODE as SECURITY_REFUSAL_CODE
from ee.api.authentication import VercelAuthentication
from ee.api.vercel.types import VercelClaims, VercelUserClaims
from ee.billing.billing_types import BillingProvider
from ee.vercel.client import SSOTokenResponse, VercelAPIClient
logger = structlog.get_logger(__name__)
VercelItemType = Literal["flag", "experiment"]
# Frameworks only expose an env var to client-side bundles if it carries their own prefix, so the
# same values are injected under every prefix we support. NEXT_PUBLIC_ must stay first: it is the
# original contract for already-installed users.
CLIENT_ENV_PREFIXES = ("NEXT_PUBLIC_", "VITE_", "NUXT_PUBLIC_", "PUBLIC_")
class VercelSSOError(Exception):
pass
class RequiresExistingUserLogin(Exception):
def __init__(self, email: str, vercel_user_id: str, installation_id: str, prefill_email: bool = True):
self.email = email
self.vercel_user_id = vercel_user_id
self.installation_id = installation_id
self.prefill_email = prefill_email
super().__init__(f"User {email} must login first")
class SSOLoginRefused(Exception):
pass
@dataclass
class SSOParams:
mode: str
code: str
state: str
product_id: str | None = None
resource_id: str | None = None
project_id: str | None = None
experimentation_item_id: str | None = None
path: str | None = None
url: str | None = None
def to_dict_no_nulls(self) -> dict[str, Any]:
return {k: v for k, v in asdict(self).items() if v is not None}
@dataclass
class ResourceConfig:
productId: str
name: str
metadata: dict[str, Any]
billingPlanId: str
externalId: str | None = None
protocolSettings: dict[str, Any] | None = None
@frozen
class InstallationCredentials:
access_token: str = field(repr=False)
token_type: str
@dataclass
class InstallationContact:
email: str
name: str | None = None
@dataclass
class InstallationAccount:
url: str
contact: InstallationContact
name: str | None = None
@dataclass
class InstallationConfig:
scopes: list[str]
acceptedPolicies: dict[str, Any]
credentials: InstallationCredentials
account: InstallationAccount
class VercelSecretPushError(Exception):
pass
@dataclass
class VercelSetupResult:
client: VercelAPIClient
integration_config_id: str
resource_id: str
def _get_feature_flag_team_id(flag_id: int) -> int | None:
# nosemgrep: idor-lookup-without-team (the SSO redirect checks the user's membership in the returned team)
return FeatureFlag.objects.filter(pk=flag_id).values_list("team_id", flat=True).first()
@frozen
class SSOExperimentationConfig:
# The team of the item with this id, or None when there is no such item.
get_team_id: Callable[[int], int | None]
url_template: str
def get_or_create_connectable_resource(team: Team) -> tuple[IntegrationRecord, bool]:
"""The team's Vercel resource, created as a connectable resource when the team has none."""
resources = IntegrationManager.vercel.oauth
existing = resources.find(team.pk, external_id=str(team.pk))
if existing is not None:
return existing, False
try:
created = resources.create(team.pk, external_id=str(team.pk), config={"type": "connectable"})
return created, True
except IntegrationConflict:
# A concurrent request created the row between the read and the insert. The SDK creates in a
# savepoint, so the caller's transaction stays usable for the second read.
existing = resources.find(team.pk, external_id=str(team.pk))
if existing is None:
raise
return existing, False
class VercelIntegration:
SSO_PATH_REDIRECT_MAP = {
"billing": "/organization/billing/overview",
"usage": "/organization/billing/usage",
"support": "/#panel=support",
"secrets": "/settings/project#variables",
"onboarding": "/onboarding",
}
SSO_DEFAULT_REDIRECT = "/"
# If this grows too big, or we start doing SSO in multiple integrations,
# this could be handled in the frontend instead.
SSO_EXPERIMENTATION_CONFIG: dict[str, SSOExperimentationConfig] = {
"flag": SSOExperimentationConfig(
get_team_id=_get_feature_flag_team_id,
url_template="/project/{team_id}/feature-flags/{item_pk}",
),
"experiment": SSOExperimentationConfig(
get_team_id=get_experiment_team_id,
url_template="/project/{team_id}/experiments/{item_pk}",
),
}
@staticmethod
def _get_installation(installation_id: str) -> OrganizationIntegration:
try:
return OrganizationIntegration.objects.get(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL, integration_id=installation_id
)
except OrganizationIntegration.DoesNotExist:
raise exceptions.NotFound("Installation not found")
@staticmethod
def _get_resource(resource_id: str) -> Integration:
try:
# nosemgrep: idor-lookup-without-team (Vercel integration auth validates ownership)
return Integration.objects.get(pk=resource_id, kind=Integration.IntegrationKind.VERCEL)
except Integration.DoesNotExist:
raise exceptions.NotFound("Resource not found")
@staticmethod
def _validate_resource_belongs_to_installation(
resource: Integration, installation: OrganizationIntegration
) -> None:
if not resource.team.organization.organizationintegration_set.filter(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL, integration_id=installation.integration_id
).exists():
raise exceptions.ValidationError({"resource": "Resource does not belong to this installation."})
@staticmethod
def _get_resource_with_installation(resource_id: str) -> tuple[Integration, OrganizationIntegration]:
resource = VercelIntegration._get_resource(resource_id)
org_integration = resource.team.organization.organizationintegration_set.get(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL
)
if not org_integration.integration_id:
raise exceptions.NotFound("Installation not found")
installation = VercelIntegration._get_installation(org_integration.integration_id)
return resource, installation
@staticmethod
def _cleanup_failed_installation(
organization: Organization, installation_id: str, user: User | None = None, user_created: bool = False
) -> None:
"""
Clean up organization and integration after a failed installation.
Deletes the organization (which cascades to OrganizationIntegration) and
optionally deletes the user if it was created specifically for this installation.
"""
try:
organization.delete()
logger.info(
"Cleaned up organization after billing failure",
installation_id=installation_id,
organization_id=str(organization.id),
)
# Only delete user if it was created specifically for this installation
# Existing users should not be deleted
if user_created and user:
user.delete()
logger.info(
"Cleaned up user after billing failure",
installation_id=installation_id,
user_id=str(user.id),
)
except Exception as cleanup_error:
logger.exception(
"Failed to clean up organization after billing failure",
installation_id=installation_id,
organization_id=str(organization.id),
)
capture_exception(cleanup_error)
@staticmethod
def get_vercel_plans() -> list[dict[str, Any]]:
# Single usage-based plan matching posthog.com model
# Billing is handled through PostHog's billing service, not Vercel
return [
{
"id": "posthog-usage-based",
"type": "subscription",
"name": "Pay-as-you-go",
"description": "Usage-based pricing. View pricing: https://posthog.com/pricing",
"scope": "installation",
"paymentMethodRequired": True,
"preauthorizationAmount": 0.5,
"details": [
{"label": "Pricing details", "value": "https://posthog.com/pricing"},
{"label": "Data retention", "value": "7 years"},
{"label": "Projects", "value": "6"},
{"label": "Team members", "value": "Unlimited"},
{"label": "API access", "value": "✓"},
{"label": "No limits on tracked users", "value": "✓"},
{"label": "Email support", "value": "✓"},
],
"highlightedDetails": [
{"label": "Feature flags", "value": "1 million requests for free, then from $0.0001/request"},
{"label": "Experiments", "value": "Billed with feature flags"},
],
},
]
@staticmethod
def upsert_installation(installation_id: str, payload: dict[str, Any], user_claims: VercelUserClaims) -> None:
account_data = payload.get("account", {})
contact_data = account_data.get("contact", {})
credentials_data = payload.get("credentials", {})
vercel_user_id = user_claims.user_id
contact = InstallationContact(email=contact_data["email"], name=contact_data.get("name"))
credentials = InstallationCredentials(
access_token=credentials_data["access_token"], token_type=credentials_data["token_type"]
)
account = InstallationAccount(url=account_data["url"], contact=contact, name=account_data.get("name"))
config = InstallationConfig(
scopes=payload["scopes"],
acceptedPolicies=payload["acceptedPolicies"],
credentials=credentials,
account=account,
)
contact_email_matches_token = (
user_claims.user_email.lower() == contact_data["email"].lower() if user_claims.user_email else None
)
if contact_email_matches_token is False:
logger.warning(
"Vercel installation contact email differs from token email",
installation_id=installation_id,
vercel_user_id=vercel_user_id,
integration="vercel",
)
logger.info(
"Starting Vercel installation upsert process",
installation_id=installation_id,
integration="vercel",
token_email_verified=user_claims.user_email_verified,
contact_email_matches_token=contact_email_matches_token,
)
# Check if there's already an OrganizationIntegration for this installation_id
# If there is, we don't need to do update anything besides OrganizationIntegration's config.
org_integration = OrganizationIntegration.objects.filter(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id=installation_id,
).first()
config_dict = asdict(config)
credentials = config_dict.pop("credentials", {})
if org_integration is not None:
org_integration.config = config_dict
org_integration.sensitive_config = {"credentials": credentials}
org_integration.save()
logger.info("Vercel installation updated", installation_id=installation_id, integration="vercel")
return
# Create organization and integration in a DB transaction
with transaction.atomic():
# Through Vercel we can only create new organizations, not use existing ones.
# Note: We won't create a team here, that's done during Vercel resource creation.
organization = Organization.objects.create(
name=config.account.name or f"Vercel Installation {installation_id}"
)
OrganizationProvisioning.objects.create(
organization=organization, partner=OrganizationProvisioning.Partner.VERCEL
)
existing_user = User.objects.filter(email=config.account.contact.email).first()
if existing_user:
user = existing_user
user_created = False
# Always add existing user to the new organization - they're installing so they should be a member
VercelIntegration._add_user_to_organization(
existing_user, organization, OrganizationMembership.Level.OWNER
)
else:
user = VercelIntegration._create_user_for_email(
email=config.account.contact.email,
name=config.account.contact.name,
organization=organization,
level=OrganizationMembership.Level.OWNER, # User installing gets owner level
)
user_created = True
try:
org_integration, _ = OrganizationIntegration.objects.update_or_create(
organization=organization,
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id=installation_id,
defaults={
"config": config_dict,
"sensitive_config": {"credentials": credentials},
"created_by": user,
},
)
if user_created:
VercelIntegration._set_user_mapping(org_integration, vercel_user_id, user.pk)
logger.info("Created new Vercel installation", installation_id=installation_id, integration="vercel")
except IntegrityError as e:
capture_exception(e)
logger.exception(
"Failed to create Vercel installation", installation_id=installation_id, integration="vercel"
)
raise exceptions.ValidationError(
{"validation_error": "Something went wrong."},
code="unique",
)
license = get_cached_instance_license()
if license:
try:
# Deferred: BillingManager pulls the billing stack (stripe SDK, requests). This module
# is imported at AppConfig.ready() to wire the Vercel receivers, so keep that path light.
from ee.billing.billing_manager import BillingManager # noqa: PLC0415
billing_manager = BillingManager(license)
billing_manager.authorize(organization, billing_provider=BillingProvider.VERCEL)
logger.info(
"Created Stripe customer for Vercel installation",
installation_id=installation_id,
organization_id=str(organization.id),
)
except Exception as e:
logger.exception(
"Failed to create Stripe customer for Vercel installation",
installation_id=installation_id,
organization_id=str(organization.id),
)
capture_exception(e)
VercelIntegration._cleanup_failed_installation(organization, installation_id, user, user_created)
raise exceptions.APIException("Failed to initialize billing. Please try again.")
if user_created:
report_user_signed_up(
user,
is_instance_first_user=False,
is_organization_first_user=True,
backend_processor="VercelIntegration",
user_analytics_metadata=user.get_analytics_metadata(),
org_analytics_metadata=organization.get_analytics_metadata(),
social_provider="vercel",
referral_source="vercel",
)
logger.info(
"Successfully created Vercel installation",
installation_id=installation_id,
organization_id=organization.id,
integration="vercel",
)
@staticmethod
def get_installation_billing_plan(installation_id: str) -> dict[str, Any]:
VercelIntegration._get_installation(installation_id)
# No billing plans - billing is handled through PostHog's billing service
return {}
@staticmethod
def update_installation(installation_id: str, billing_plan_id: str) -> None:
logger.info("Starting Vercel installation update", installation_id=installation_id, integration="vercel")
# TODO: Implement billing plan update logic here, awaiting billing service implementation.
logger.info("Successfully updated Vercel installation", installation_id=installation_id, integration="vercel")
@staticmethod
def delete_installation(installation_id: str) -> dict[str, Any]:
logger.info("Starting Vercel installation deletion", installation_id=installation_id, integration="vercel")
installation = VercelIntegration._get_installation(installation_id)
organization = installation.organization
license = get_cached_instance_license()
if not license:
raise RuntimeError("No license available to deauthorize billing")
org_membership = (
OrganizationMembership.objects.filter(
organization=organization, level__gte=OrganizationMembership.Level.ADMIN
)
.select_related("user")
.order_by("-level")
.first()
)
if not org_membership:
raise RuntimeError(
f"No admin or owner found for organization {organization.id} — cannot deauthorize billing"
)
from ee.billing.billing_manager import BillingManager # noqa: PLC0415
billing_manager = BillingManager(license, user=org_membership.user)
billing_manager.deauthorize(organization, billing_provider=BillingProvider.VERCEL)
logger.info(
"Deauthorized billing for Vercel installation",
installation_id=installation_id,
organization_id=str(organization.id),
)
installation.delete()
logger.info(
"Successfully deleted Vercel installation",
installation_id=installation_id,
integration="vercel",
)
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":
raise exceptions.NotFound("Product not found")
return {"plans": VercelIntegration.get_vercel_plans()}
@staticmethod
def create_resource(installation_id: str, resource_data: dict[str, Any]) -> dict[str, Any]:
logger.info(
"Starting Vercel resource creation",
installation_id=installation_id,
resource_name=resource_data.get("name"),
integration="vercel",
)
if not resource_data.get("name"):
raise exceptions.ValidationError({"name": "Resource name is required."})
config = ResourceConfig(**resource_data)
installation = VercelIntegration._get_installation(installation_id)
organization: Organization = installation.organization
team = Team.objects.create_with_data(
initiating_user=installation.created_by or None,
organization=organization,
name=config.name,
# Mark one product as onboarded to skip onboarding flow and show quick start sidebar instead
has_completed_onboarding_for={"product_analytics": True},
)
# Populate intent, this will add to the sidebar and also to the quick start section
if installation.created_by:
ProductIntent.register(
team=team,
product_type=ProductKey.FEATURE_FLAGS,
context=ProductIntentContext.VERCEL_INTEGRATION,
user=installation.created_by,
)
ProductIntent.register(
team=team,
product_type=ProductKey.EXPERIMENTS,
context=ProductIntentContext.VERCEL_INTEGRATION,
user=installation.created_by,
)
resource = IntegrationManager.vercel.oauth.create(
team.pk,
external_id=str(team.pk),
config=asdict(config),
created_by_id=installation.created_by_id,
)
logger.info(
"Successfully created Vercel resource",
installation_id=installation_id,
resource_id=resource.id,
team_id=team.pk,
integration="vercel",
)
return VercelIntegration._build_resource_response(resource, team, installation)
@staticmethod
def get_resource(resource_id: str) -> dict[str, Any]:
resource, installation = VercelIntegration._get_resource_with_installation(resource_id)
return VercelIntegration._build_resource_response(resource, resource.team, installation)
@staticmethod
def update_resource(resource_id: str, resource_data: dict[str, Any]) -> dict[str, Any]:
logger.info("Starting Vercel resource update", resource_id=resource_id, integration="vercel")
resource, installation = VercelIntegration._get_resource_with_installation(resource_id)
updated_config = copy.deepcopy(resource.config)
updated_config.update(resource_data)
validated_config = ResourceConfig(**updated_config)
resource.config = asdict(validated_config)
resource.save(update_fields=["config"])
logger.info("Successfully updated Vercel resource", resource_id=resource_id, integration="vercel")
return VercelIntegration._build_resource_response(resource, resource.team, installation)
@staticmethod
def delete_resource(resource_id: str) -> None:
logger.info("Starting Vercel resource deletion", resource_id=resource_id, integration="vercel")
resource, _ = VercelIntegration._get_resource_with_installation(resource_id)
resource.delete()
logger.info("Successfully deleted Vercel resource", resource_id=resource_id, integration="vercel")
@staticmethod
def _build_resource_response(
resource: IntegrationRecord, team: Team, installation: OrganizationIntegration
) -> dict[str, Any]:
billing_plans = VercelIntegration.get_vercel_plans()
current_plan_id = installation.config.get("billing_plan_id", "posthog-usage-based")
current_plan = next((plan for plan in billing_plans if plan["id"] == current_plan_id), None)
return {
"id": str(resource.id),
"productId": resource.config.get("productId", ""),
"name": resource.config.get("name", team.name),
"metadata": resource.config.get("metadata", {}),
"status": "ready",
"secrets": VercelIntegration._build_secrets(team),
"billingPlan": current_plan,
}
@staticmethod
def _build_secrets(team: Team) -> list[dict[str, str]]:
values = {
"POSTHOG_PROJECT_TOKEN": team.api_token,
"POSTHOG_HOST": absolute_uri(),
}
return [
{"name": f"{prefix}{name}", "value": value}
for prefix in CLIENT_ENV_PREFIXES
for name, value in values.items()
]
@staticmethod
def _get_vercel_resource_for_team(team: Team) -> IntegrationRecord | None:
return IntegrationManager.vercel.oauth.find(team.pk)
@staticmethod
def _get_installation_for_organization(organization: Organization) -> OrganizationIntegration | None:
try:
return OrganizationIntegration.objects.get(
organization=organization, kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL
)
except OrganizationIntegration.DoesNotExist:
return None
@staticmethod
def _get_access_token(installation: OrganizationIntegration) -> str | None:
access_token = installation.sensitive_config.get("credentials", {}).get("access_token")
if not access_token:
# Fallback for installations not yet migrated
access_token = installation.config.get("credentials", {}).get("access_token")
if not access_token:
logger.exception(
"Missing access token for Vercel installation",
installation_id=installation.integration_id,
integration="vercel",
)
return access_token
@staticmethod
def _create_vercel_client(access_token: str) -> VercelAPIClient | None:
try:
return VercelAPIClient(bearer_token=access_token)
except ValueError as e:
logger.exception("Failed to create Vercel API client", integration="vercel")
capture_exception(e)
return None
@staticmethod
def _setup_vercel_client_for_team(team: Team) -> VercelSetupResult | None:
resource = VercelIntegration._get_vercel_resource_for_team(team)
if not resource:
logger.info("Vercel resource not found for team", team_id=team.id, integration="vercel")
return None
installation = VercelIntegration._get_installation_for_organization(team.organization)
if not installation:
logger.info(
"Vercel installation not found for organization",
team_id=team.pk,
organization_id=team.organization.pk,
integration="vercel",
)
return None
access_token = VercelIntegration._get_access_token(installation)
if not access_token:
logger.exception(
"Failed to get access token for Vercel installation",
installation_id=installation.integration_id,
team_id=team.pk,
integration="vercel",
)
return None
client = VercelIntegration._create_vercel_client(access_token)
if not client:
logger.exception(
"Failed to create Vercel API client",
installation_id=installation.integration_id,
team_id=team.pk,
integration="vercel",
)
return None
integration_config_id = installation.integration_id
if not integration_config_id:
logger.exception(
"Missing integration_id in installation",
installation_id=installation.pk,
team_id=team.pk,
integration="vercel",
)
return None
resource_id = str(resource.id)
logger.debug(
"Successfully set up Vercel client",
team_id=team.pk,
integration_config_id=integration_config_id,
resource_id=resource_id,
integration="vercel",
)
return VercelSetupResult(
client=client,
integration_config_id=integration_config_id,
resource_id=resource_id,
)
@staticmethod
def _get_vercel_item_id(item_type: VercelItemType, item_id: str | int) -> str:
return f"{item_type}_{item_id}"
@staticmethod
def _sync_item_to_vercel(
team: Team,
item_type: VercelItemType,
item_pk: str | int,
vercel_item: dict,
created: bool,
) -> None:
setup_result = VercelIntegration._setup_vercel_client_for_team(team)
if not setup_result:
return
item_id = VercelIntegration._get_vercel_item_id(item_type, item_pk)
if created:
result = setup_result.client.create_experimentation_items(
integration_config_id=setup_result.integration_config_id,
resource_id=setup_result.resource_id,
items=[vercel_item],
)
if result.success:
logger.info(
f"{item_type} created in Vercel",
item_id=item_id,
integration_config_id=setup_result.integration_config_id,
resource_id=setup_result.resource_id,
integration="vercel",
)
else:
logger.exception(
f"Failed to create {item_type} in Vercel",
item_id=item_id,
error=result.error,
integration="vercel",
)
else:
result = setup_result.client.update_experimentation_item(
integration_config_id=setup_result.integration_config_id,
resource_id=setup_result.resource_id,
item_id=item_id,
data=vercel_item,
)
if result.success:
logger.info(
f"{item_type} updated in Vercel",
item_id=item_id,
integration_config_id=setup_result.integration_config_id,
resource_id=setup_result.resource_id,
integration="vercel",
)
else:
logger.exception(
f"Failed to update {item_type} in Vercel",
item_id=item_id,
error=result.error,
integration="vercel",
)
@staticmethod
def sync_feature_flag_to_vercel(feature_flag: FeatureFlag, created: bool) -> None:
vercel_item = VercelIntegration._convert_feature_flag_to_vercel_item(feature_flag, created)
VercelIntegration._sync_item_to_vercel(
team=feature_flag.team,
item_type="flag",
item_pk=feature_flag.pk,
vercel_item=vercel_item,
created=created,
)
@staticmethod
def bulk_sync_feature_flags_to_vercel(team: Team) -> None:
flags = FeatureFlag.objects.filter(team=team, deleted=False)
for flag in flags:
try:
VercelIntegration.sync_feature_flag_to_vercel(flag, created=True)
except Exception:
logger.exception(
"Failed to bulk sync feature flag to Vercel",
flag_id=flag.pk,
team_id=team.pk,
integration="vercel",
)
@staticmethod
def _delete_item_from_vercel(team: Team, item_type: VercelItemType, item_id: str) -> None:
setup_result = VercelIntegration._setup_vercel_client_for_team(team)
if not setup_result:
return
logger.debug(f"Starting Vercel {item_type} deletion", item_id=item_id, integration="vercel")
result = setup_result.client.delete_experimentation_item(
integration_config_id=setup_result.integration_config_id,
resource_id=setup_result.resource_id,
item_id=item_id,
)
if result.success:
logger.info(
f"{item_type} deleted from Vercel",
item_id=item_id,
integration_config_id=setup_result.integration_config_id,
resource_id=setup_result.resource_id,
integration="vercel",
)
else:
logger.exception(
f"Failed to delete {item_type} from Vercel",
item_id=item_id,
integration_config_id=setup_result.integration_config_id,
resource_id=setup_result.resource_id,
error=result.error,
integration="vercel",
)
@staticmethod
def delete_feature_flag_from_vercel(feature_flag: FeatureFlag) -> None:
VercelIntegration._delete_item_from_vercel(
team=feature_flag.team,
item_type="flag",
item_id=VercelIntegration._get_vercel_item_id("flag", feature_flag.pk),
)
@staticmethod
def sync_experiment_to_vercel(team: Team, experiment: ExperimentChanged) -> None:
vercel_item = VercelIntegration._convert_experiment_to_vercel_item(experiment)
VercelIntegration._sync_item_to_vercel(
team=team,
item_type="experiment",
item_pk=experiment.experiment_id,
vercel_item=vercel_item,
created=experiment.created,
)
@staticmethod
def delete_experiment_from_vercel(team: Team, experiment_id: int) -> None:
VercelIntegration._delete_item_from_vercel(
team=team,
item_type="experiment",
item_id=VercelIntegration._get_vercel_item_id("experiment", experiment_id),
)
@staticmethod
def _convert_feature_flag_to_vercel_item(feature_flag: FeatureFlag, created: bool) -> dict:
return {
**({"id": VercelIntegration._get_vercel_item_id("flag", feature_flag.pk)} if created else {}),
"slug": feature_flag.key,
"origin": absolute_uri(f"/project/{feature_flag.team.id}/feature-flags/{feature_flag.pk}"),
"category": "flag",
"name": feature_flag.key,
"description": feature_flag.name,
"isArchived": feature_flag.deleted,
"createdAt": int(feature_flag.created_at.timestamp() * 1000),
"updatedAt": int(timezone.now().timestamp() * 1000),
}
@staticmethod
def _convert_experiment_to_vercel_item(experiment: ExperimentChanged) -> dict:
experiment_id = experiment.experiment_id
return {
**(
{"id": VercelIntegration._get_vercel_item_id("experiment", experiment_id)} if experiment.created else {}
),
"slug": slugify(experiment.name) or f"experiment-{experiment_id}",
"origin": absolute_uri(f"/project/{experiment.team_id}/experiments/{experiment_id}"),
"category": "experiment",
"name": experiment.name,
"description": experiment.description or "",
"isArchived": experiment.archived or experiment.deleted,
"createdAt": int(experiment.created_at.timestamp() * 1000),
"updatedAt": int(experiment.updated_at.timestamp() * 1000),
}
@staticmethod
def _validate_client_credentials() -> tuple[str, str]:
if not getattr(settings, "VERCEL_CLIENT_INTEGRATION_ID", None):
raise RuntimeError("Vercel integration not configured: missing VERCEL_CLIENT_INTEGRATION_ID")
if not getattr(settings, "VERCEL_CLIENT_INTEGRATION_SECRET", None):
raise RuntimeError("Vercel integration not configured: missing VERCEL_CLIENT_INTEGRATION_SECRET")
return settings.VERCEL_CLIENT_INTEGRATION_ID, settings.VERCEL_CLIENT_INTEGRATION_SECRET
@staticmethod
def _get_sso_claims_from_code(code: str, state: str | None) -> VercelClaims:
client_id, client_secret = VercelIntegration._validate_client_credentials()
# Exchange code + state for token
token_response = VercelIntegration._exchange_sso_token(code, client_id, client_secret, state)
if not token_response.id_token:
raise exceptions.AuthenticationFailed("Vercel SSO response missing id_token")
# Then exchange token for claim
claims = VercelAuthentication()._validate_jwt_token(token_response.id_token, "user")
if not isinstance(claims, VercelUserClaims):
raise NotImplementedError("SSO is only supported for user claims, not system claims")
# Cache claims for potential existing user login flow (needed because the code can only be exchanged once)
VercelIntegration.set_cached_claims(code, claims, timeout=300) # 5 minutes
return claims
@staticmethod
def _claims_prove_email(claims: VercelUserClaims, email: str) -> bool:
return claims.user_email_verified is True and (claims.user_email or "").lower() == email.lower()
@staticmethod
def _sso_login_block_reason(
user: User, claims: VercelUserClaims, installation: OrganizationIntegration
) -> str | None:
if not user.is_active:
return "inactive_user"
if claims.user_email_verified is not True:
return "email_unverified"
if not VercelIntegration._claims_prove_email(claims, user.email):
return "email_mismatch"
if default_device(user) or (user.passkeys_enabled_for_2fa and has_passkeys(user)):
return "two_factor_required"
if OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email):
return "sso_enforced"
if OrganizationDomain.objects.is_email_blocked_by_domain_enforcement(user.email, installation.organization):
return "domain_blocked"
return None
@staticmethod
def _authenticate_and_login_user(request, claims: VercelUserClaims, resource_id: str | None) -> User:
user = VercelIntegration._find_sso_user(claims)
if account_refused(request, user, call_site="vercel_sso", impersonated=False):
raise SSOLoginRefused()
if user.is_email_verified is not True and VercelIntegration._claims_prove_email(claims, user.email):
# Vercel verified the mailbox before issuing the claim, so this login proves it.
user.is_email_verified = True
user.save(update_fields=["is_email_verified"])
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
if resource_id:
VercelIntegration.set_active_project(user, resource_id)
return user
@staticmethod
def complete_sso_for_logged_in_user(request, params: SSOParams) -> str:
if not request.user.is_authenticated:
raise exceptions.AuthenticationFailed("User must be logged in")
try:
claims = VercelIntegration._get_cached_claims(params.code)
if claims is None:
raise exceptions.AuthenticationFailed("SSO claims not found in cache")
if not isinstance(claims, VercelUserClaims):
raise NotImplementedError("SSO is only supported for user claims, not system claims")
if not claims.user_email:
raise exceptions.AuthenticationFailed("Vercel SSO claims missing user email")
with transaction.atomic():
installation = OrganizationIntegration.objects.select_for_update().get(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id=claims.installation_id,
)
mapped_user_pk = VercelIntegration._get_user_mapping(installation, claims.user_id)
if mapped_user_pk is not None and not User.objects.filter(pk=mapped_user_pk).exists():
mapped_user_pk = None
if mapped_user_pk is None:
can_link = VercelIntegration._claims_prove_email(claims, request.user.email)
else:
can_link = (
mapped_user_pk == request.user.pk
and request.user.organization_memberships.filter(
organization=installation.organization, level__gte=OrganizationMembership.Level.MEMBER
).exists()
)
if not can_link:
logger.warning(
"Email mismatch in Vercel SSO",
expected_email=claims.user_email,
logged_in_email=request.user.email,
integration="vercel",
)
VercelIntegration.set_cached_claims(params.code, claims, timeout=300)
error_params = {"current_email": request.user.email, "code": params.code, "state": params.state}
# With a mapping, the linked account is the mapped one, whose email the token never proved, so name none.
if mapped_user_pk is None:
error_params["expected_email"] = claims.user_email
return f"/integrations/vercel/link-error?{urlencode(error_params)}"
intended_level = VercelIntegration._determine_membership_level(request.user.email, installation)
created = VercelIntegration._add_user_to_organization(
request.user, installation.organization, intended_level
)
VercelIntegration._set_user_mapping(installation, claims.user_id, request.user.pk)
request.user.current_organization = installation.organization
request.user.save(update_fields=["current_organization"])
# Set active project if provided, otherwise set the user's current organization
if params.resource_id:
VercelIntegration.set_active_project(request.user, params.resource_id)
redirect_url = VercelIntegration.determine_sso_redirect(
path=params.path,
url=params.url,
experimentation_item_id=params.experimentation_item_id,
user=request.user,
)
logger.info(
"Vercel SSO completed for existing user",
resource_id=params.resource_id,
installation_id=claims.installation_id,
membership_level=intended_level.label,
membership_created=created,
method="existing_user_flow",
integration="vercel",
)
return redirect_url
except Exception as e:
logger.exception("Vercel SSO completion failed", error=str(e), integration="vercel")
capture_exception(e)
raise exceptions.AuthenticationFailed("SSO completion failed")
@staticmethod
def _determine_membership_level(
user_email: str, installation: OrganizationIntegration
) -> OrganizationMembership.Level:
installer_email = installation.config.get("account", {}).get("contact", {}).get("email")
if installer_email and installer_email.lower() == user_email.lower():
return OrganizationMembership.Level.OWNER
return OrganizationMembership.Level.MEMBER
@staticmethod
def _add_user_to_organization(
user: User, organization: Organization, level: OrganizationMembership.Level
) -> tuple[OrganizationMembership, bool]:
membership, created = OrganizationMembership.objects.get_or_create(
user=user, organization=organization, defaults={"level": level}
)
if not created and membership.level < level:
membership.level = level
membership.save(update_fields=["level"])
return membership, created
@staticmethod
def _get_cache_key(code: str) -> str:
# Hash to prevent guessability (bit paranoid but better safe than sorry)
cache_salt = hmac.new(settings.SECRET_KEY.encode(), code.encode(), hashlib.sha256).hexdigest()
return f"vercel_sso_claims:{cache_salt}"
@staticmethod
def _get_cached_claims(code: str) -> VercelUserClaims | None:
claims_key = VercelIntegration._get_cache_key(code)
claims = cache.get(claims_key)
if claims:
cache.delete(claims_key) # These intended as single-use codes
return claims
@staticmethod
def set_cached_claims(code: str, claims: VercelUserClaims, timeout: int = 300) -> None:
claims_key = VercelIntegration._get_cache_key(code)
cache.set(claims_key, claims, timeout=timeout)
@staticmethod
def authenticate_sso(request, params: SSOParams) -> str:
claims: VercelClaims | None = None
try:
# First check for cached claims (from a previous attempt with email mismatch)
claims = VercelIntegration._get_cached_claims(params.code)
if claims is None:
# No cached claims, exchange the code with Vercel
claims = VercelIntegration._get_sso_claims_from_code(params.code, params.state)
if not isinstance(claims, VercelUserClaims):
raise NotImplementedError("SSO is only supported for user claims, not system claims")
user = VercelIntegration._authenticate_and_login_user(request, claims, params.resource_id)
redirect_url = VercelIntegration.determine_sso_redirect(
path=params.path,
url=params.url,
experimentation_item_id=params.experimentation_item_id,
user=user,
)
logger.info(
"Vercel SSO login successful",
resource_id=params.resource_id,
method="new_user_flow",
integration="vercel",
)
return redirect_url
except RequiresExistingUserLogin as e:
# Re-cache the claims so they're available after the user logs in
if isinstance(claims, VercelUserClaims):
VercelIntegration.set_cached_claims(params.code, claims, timeout=300)
continuation_url = f"/login/vercel/continue?{urlencode(params.to_dict_no_nulls())}"
if e.prefill_email:
message = f"Please log in with {e.email} to link your Vercel account"
login_url = f"/login?email={quote(e.email)}&message={quote(message)}&next={quote(continuation_url)}"
else:
message = "Please log in to PostHog to link your Vercel account"
login_url = f"/login?message={quote(message)}&next={quote(continuation_url)}"
logger.info(
"Vercel SSO requires existing user login",
installation_id=e.installation_id,
email=e.email,
method="login_redirect_flow",
integration="vercel",
)
return login_url
except SSOLoginRefused:
return ACCOUNT_BLOCKED_LOGIN_URL
except Exception as e:
logger.exception("Vercel SSO authentication failed", error=str(e), integration="vercel")
capture_exception(e)
raise exceptions.AuthenticationFailed("Authentication failed")
@staticmethod
def _exchange_sso_token(code: str, client_id: str, client_secret: str, state: str | None) -> SSOTokenResponse:
client = VercelAPIClient(bearer_token=None)
response = client.sso_token_exchange(code=code, client_id=client_id, client_secret=client_secret, state=state)
if not response or response.error:
error_msg = response.error if response else "Token exchange failed"
raise exceptions.AuthenticationFailed(f"Vercel token exchange failed: {error_msg}")
return response
@staticmethod
def _get_user_mapping(installation: OrganizationIntegration, vercel_user_id: str) -> int | None:
user_mappings = installation.config.get("user_mappings", {})
return user_mappings.get(vercel_user_id)
@staticmethod
def _set_user_mapping(installation: OrganizationIntegration, vercel_user_id: str, user_pk: int) -> None:
"""
We can't utilize user emails provided by Vercel for user mappings. Instead of that Vercel gives us a user id,
which is based on the Vercel account ID, the integration ID, and the installation ID.
We can store this on the OrganizationIntegration config since it's bound to an installation.
"""
if "user_mappings" not in installation.config:
installation.config["user_mappings"] = {}
installation.config["user_mappings"][vercel_user_id] = user_pk
installation.save(update_fields=["config"])
@staticmethod
def _create_user_for_email(
email: str, name: str | None, organization: Organization, level: OrganizationMembership.Level
) -> User:
first_name = ""
if name:
first_name = name.split()[0] if name.split() else name
elif email:
first_name = email.split("@")[0]
if signup_refused(email, call_site="vercel_provisioning"):
raise exceptions.PermissionDenied(SIGNUP_BLOCKED_DETAIL, code=SECURITY_REFUSAL_CODE)
user = User.objects.create_user(
email=email,
password=None,
first_name=first_name,
is_staff=False,
is_email_verified=False,
)
VercelIntegration._add_user_to_organization(user, organization, level)
return user
@staticmethod
@transaction.atomic
def _find_sso_user(claims: VercelUserClaims) -> User:
if not claims.user_email:
raise ValueError("Email is required for user creation")
installation = OrganizationIntegration.objects.select_for_update().get(
kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
integration_id=claims.installation_id,
)
# Try to find already mapped user
user_pk = VercelIntegration._get_user_mapping(installation, claims.user_id)
if user_pk:
user = User.objects.filter(pk=user_pk).first()
if user:
# Validate that the user still has access to the organization associated with the installation
if (
user.is_active
and not user.organization_memberships.filter(
organization=installation.organization, level__gte=OrganizationMembership.Level.MEMBER
).exists()
):
raise exceptions.PermissionDenied("User no longer has access to this organization")
reason = VercelIntegration._sso_login_block_reason(user, claims, installation)
if reason is None:
return user
logger.info(
"Vercel SSO mapping needs a PostHog login",
reason=reason,
email_verified=claims.user_email_verified,
installation_id=claims.installation_id,
integration="vercel",
)
# Falling through would create a second account for this person, so a mismatch goes to a PostHog login.
# The token has not proven it owns the mapped account's email, so the login page must not show it.
raise RequiresExistingUserLogin(
email=claims.user_email,
vercel_user_id=claims.user_id,
installation_id=claims.installation_id,
prefill_email=False,
)
# User was deleted, remove stale mapping
user_mappings = installation.config.get("user_mappings", {})
if claims.user_id in user_mappings:
del user_mappings[claims.user_id]
installation.save(update_fields=["config"])
existing_user = EmailLookupHandler.get_user_by_email(claims.user_email, is_active=None)
if existing_user:
if VercelIntegration._sso_login_block_reason(existing_user, claims, installation) is not None:
raise RequiresExistingUserLogin(
email=claims.user_email, vercel_user_id=claims.user_id, installation_id=claims.installation_id
)
user = existing_user
intended_level = VercelIntegration._determine_membership_level(user.email, installation)
VercelIntegration._add_user_to_organization(user, installation.organization, intended_level)
user.current_organization = installation.organization
user.save(update_fields=["current_organization"])
else:
intended_level = VercelIntegration._determine_membership_level(claims.user_email, installation)
user = VercelIntegration._create_user_for_email(
email=claims.user_email,
name=claims.user_name,
organization=installation.organization,
level=intended_level,
)
VercelIntegration._set_user_mapping(installation, claims.user_id, user.pk)
return user
@staticmethod
def determine_sso_redirect(
path: str | None, url: str | None, experimentation_item_id: str | None, user: User
) -> str:
if url:
return url
if experimentation_item_id:
if item_url := VercelIntegration._get_sso_experimentation_url(experimentation_item_id, user):
return item_url
logger.warning(
"Invalid experimentation item",
experimentation_item_id=experimentation_item_id,
url=url,
integration="vercel",
)
if path in VercelIntegration.SSO_PATH_REDIRECT_MAP:
return VercelIntegration.SSO_PATH_REDIRECT_MAP[path]
return VercelIntegration.SSO_DEFAULT_REDIRECT
@staticmethod
def _get_sso_experimentation_url(item_id: str, user: User) -> str | None:
if not item_id:
return None
item_type, item_pk = VercelIntegration._parse_sso_item_id(item_id)
if not item_type or not item_pk:
return None
config = VercelIntegration.SSO_EXPERIMENTATION_CONFIG.get(item_type)
if not config:
return None
team_id = config.get_team_id(item_pk)
if team_id is None:
return None
# Sanity check to ensure the user has access to the item's team
if not user.teams.filter(pk=team_id).exists():
return None
return config.url_template.format(team_id=team_id, item_pk=item_pk)
@staticmethod
def _parse_sso_item_id(item_id: str) -> tuple[str | None, int | None]:
for item_type in VercelIntegration.SSO_EXPERIMENTATION_CONFIG:
prefix = f"{item_type}_"
if not item_id.startswith(prefix):
continue
id_str = item_id[len(prefix) :]
if id_str.isdigit():
return item_type, int(id_str)
return None, None
@staticmethod
def set_active_project(user: User, resource_id: str):
# nosemgrep: idor-lookup-without-team (Vercel integration auth validates ownership)
resource = Integration.objects.filter(pk=resource_id, kind=Integration.IntegrationKind.VERCEL).first()
if not resource:
raise exceptions.NotFound(f"Vercel resource not found: {resource_id}")
team = resource.team
if not team:
raise exceptions.ValidationError(f"Resource has no associated team: {resource_id}")
if not user.teams.filter(pk=team.pk).exists():
raise exceptions.PermissionDenied(f"User not member of team for resource: {resource_id}")
user.current_team = team
user.save()
return resource, user, team
@staticmethod
def push_secrets_to_vercel(team: Team) -> None:
"""Push updated secrets to all Vercel resources linked to this team."""
setup_result = VercelIntegration._setup_vercel_client_for_team(team)
if not setup_result:
return
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,
)
except Exception as e:
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(
operation_name: str, item_id: str | int, team: Team, sync_func: Callable[[], None], *, is_delete: bool = False
) -> None:
"""
Safety wrapper for Vercel sync operations triggered by Django signals.
Django signals run synchronously within the same database transaction as the save/delete operation.
Without this wrapper, any network failure or API error from Vercel would cause the entire database operation to fail,
blocking users from saving or deleting their feature flags and experiments.
Operations are silently skipped if Vercel integration is not configured and
exceptions are caught and logged rather than bubbling up to the caller.
On delete (``is_delete=True``) we never auto-create a Vercel resource: with no existing resource there is
nothing to delete from Vercel, and creating one is actively harmful during team deletion. Signals run in the
caller's transaction, so the team-deletion cascade would re-insert an Integration row for a team being deleted
in that same transaction — orphaning it and failing the commit with an IntegrityError on the team FK.
"""
if not VercelIntegration._get_vercel_resource_for_team(team):
if is_delete:
return
installation = VercelIntegration._get_installation_for_organization(team.organization)
if not installation:
return
try:
resource, created = get_or_create_connectable_resource(team)
if created:
logger.info(
"Auto-created Vercel resource for connectable installation",
team_id=team.pk,
integration="vercel",
)
access_token = VercelIntegration._get_access_token(installation)
if access_token and installation.integration_id:
client = VercelAPIClient(bearer_token=access_token)
client.import_resource(
integration_config_id=installation.integration_id,
resource_id=str(resource.id),
product_id="posthog",
name=team.name,
secrets=VercelIntegration._build_secrets(team),
)
except Exception as e:
logger.exception("Failed to auto-create Vercel resource", team_id=team.pk, integration="vercel")
capture_exception(e)
return
try:
sync_func()
except Exception as e:
logger.exception(
f"Failed to {operation_name}",
item_id=item_id,
integration="vercel",
)
capture_exception(e)