Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llm-gateway): refuse gateway credentials until the email is verified (#96740)

Matt Brookere7eb9c983171
diff --git a/ee/vercel/integration.py b/ee/vercel/integration.py
index c31906f4a482..6a3b5b371ead 100644
--- a/ee/vercel/integration.py
+++ b/ee/vercel/integration.py
@@ -875,6 +875,10 @@ class VercelIntegration:
@staticmethod
def _authenticate_and_login_user(request, claims: VercelUserClaims, resource_id: str | None) -> User:
user = VercelIntegration._find_sso_user(claims)
+ if user.is_email_verified is not True and claims.user_email and claims.user_email.lower() == user.email.lower():
+ # 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)
diff --git a/ee/vercel/test/test_integration.py b/ee/vercel/test/test_integration.py
index e5d1a5a7962d..a018327bc0fe 100644
--- a/ee/vercel/test/test_integration.py
+++ b/ee/vercel/test/test_integration.py
@@ -3,8 +3,10 @@ from typing import Any
from unittest import mock
from unittest.mock import Mock, patch
+from django.contrib.sessions.middleware import SessionMiddleware
from django.db import IntegrityError
-from django.test import TestCase
+from django.http import HttpResponse
+from django.test import RequestFactory, TestCase
from parameterized import parameterized
from rest_framework import exceptions
@@ -378,6 +380,38 @@ class TestVercelIntegration(TestCase):
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._find_sso_user(sso_claims)
+ @patch("ee.vercel.integration.report_user_signed_up")
+ def test_sso_login_marks_a_matching_email_verified(self, mock_report):
+ installation_id = self.NEW_INSTALLATION_ID
+ claims = self._create_user_claims("vercel_user_verify")
+ claims.installation_id = installation_id
+ VercelIntegration.upsert_installation(installation_id, self.payload, claims)
+ user = User.objects.get(email=self.payload["account"]["contact"]["email"])
+ assert user.is_email_verified is False
+
+ request = RequestFactory().get("/")
+ SessionMiddleware(lambda request: HttpResponse()).process_request(request)
+ VercelIntegration._authenticate_and_login_user(request, claims, None)
+
+ user.refresh_from_db()
+ assert user.is_email_verified is True
+
+ @patch("ee.vercel.integration.report_user_signed_up")
+ def test_sso_login_leaves_verification_alone_when_the_claim_email_differs(self, mock_report):
+ installation_id = self.NEW_INSTALLATION_ID
+ claims = self._create_user_claims("vercel_user_other_email")
+ 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 = "[email protected]"
+
+ request = RequestFactory().get("/")
+ SessionMiddleware(lambda request: HttpResponse()).process_request(request)
+ VercelIntegration._authenticate_and_login_user(request, claims, None)
+
+ user.refresh_from_db()
+ assert user.is_email_verified is False
+
@patch("ee.vercel.integration.report_user_signed_up")
def test_sso_works_for_trusted_vercel_user_second_installation(self, mock_report):
"""E2E: Trusted Vercel user's second installation should auto-link and SSO should work."""
diff --git a/posthog/api/email_verification.py b/posthog/api/email_verification.py
index 9f94062d1f09..2c68c6a6584b 100644
--- a/posthog/api/email_verification.py
+++ b/posthog/api/email_verification.py
@@ -3,6 +3,7 @@ import time
import structlog
from rest_framework import exceptions
+from posthog.email import is_email_available
from posthog.exceptions_capture import capture_exception
from posthog.helpers.two_factor_session import (
CODE_MAX_ATTEMPTS,
@@ -10,7 +11,7 @@ from posthog.helpers.two_factor_session import (
code_based_verification_token_generator,
)
from posthog.models.user import User
-from posthog.ph_client import feature_enabled_or_false
+from posthog.ph_client import get_feature_flag_or_none
from posthog.redis import get_client
from posthog.tasks.email import send_email_verification_code
@@ -23,15 +24,29 @@ EMAIL_CODE_ATTEMPTS_REDIS_KEY_PREFIX = "email_verification_code_attempts"
def is_email_verification_disabled(user: User) -> bool:
- # using disabled here so that the default state (if no flag exists) is that verification defaults to ON.
- return user.organization is not None and feature_enabled_or_false(
- VERIFICATION_DISABLED_FLAG,
- str(user.organization.id),
- groups={"organization": str(user.organization.id)},
- group_properties={"organization": {"id": str(user.organization.id)}},
+ # Never raises: a missing flag or a flag failure both read as verification ON, and the
+ # gateway credential projection calls this from cache writes and background tasks.
+ return user.organization is not None and (
+ get_feature_flag_or_none(
+ VERIFICATION_DISABLED_FLAG,
+ str(user.organization.id),
+ groups={"organization": str(user.organization.id)},
+ group_properties={"organization": {"id": str(user.organization.id)}},
+ )
+ is True
)
+def email_verification_pending(user: User) -> bool:
+ """Whether this instance still requires the user to verify their email.
+
+ Mirrors the login gate: a null state is an account from before verification
+ existed, and an instance without email or an organization with verification
+ switched off cannot ask for one.
+ """
+ return user.is_email_verified is False and is_email_available() and not is_email_verification_disabled(user)
+
+
class EmailVerificationCodeVerifier:
"""Issues and checks the 6-digit code for signup and email-change verification.
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 2a7e25f94fe2..1c46b6922f69 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -34,6 +34,7 @@ from social_django.models import UserSocialAuth
from two_factor.utils import totp_digits
from posthog.api.authentication import password_reset_token_generator, social_login_notification
+from posthog.api.email_verification import is_email_verification_disabled
from posthog.auth import (
InternalAPIUser,
OAuthAccessTokenAuthentication,
@@ -545,6 +546,11 @@ class TestLoginAPI(APIBaseTest):
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ @patch("posthog.ph_client.posthoganalytics.get_feature_flag", side_effect=RuntimeError("flags down"))
+ @patch("posthog.ph_client.posthoganalytics.feature_enabled", side_effect=RuntimeError("flags down"))
+ def test_verification_flag_failure_reads_as_verification_required(self, _mock_enabled, _mock_get):
+ assert is_email_verification_disabled(self.user) is False
+
@patch("posthog.api.authentication.is_email_available", return_value=True)
@patch("posthog.api.authentication.email_verification_code_verifier.send_code")
@patch("posthog.api.authentication.is_email_verification_disabled", return_value=True)
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.py
index 7ff6a1a00e14..2feb12bab891 100644
--- a/posthog/api/wizard/http.py
+++ b/posthog/api/wizard/http.py
@@ -28,6 +28,7 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.email_verification import email_verification_pending
from posthog.api.wizard.utils import json_schema_to_gemini_schema
from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication
from posthog.cloud_utils import get_api_host
@@ -80,6 +81,10 @@ OPENAI_SUPPORTED_MODELS = {"o4-mini", "gpt-5-mini", "gpt-5-nano", "gpt-5"}
# loop lands on. Only requests that reach creation consume it.
WIZARD_CLOUD_RUN_DAILY_ATTEMPT_CAP = 15
+WIZARD_EMAIL_UNVERIFIED_DETAIL = (
+ "Verify your email address, then run the wizard again. The link is in the welcome email from PostHog."
+)
+
WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL = Counter(
"posthog_wizard_gateway_token_requests_total",
"Wizard gateway-token mint requests, by outcome (minted/unconfigured/not_wizard_app/"
@@ -557,6 +562,11 @@ class SetupWizardViewSet(viewsets.ViewSet):
# 403: a vanished team is an authorization failure, not a missing route.
refuse("team_missing", exceptions.PermissionDenied(ERROR_PROJECT_NOT_FOUND), user=user)
+ # Named ahead of the generic authorization check so the CLI can tell the user what to do.
+ if email_verification_pending(user):
+ WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="email_unverified").inc()
+ raise exceptions.PermissionDenied(WIZARD_EMAIL_UNVERIFIED_DETAIL)
+
# scoped_teams is frozen at consent, so re-check what it cannot see.
if not oauth_credential_authorized(access_token, team):
refuse(
diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.py
index 5a1af0d0e525..47363009de5c 100644
--- a/posthog/api/wizard/test/test_http.py
+++ b/posthog/api/wizard/test/test_http.py
@@ -17,7 +17,11 @@ from rest_framework.exceptions import AuthenticationFailed, Throttled
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
-from posthog.api.wizard.http import SETUP_WIZARD_CACHE_PREFIX, SETUP_WIZARD_CACHE_TIMEOUT
+from posthog.api.wizard.http import (
+ SETUP_WIZARD_CACHE_PREFIX,
+ SETUP_WIZARD_CACHE_TIMEOUT,
+ WIZARD_EMAIL_UNVERIFIED_DETAIL,
+)
from posthog.cloud_utils import get_api_host
from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL
from posthog.llm.wizard_gateway_token import WizardGatewayMintError
@@ -896,6 +900,27 @@ class SetupWizardGatewayTokenTests(APIBaseTest):
assert response.json()["detail"] == WIZARD_BLOCKED_DETAIL
mock_mint.assert_not_called()
+ @patch("posthog.api.email_verification.is_email_verification_disabled", return_value=False)
+ @patch("posthog.api.email_verification.is_email_available", return_value=True)
+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)
+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)
+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")
+ def test_unverified_email_is_403_and_never_mints(
+ self, mock_authentication, mock_flag, mock_mint, mock_authorized, _mock_email_available, _mock_disabled
+ ):
+ self._mock_oauth(mock_authentication)
+ self.user.is_email_verified = False
+ self.user.save()
+
+ response = self.client.post(
+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert response.json()["detail"] == WIZARD_EMAIL_UNVERIFIED_DETAIL
+ mock_mint.assert_not_called()
+
@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)
@patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)
@patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=False)
diff --git a/posthog/storage/gateway_credential_cache.py b/posthog/storage/gateway_credential_cache.py
index a39f6e789042..5ba420071b6f 100644
--- a/posthog/storage/gateway_credential_cache.py
+++ b/posthog/storage/gateway_credential_cache.py
@@ -219,13 +219,20 @@ def _ttl_for_credential(credential: Credential) -> float:
def _oauth_authorization_ok(credential: OAuthAccessToken, team: Any, team_id: int, memo: "_RefreshMemo | None") -> bool:
"""Authorization checks that only apply to an OAuth credential.
- OAuth tokens carry a user, an expiry, and scoped_* narrowing the gateway can't
- see — all enforced here, since the gateway authenticates from the cached blob
- alone (and the hourly refresh re-checks). Returns False to fail closed.
+ OAuth tokens carry a user, an expiry, scoped_* narrowing, and the user's email
+ verification state, none of which the gateway can see. All of it is enforced
+ here, since the gateway authenticates from the cached blob alone (and the hourly
+ refresh re-checks). Returns False to fail closed.
"""
+ from posthog.api.email_verification import ( # noqa: PLC0415 - keeps the email task stack off django.setup()
+ email_verification_pending,
+ )
+
user = credential.user
if user is None or not user.is_active:
return False
+ if email_verification_pending(user):
+ return False
if credential.application_id is None:
return False
if credential.expires <= timezone.now():
diff --git a/posthog/storage/gateway_credential_signal_handlers.py b/posthog/storage/gateway_credential_signal_handlers.py
index 6db84a06940d..62f04eb640c3 100644
--- a/posthog/storage/gateway_credential_signal_handlers.py
+++ b/posthog/storage/gateway_credential_signal_handlers.py
@@ -3,9 +3,9 @@ Signal handlers that keep the gateway credential cache in sync with credential a
The blob is keyed by the credential hash, so a revoke / scope removal / rotation that
doesn't invalidate it leaves a stale entry for the full TTL. OAuth access also depends on
-user state the token row doesn't carry (deactivation, org membership, RBAC), so those
-re-project the user's OAuth credentials. Project secret keys have no user, so they
-re-project only on their own save/delete and on gateway/team changes.
+user state the token row doesn't carry (deactivation, email verification, org membership,
+RBAC), so those re-project the user's OAuth credentials. Project secret keys have no user,
+so they re-project only on their own save/delete and on gateway/team changes.
A pre_save fallback handles credentials loaded with hash/scope deferred (.only()/.defer()),
where post_init skips the snapshot — without it a deferred-load rotation wouldn't clear the
@@ -47,6 +47,7 @@ _CACHE_NAME = "gateway_credential"
_LOADED_HASH_ATTR = "_fp_loaded_hash"
_LOADED_ELIGIBLE_ATTR = "_fp_loaded_eligible"
_LOADED_IS_ACTIVE_ATTR = "_fp_loaded_is_active"
+_LOADED_IS_EMAIL_VERIFIED_ATTR = "_fp_loaded_is_email_verified"
_LOADED_MEMBERSHIP_LEVEL_ATTR = "_fp_loaded_membership_level"
_LOADED_TEAM_API_TOKEN_ATTR = "_fp_loaded_team_api_token"
_LOADED_TEAM_OVERSPEND_ATTR = "_fp_loaded_team_overspend_allowance"
@@ -100,21 +101,32 @@ def _snapshot_oauth(sender: type[OAuthAccessToken], instance: OAuthAccessToken,
def _snapshot_user(sender: type[User], instance: User, **kwargs: Any) -> None:
if not settings.AI_GATEWAY_REDIS_URL:
return
- if "is_active" not in instance.get_deferred_fields():
+ deferred = instance.get_deferred_fields()
+ if "is_active" not in deferred:
instance.__dict__[_LOADED_IS_ACTIVE_ATTR] = instance.is_active
+ if "is_email_verified" not in deferred:
+ instance.__dict__[_LOADED_IS_EMAIL_VERIFIED_ATTR] = instance.is_email_verified
-def _capture_old_user_is_active_if_deferred(sender: type[User], instance: User, **kwargs: Any) -> None:
- # Fallback for a user loaded with is_active deferred (.only()/.defer()): re-read the
- # old value so a deferred-load deactivation still clears the blob. No query on the
- # common full-load path, where post_init already snapshotted.
- if not settings.AI_GATEWAY_REDIS_URL or _LOADED_IS_ACTIVE_ATTR in instance.__dict__:
+def _capture_old_user_fields_if_deferred(sender: type[User], instance: User, **kwargs: Any) -> None:
+ # Fallback for a user loaded with is_active/is_email_verified deferred (.only()/.defer()):
+ # re-read the old values so a deferred-load change still clears or restores the blob. No
+ # query on the common full-load path, where post_init already snapshotted both.
+ if not settings.AI_GATEWAY_REDIS_URL:
+ return
+ needs_is_active = _LOADED_IS_ACTIVE_ATTR not in instance.__dict__
+ needs_is_email_verified = _LOADED_IS_EMAIL_VERIFIED_ATTR not in instance.__dict__
+ if not needs_is_active and not needs_is_email_verified:
return
if not instance.pk or instance._state.adding:
return
- row = User.objects.filter(pk=instance.pk).values("is_active").first()
- if row is not None:
+ row = User.objects.filter(pk=instance.pk).values("is_active", "is_email_verified").first()
+ if row is None:
+ return
+ if needs_is_active:
instance.__dict__[_LOADED_IS_ACTIVE_ATTR] = row["is_active"]
+ if needs_is_email_verified:
+ instance.__dict__[_LOADED_IS_EMAIL_VERIFIED_ATTR] = row["is_email_verified"]
def _capture_old_secret_key_if_deferred(
@@ -246,13 +258,20 @@ def _reproject_user_sync_then_async(user_id: int) -> None:
def _reproject_user_on_save(sender: type[User], instance: User, created: bool, **kwargs: Any) -> None:
- # Only OAuth carries a user. Deactivation must clear it (the token row doesn't
- # change on is_active flips); reactivation re-grants.
+ # Only OAuth carries a user. Deactivation and losing email verification must clear
+ # it (the token row doesn't change on either flip); reversing either re-grants.
if not settings.AI_GATEWAY_REDIS_URL or created:
return
old_is_active = instance.__dict__.get(_LOADED_IS_ACTIVE_ATTR)
+ old_is_email_verified = instance.__dict__.get(_LOADED_IS_EMAIL_VERIFIED_ATTR, _UNSET)
instance.__dict__[_LOADED_IS_ACTIVE_ATTR] = instance.is_active
- if old_is_active is None or old_is_active == instance.is_active:
+ instance.__dict__[_LOADED_IS_EMAIL_VERIFIED_ATTR] = instance.is_email_verified
+
+ is_active_changed = old_is_active is not None and old_is_active != instance.is_active
+ is_email_verified_changed = (
+ old_is_email_verified is not _UNSET and old_is_email_verified != instance.is_email_verified
+ )
+ if not is_active_changed and not is_email_verified_changed:
return
_reproject_user_sync_then_async(instance.pk)
@@ -373,7 +392,7 @@ def connect_signal_handlers() -> None:
post_save.connect(_reproject_team_on_change, sender=Team)
post_init.connect(_snapshot_user, sender=User)
- pre_save.connect(_capture_old_user_is_active_if_deferred, sender=User)
+ pre_save.connect(_capture_old_user_fields_if_deferred, sender=User)
post_save.connect(_reproject_user_on_save, sender=User)
pre_save.connect(_capture_old_membership_level_if_deferred, sender=OrganizationMembership)
diff --git a/posthog/storage/test/test_gateway_credential_cache.py b/posthog/storage/test/test_gateway_credential_cache.py
index d0288542a895..caba7ebf8f1e 100644
--- a/posthog/storage/test/test_gateway_credential_cache.py
+++ b/posthog/storage/test/test_gateway_credential_cache.py
@@ -363,6 +363,33 @@ class TestGatewayCredentialFailClosed(GatewayCredentialTestMixin):
project_gateway_credential(credential)
self.assertIsNone(self._read_blob(cache_hash))
+ @parameterized.expand(
+ [
+ ("verified", True, True, False, True),
+ ("legacy_null", None, True, False, True),
+ ("unverified", False, True, False, False),
+ ("unverified_instance_without_email", False, False, False, True),
+ ("unverified_org_verification_disabled", False, True, True, True),
+ ]
+ )
+ def test_email_verification_gating(
+ self,
+ _name: str,
+ is_email_verified: bool | None,
+ email_available: bool,
+ verification_disabled: bool,
+ should_write: bool,
+ ):
+ credential = self._make_oauth(GATEWAY_SCOPE)
+ self.user.is_email_verified = is_email_verified
+ self.user.save()
+ with (
+ patch("posthog.api.email_verification.is_email_available", return_value=email_available),
+ patch("posthog.api.email_verification.is_email_verification_disabled", return_value=verification_disabled),
+ ):
+ project_gateway_credential(credential)
+ self.assertEqual(self._read_blob(credential_hash(credential)) is not None, should_write)
+
def test_oauth_scoped_team_outside_fails_closed(self):
other = Team.objects.create(organization=self.organization, name="other")
credential = self._make_oauth(GATEWAY_SCOPE)
@@ -665,6 +692,37 @@ class TestGatewayCredentialSignals(GatewayCredentialTestMixin):
self.assertIsNone(self._read_blob(cache_hash))
mock_delay.assert_not_called() # sync clear succeeded, no async retry needed
+ @parameterized.expand(
+ [
+ ("becomes_verified", False, True),
+ ("becomes_unverified", True, False),
+ ]
+ )
+ @patch("posthog.api.email_verification.is_email_available", return_value=True)
+ def test_user_email_verification_change_reprojects_synchronously(
+ self, _name: str, initial: bool, new: bool, _mock_email_available
+ ):
+ self.user.is_email_verified = initial
+ self.user.save()
+ oauth = self._make_oauth(GATEWAY_SCOPE)
+ project_gateway_credential(oauth)
+ cache_hash = credential_hash(oauth)
+ self.assertEqual(self._read_blob(cache_hash) is not None, initial)
+
+ with (
+ patch("posthog.storage.gateway_credential_signal_handlers.settings") as mock_settings,
+ patch("posthog.storage.gateway_credential_signal_handlers.transaction") as mock_transaction,
+ patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task.delay") as mock_delay,
+ ):
+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"
+ mock_transaction.on_commit.side_effect = lambda fn: fn()
+ user = User.objects.get(pk=self.user.pk)
+ user.is_email_verified = new
+ user.save()
+
+ self.assertEqual(self._read_blob(cache_hash) is not None, new)
+ mock_delay.assert_not_called() # sync reprojection succeeded, no async retry needed
+
@patch("posthog.storage.gateway_credential_signal_handlers.transaction")
@patch("posthog.storage.gateway_credential_signal_handlers.settings")
@patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task.delay")
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 74b7cea13d3f..e73e003564ee 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -256,7 +256,7 @@ pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_members
pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_oauth_if_deferred
pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_secret_key_if_deferred
pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_team_fields_if_deferred
-pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_user_is_active_if_deferred
+pre_save:posthog.storage.gateway_credential_signal_handlers._capture_old_user_fields_if_deferred
pre_save:posthog.storage.team_access_cache_signal_handlers.personal_api_key_pre_save
pre_save:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_pre_save
pre_save:posthog.storage.team_access_cache_signal_handlers.team_pre_save_auth_cache
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index 30e7451848a6..2a6ca7ac8daf 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -70,19 +70,19 @@ These are compatibility checks, not automatic blockers:
## Parity map
-| Contract | Go gateway today | Python-only behavior that can block migration |
-| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Authentication | `phs_` project secrets and `pha_` OAuth credentials require `llm_gateway:read`. Standard credentials can mint capped and revocable `phe_` tokens. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |
-| Trusted first-party identity | Scoped tokens pin product, user, and obo attribution at mint. Standard credential headers remain caller-controlled and do not authorize a product. | Product routes select allowlisted OAuth apps, server credential requirements, model policy, and Django product policy. Django also decides which callers may receive a product-scoped credential. |
-| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to a namespaced team identity. Product, user, and obo attribution land on events and ledger entries with provenance. | OAuth user identity, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived end-user identity, gateway-owned `$ai_billable`, per-key properties, and feature flag headers. |
-| Billing and limits | Wallet reservation and settlement, soft attribution budgets, a hard team cap, per-token caps, idempotency, balance and usage reads, and front-line rate limits. | Plans, quota buckets, product-specific free-model policy, unbilled products, product usage status, and Django provenance rules that decide which cap applies. |
-| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |
-| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |
-| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and configured Modal, Fireworks, and Baseten hosts. | OpenRouter and Cloudflare Workers AI. |
-| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, per-model access flags with caller-filtered listings, and product-scoped model pricing. |
-| Routing and failure behavior | Operator-managed provider plans, health-aware ordering, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |
-| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated product, user, obo, distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |
-| Session attribution | `X-PostHog-Session-Id` is recorded as the gateway-owned `$ai_session_id`. | The per-key property header can also emit `$ai_session_id`. |
+| Contract | Go gateway today | Python-only behavior that can block migration |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Authentication | `phs_` project secrets and `pha_` OAuth credentials require `llm_gateway:read`. A `pha_` credential is also rejected when its user has `is_email_verified = false`; `NULL` (legacy accounts) and `true` pass. Standard credentials can mint capped and revocable `phe_` tokens. | `phx_` personal keys (rejected on the same `is_email_verified = false` rule, without the `email-verification-disabled` incident flag bypass that Django honors), wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |
+| Trusted first-party identity | Scoped tokens pin product, user, and obo attribution at mint. Standard credential headers remain caller-controlled and do not authorize a product. | Product routes select allowlisted OAuth apps, server credential requirements, model policy, and Django product policy. Django also decides which callers may receive a product-scoped credential. |
+| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to a namespaced team identity. Product, user, and obo attribution land on events and ledger entries with provenance. | OAuth user identity, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived end-user identity, gateway-owned `$ai_billable`, per-key properties, and feature flag headers. |
+| Billing and limits | Wallet reservation and settlement, soft attribution budgets, a hard team cap, per-token caps, idempotency, balance and usage reads, and front-line rate limits. | Plans, quota buckets, product-specific free-model policy, unbilled products, product usage status, and Django provenance rules that decide which cap applies. |
+| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |
+| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |
+| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and configured Modal, Fireworks, and Baseten hosts. | OpenRouter and Cloudflare Workers AI. |
+| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, per-model access flags with caller-filtered listings, and product-scoped model pricing. |
+| Routing and failure behavior | Operator-managed provider plans, health-aware ordering, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |
+| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated product, user, obo, distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |
+| Session attribution | `X-PostHog-Session-Id` is recorded as the gateway-owned `$ai_session_id`. | The per-key property header can also emit `$ai_session_id`. |
## Migration checklist
@@ -98,10 +98,10 @@ Run `/migrating-llm-gateway-callers` to inventory and convert a caller.
Run `/auditing-llm-gateway-parity` after either gateway changes auth, attribution, billing, endpoints, providers, models, routing, or event metadata. The skill audits implementation sources in both repositories and updates this file without migrating callers.
-Last verified on 2026-09-07 against:
+Last verified on 2026-09-08 against:
-- `PostHog/posthog` working tree compared with master at `cab2e7ddca85e189cab9deb374cb1e82e55bd16d`
-- `PostHog/ai-gateway` main at `13a9277ab0e0079e9581c0e780b2b83aa72ff3db`
+- `PostHog/posthog` working tree compared with master at `5d1154d4f2d93613a5d9875e9c11d66778958a79`
+- `PostHog/ai-gateway` main at `7f61cfe690a855d465e362297ff76b98d6526314`
## References
diff --git a/services/llm-gateway/src/llm_gateway/auth/authenticators.py b/services/llm-gateway/src/llm_gateway/auth/authenticators.py
index 34c286255242..18468e06c3bf 100644
--- a/services/llm-gateway/src/llm_gateway/auth/authenticators.py
+++ b/services/llm-gateway/src/llm_gateway/auth/authenticators.py
@@ -66,6 +66,8 @@ class PersonalApiKeyAuthenticator(Authenticator):
FROM posthog_personalapikey pak
JOIN posthog_user u ON pak.user_id = u.id
WHERE pak.secure_value = $1 AND u.is_active = true
+ -- Legacy accounts predate the column and store NULL; they must pass like true.
+ AND u.is_email_verified IS DISTINCT FROM false
""",
token_hash,
)
@@ -115,6 +117,7 @@ class OAuthAccessTokenAuthenticator(Authenticator):
FROM posthog_oauthaccesstoken oat
JOIN posthog_user u ON oat.user_id = u.id
WHERE oat.token_checksum = $1 AND u.is_active = true
+ AND u.is_email_verified IS DISTINCT FROM false
""",
token_hash,
)
diff --git a/services/llm-gateway/tests/test_auth.py b/services/llm-gateway/tests/test_auth.py
index 8fa450044175..595dffcb4f66 100644
--- a/services/llm-gateway/tests/test_auth.py
+++ b/services/llm-gateway/tests/test_auth.py
@@ -710,6 +710,19 @@ class TestPersonalApiKeyAuthenticator:
assert result.auth_method == "personal_api_key"
assert result.is_staff is False
+ @pytest.mark.asyncio
+ async def test_query_requires_verified_email(
+ self, authenticator: PersonalApiKeyAuthenticator, mock_pool: MagicMock
+ ) -> None:
+ conn = mock_pool.acquire.return_value
+ conn.fetchrow = AsyncMock(return_value=None)
+
+ token_hash = authenticator.hash_token("phx_test_key")
+ await authenticator.authenticate(token_hash, mock_pool)
+
+ query = conn.fetchrow.call_args.args[0]
+ assert "u.is_email_verified IS DISTINCT FROM false" in query
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"db_result",
@@ -927,6 +940,19 @@ class TestOAuthAccessTokenAuthenticator:
assert result.scopes == ["llm_gateway:read"]
assert result.is_staff is True
+ @pytest.mark.asyncio
+ async def test_query_requires_verified_email(
+ self, authenticator: OAuthAccessTokenAuthenticator, mock_pool: MagicMock
+ ) -> None:
+ conn = mock_pool.acquire.return_value
+ conn.fetchrow = AsyncMock(return_value=None)
+
+ token_hash = authenticator.hash_token("pha_test_token")
+ await authenticator.authenticate(token_hash, mock_pool)
+
+ query = conn.fetchrow.call_args.args[0]
+ assert "u.is_email_verified IS DISTINCT FROM false" in query
+
@pytest.mark.asyncio
async def test_valid_token_with_null_team_id(
self, authenticator: OAuthAccessTokenAuthenticator, mock_pool: MagicMock