:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(auth): resolve case-variant email logins to the account in use (#92386)
posthog[bot]e194e455d76b
diff --git a/ee/api/scim/test/test_users_api.py b/ee/api/scim/test/test_users_api.pyindex a806fc43e7e8..b2e9aed0f08b 100644--- a/ee/api/scim/test/test_users_api.py+++ b/ee/api/scim/test/test_users_api.py@@ -497,10 +497,16 @@ class TestSCIMUsersAPI(APILicensedTest):)assert not User.objects.filter(email="[email protected]").exists()- def test_put_user_email_belongs_to_another_user(self):+ @parameterized.expand(+ [+ ("exact", "[email protected]", "[email protected]"),+ ("dotted_capital_i", "[email protected]", "bİ[email protected]"),+ ]+ )+ def test_put_user_email_belongs_to_another_user(self, _name, existing_email, submitted_email):# Existing user A in orguser_a = User.objects.create_user(- email="[email protected]", password=None, first_name="Alpha", is_email_verified=True+ email=existing_email, password=None, first_name="Alpha", is_email_verified=True)OrganizationMembership.objects.create(user=user_a, organization=self.organization, level=OrganizationMembership.Level.MEMBER@@ -517,9 +523,9 @@ class TestSCIMUsersAPI(APILicensedTest):# IdP mismatches B and tries to PUT with A emailput_data_conflict = {"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],- "userName": "[email protected]",+ "userName": submitted_email,"name": {"givenName": "Should", "familyName": "Fail"},- "emails": [{"value": "[email protected]", "primary": True}],+ "emails": [{"value": submitted_email, "primary": True}],"active": True,}@@ -1152,9 +1158,15 @@ class TestSCIMUsersAPI(APILicensedTest):user.refresh_from_db()assert user.email == "[email protected]"- def test_patch_replace_email_case_collision_rejected(self):- # A case-variant of an existing account's email collides at login time (email__iexact),- # so SCIM must reject it even though the unique index is case-sensitive.+ @parameterized.expand(+ [+ ("ascii_case_variant", "[email protected]"),+ ("dotted_capital_i", "exİ[email protected]"),+ ]+ )+ def test_patch_replace_email_case_collision_rejected(self, _name, colliding_email):+ # A case-variant of an existing account's email collides at login time, so SCIM must reject it+ # even though the unique index is case-sensitive.user_a = User.objects.create_user(email="[email protected]", password=None, first_name="A", is_email_verified=True)@@ -1181,7 +1193,7 @@ class TestSCIMUsersAPI(APILicensedTest):{"op": "replace","path": "emails",- "value": [{"value": "[email protected]", "primary": True}],+ "value": [{"value": colliding_email, "primary": True}],}],}diff --git a/ee/api/scim/user.py b/ee/api/scim/user.pyindex ce6b1c43f741..4a1890e5cdf9 100644--- a/ee/api/scim/user.py+++ b/ee/api/scim/user.py@@ -7,6 +7,7 @@ from django_scim import constantsfrom django_scim.adapters import SCIMUserfrom scim2_filter_parser.attr_paths import AttrPath+from posthog.helpers.email_utils import EmailLookupHandlerfrom posthog.models import Organization, OrganizationMembership, Userfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomain@@ -237,7 +238,7 @@ class PostHogSCIMUser(SCIMUser):with transaction.atomic():# Do not allow changing email to another user's email- existing_user_with_email = User.objects.filter(email__iexact=email).exclude(id=self.obj.id).first()+ existing_user_with_email = EmailLookupHandler.users_matching_email(email).exclude(id=self.obj.id).first()if existing_user_with_email:raise ValueError("Email belongs to another user")@@ -353,7 +354,7 @@ class PostHogSCIMUser(SCIMUser):return Nonedef _apply_email(self, email: str) -> None:- if User.objects.filter(email__iexact=email).exclude(id=self.obj.id).exists():+ if EmailLookupHandler.users_matching_email(email).exclude(id=self.obj.id).exists():raise ValueError("Email belongs to another user")_validate_email_domain_is_verified(email, self._config.organization)# Org must also own the current email domain to prevent cross-tenant account takeoverdiff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex 0b06e5f33a10..5dadc4a8aa3f 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -239,6 +239,36 @@ class TestEEAuthenticationAPI(APILicensedTest):)self.assertEqual(len(mail.outbox), 0)+ def test_sso_enforcement_follows_the_account_the_typed_address_resolves_to(self):+ self.client.logout()+ member = User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)+ member.is_email_verified = True+ member.save(update_fields=["is_email_verified"])+ self.create_enforced_domain(domain="victim.example")++ # Postgres lowercases `İ` (U+0130) to `i`, so the second address resolves to the member's account+ # while its typed domain does not match the enforced one.+ for typed_email in ("[email protected]", "member@vİctim.example"):+ with self.subTest(email=typed_email), self.settings(**GOOGLE_MOCK_SETTINGS):+ precheck = self.client.post("/api/login/precheck", {"email": typed_email})+ response = self.client.post("/api/login", {"email": typed_email, "password": self.CONFIG_PASSWORD})++ self.assertEqual(precheck.json()["sso_enforcement"], "google-oauth2")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertEqual(response.json()["code"], "sso_enforced")+ self.assertNotIn("_auth_user_id", self.client.session)++ def test_cannot_reset_password_through_a_typed_domain_that_resolves_to_an_enforced_account(self):+ User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)+ self.create_enforced_domain(domain="victim.example")++ with self.settings(**GOOGLE_MOCK_SETTINGS, EMAIL_HOST="localhost", SITE_URL="https://my.posthog.net"):+ response = self.client.post("/api/reset/", {"email": "member@vİctim.example"})++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "sso_enforced")+ self.assertEqual(len(mail.outbox), 0)+@patch("posthog.models.organization_domain.logger.warning")def test_cannot_enforce_sso_without_a_license(self, mock_warning):self.client.logout()diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 4af6954c2e46..80169ca825c3 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -98,6 +98,20 @@ class WebauthnCredentialPrecheck(TypedDict):transports: list[str]+def sso_enforcement_for_login_address(email: str, user: User | None) -> str | None:+ """+ Return the SSO enforcement for a typed address or for the account it resolves to.++ The account lookup folds case in Postgres, so a typed domain can differ from the domain on the account it+ reaches: Postgres lowercases `İ` (U+0130) to `i`. Checking only the typed domain would let an address that+ reaches an account on an enforced domain skip SSO, so the account's own address is checked too.+ """+ sso_enforcement = OrganizationDomain.objects.get_sso_enforcement_for_email_address(email)+ if sso_enforcement or user is None:+ return sso_enforcement+ return OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email)++@require_http_methods(["POST"])def logout(request):clear_two_factor_session_flags(request)@@ -276,8 +290,10 @@ class LoginSerializer(serializers.Serializer):return Truedef create(self, validated_data: dict[str, str]) -> Any:+ existing_user = EmailLookupHandler.get_user_by_email(validated_data["email"], is_active=None)+# Check SSO enforcement (which happens at the domain level)- sso_enforcement = OrganizationDomain.objects.get_sso_enforcement_for_email_address(validated_data["email"])+ sso_enforcement = sso_enforcement_for_login_address(validated_data["email"], existing_user)if sso_enforcement:raise serializers.ValidationError(f"You can only login with SSO for this account ({sso_enforcement}).",@@ -286,7 +302,6 @@ class LoginSerializer(serializers.Serializer):request = self.context["request"]- existing_user = User.objects.filter(email__iexact=validated_data["email"]).first()evaluate_auth_attempt(request=request._request,email=validated_data["email"],@@ -410,6 +425,7 @@ class LoginPrecheckSerializer(serializers.Serializer):email = validated_data.get("email", "")# TODO: Refactor methods below to remove duplicate queries+ user = EmailLookupHandler.get_user_by_email(email, is_active=None)credentials = WebauthnCredential.objects.get_verified_for_email(email)webauthn_credentials = [@@ -424,7 +440,7 @@ class LoginPrecheckSerializer(serializers.Serializer):saml_available = IdentityProviderConfig.objects.get_is_saml_available_for_email(email)return {- "sso_enforcement": OrganizationDomain.objects.get_sso_enforcement_for_email_address(email),+ "sso_enforcement": sso_enforcement_for_login_address(email, user),"saml_available": saml_available,"webauthn_credentials": webauthn_credentials,**self._available_local_methods(email, saml_available=saml_available),@@ -442,8 +458,8 @@ class LoginPrecheckSerializer(serializers.Serializer):that are genuinely passwordless."""# Same lookup login itself uses (`UserManager.get_by_natural_key`), so precheck can never- # describe a different account than the one a password would authenticate: exact case first,- # then case-insensitive, and deterministic (last logged in) if case variations coexist.+ # describe a different account than the one a password would authenticate: case-insensitive,+ # and deterministic (active first, then last logged in) if case variations coexist.user = EmailLookupHandler.get_user_by_email(email)if user is None:return {"password_login_available": True, "social_providers": []}@@ -1115,9 +1131,12 @@ class PasswordResetSerializer(serializers.Serializer):def create(self, validated_data):email = validated_data.pop("email")+ # Same lookup login uses, so a reset link can never reach a different account than the+ # password it replaces.+ user = EmailLookupHandler.get_user_by_email(email)# Check SSO enforcement (which happens at the domain level)- if OrganizationDomain.objects.get_sso_enforcement_for_email_address(email):+ if sso_enforcement_for_login_address(email, user):raise serializers.ValidationError("Password reset is disabled because SSO login is enforced for this domain.",code="sso_enforced",@@ -1129,14 +1148,6 @@ class PasswordResetSerializer(serializers.Serializer):code="email_not_available",)- try:- user = User.objects.filter(is_active=True).get(email__iexact=email)- except User.DoesNotExist:- user = None- except User.MultipleObjectsReturned:- # If multiple users share the same email (different casing), use the exact match- user = User.objects.filter(is_active=True, email=email).first()-if user:user.requested_password_reset_at = datetime.datetime.now(datetime.UTC)user.save()diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex c448526a7703..bbd5396557c2 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -15,8 +15,10 @@ from django.contrib.sessions.middleware import SessionMiddlewarefrom django.core import mailfrom django.core.asgi import get_asgi_applicationfrom django.core.cache import cache+from django.db import connectionfrom django.http import HttpResponsefrom django.test import RequestFactory, SimpleTestCase, override_settings+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom asgiref.sync import sync_to_async@@ -147,6 +149,34 @@ class TestLoginPrecheckAPI(APIBaseTest):self.assertEqual(response_data["webauthn_credentials"][0]["type"], "public-key")self.assertEqual(response_data["webauthn_credentials"][0]["transports"], ["internal", "hybrid"])+ def test_login_precheck_offers_only_the_resolved_accounts_passkeys(self):+ from webauthn.helpers import bytes_to_base64url++ from posthog.models.webauthn_credential import WebauthnCredential++ abandoned = User.objects.create_and_join(self.organization, "[email protected]", None)+ in_use = User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)+ User.objects.filter(pk=in_use.pk).update(email="[email protected]", last_login=timezone.now())+ for owner, credential_id in ((abandoned, b"abandoned-credential"), (in_use, b"in-use-credential")):+ WebauthnCredential.objects.create(+ user=owner,+ credential_id=credential_id,+ label="Passkey",+ public_key=b"test-public-key",+ algorithm=-7,+ counter=0,+ transports=["internal"],+ verified=True,+ )++ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ [credential["id"] for credential in response.json()["webauthn_credentials"]],+ [bytes_to_base64url(b"in-use-credential")],+ )+def test_login_precheck_does_not_return_unverified_webauthn_credentials(self):from posthog.models.webauthn_credential import WebauthnCredential@@ -317,22 +347,21 @@ class TestLoginPrecheckAPI(APIBaseTest):response = self.client.post("/api/login/precheck", {"email": "[email protected]"})self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)- def test_login_precheck_prefers_the_exact_case_match_like_login_does(self):+ def test_login_precheck_describes_the_account_login_would_authenticate(self):# `User.email` is only unique case-*sensitively*, so variations can coexist. Precheck must- # describe the same account login would authenticate — an exact-case match wins.+ # describe the same account login would authenticate: the one still in use, whichever case+ # the person types.User.objects.create_and_join(self.organization, "[email protected]", None)with_password = User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)# `create_user` normalizes the address to lowercase, so write the variation in directly — the# accounts this guards against predate that normalization.- User.objects.filter(pk=with_password.pk).update(email="[email protected]")+ User.objects.filter(pk=with_password.pk).update(email="[email protected]", last_login=timezone.now())- response = self.client.post("/api/login/precheck", {"email": "[email protected]"})- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["password_login_available"], True)-- response = self.client.post("/api/login/precheck", {"email": "[email protected]"})- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["password_login_available"], False)+ for typed_email in ("[email protected]", "[email protected]"):+ with self.subTest(email=typed_email):+ response = self.client.post("/api/login/precheck", {"email": typed_email})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["password_login_available"], True)class TestLoginAPI(APIBaseTest):@@ -343,6 +372,20 @@ class TestLoginAPI(APIBaseTest):CONFIG_AUTO_LOGIN = False+ def test_login_resolves_the_email_through_the_indexed_lower_fold(self):+ self.user.is_email_verified = True+ self.user.save()++ with CaptureQueriesContext(connection) as queries:+ response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ # `posthog_user` has an expression index on `LOWER(email)` only, so an `UPPER` comparison+ # from `email__iexact` falls back to a sequential scan on every login attempt.+ user_lookups = [q["sql"] for q in queries.captured_queries if 'FROM "posthog_user"' in q["sql"]]+ self.assertTrue(user_lookups)+ self.assertFalse([sql for sql in user_lookups if "UPPER(" in sql])+@patch("posthoganalytics.capture")def test_user_logs_in_with_email_and_password(self, mock_capture):self.user.is_email_verified = True@@ -1602,6 +1645,22 @@ class TestPasswordResetAPI(APIBaseTest):self.assertEqual(len(mail.outbox), 1)self.assertSetEqual({",".join(outmail.to) for outmail in mail.outbox}, {self.CONFIG_EMAIL})+ def test_password_reset_reaches_the_account_login_would_authenticate(self):+ set_instance_setting("EMAIL_HOST", "localhost")+ abandoned = User.objects.create_and_join(self.organization, "[email protected]", None)+ in_use = User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)+ # `create_user` normalizes the address to lowercase, so write the variation in directly — the+ # accounts this guards against predate that normalization.+ User.objects.filter(pk=in_use.pk).update(email="[email protected]", last_login=timezone.now())++ with self.settings(CELERY_TASK_ALWAYS_EAGER=True, SITE_URL="https://my.posthog.net"):+ response = self.client.post("/api/reset/", {"email": "[email protected]"})++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertSetEqual({",".join(outmail.to) for outmail in mail.outbox}, {"[email protected]"})+ abandoned.refresh_from_db()+ self.assertIsNone(abandoned.requested_password_reset_at)+def test_reset_with_sso_available(self):"""If the user has logged in / signed up with SSO, we let them know so they don't have to reset their password.diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.pyindex 98858245bc59..90baa34f7f66 100644--- a/posthog/helpers/email_utils.py+++ b/posthog/helpers/email_utils.py@@ -17,7 +17,7 @@ from urllib.parse import quotefrom django.conf import settingsfrom django.core.cache import cachefrom django.core.exceptions import MultipleObjectsReturned-from django.db.models import Func, QuerySet, Value+from django.db.models import F, Func, QuerySet, Valuefrom django.db.models.functions import Lowerimport requests@@ -261,11 +261,15 @@ def strip_email_alias(email: str) -> str:return f"{local}@{domain}"+def _stripped_email(expression: "str | Value") -> Func:+ return Func(Lower(expression), Value(r"\+[^@]*@"), Value("@"), function="regexp_replace")++# SQL counterpart of `strip_email_alias`, lowercased. Shared by the lookup in# `EmailValidationHelper.user_exists_with_stripped_alias` and by the `user_stripped_alias_idx`# index on `User` that makes it an index lookup — Postgres only uses a functional index when# the query filters on the identical expression, so these must not drift apart.-STRIPPED_EMAIL_EXPRESSION = Func(Lower("email"), Value(r"\+[^@]*@"), Value("@"), function="regexp_replace")+STRIPPED_EMAIL_EXPRESSION = _stripped_email("email")def reject_plus_addressed_email(value: str) -> None:@@ -279,37 +283,50 @@ def reject_plus_addressed_email(value: str) -> None:class EmailLookupHandler:+ @staticmethod+ def users_matching_email(email: str, queryset: Optional[QuerySet] = None) -> QuerySet:+ """+ Return the users whose address matches `email` under the fold that email lookups share.++ The fold is `LOWER`. `iexact` would fold on `UPPER`, which maps `ı` (U+0131) to `I` and `ſ`+ (U+017F) to `S`, while `LOWER` leaves both alone; `LOWER` in turn maps `İ` (U+0130) to `i`.+ Every case fold merges some characters, so what matters is that one fold is used everywhere.++ Postgres folds both sides. Python's `str.lower()` is a different operation: it maps `İ` to+ `i` plus a combining dot, where Postgres maps it to a plain `i`, so comparing a Postgres fold+ against a Python fold stops the owner of such an address matching their own row.++ A duplicate check on a path that writes `User.email` must use this fold. If it folds+ differently, an account can store an address that this lookup then resolves to another+ account, and that account's login and password reset reach the wrong row.+ """+ from posthog.models.user import User++ base = queryset if queryset is not None else User.objects.all()+ return base.alias(_lower_email=Lower("email")).filter(_lower_email=Lower(Value(email)))+@staticmethoddef get_user_by_email(email: str, is_active: Optional[bool] = True) -> Optional["User"]:"""- Get user by email with backwards compatibility.- First tries exact match (for existing users), then case-insensitive fallback.+ Resolve an email address to a user, case-insensitively.- Handles the edge case where multiple users exist with case variations of the same email- 1. Preferring exact case match if it exists- 2. Returning the first case-insensitive match deterministically if no exact match+ Accounts created before signup lowercased emails can differ from a newer account only by+ letter case. One case-insensitive rule keeps every caller on the same account, so a login,+ a password reset, and the login precheck cannot disagree about who is signing in.+ `EmailMultiRecordHandler` chooses between case variations when more than one matches, and+ `users_matching_email` holds the fold itself."""from posthog.models.user import Userqueryset = User.objects.filter(is_active=is_active) if is_active else User.objects.all()+ matches = EmailLookupHandler.users_matching_email(email, queryset)- # First try: exact match (preserves existing behavior)- try:- return queryset.get(email=email)- except User.DoesNotExist:- pass-- # Second try: case-insensitive matchtry:- return queryset.get(email__iexact=email)+ return matches.get()except User.DoesNotExist:return Noneexcept MultipleObjectsReturned:- # Handle multiple case variations of the same email- return EmailMultiRecordHandler.handle_multiple_users(- queryset.filter(email__iexact=email), email, "user_lookup"- )+ return EmailMultiRecordHandler.handle_multiple_users(matches, email, "user_lookup")class EmailMultiRecordHandler:@@ -324,9 +341,18 @@ class EmailMultiRecordHandler:Handle multiple user records with case variations of the same email.Returns:- Last logged in user deterministically+ Last logged in user deterministically, preferring an active account"""- case_insensitive_matches = queryset.order_by("-last_login")+ # An active account wins first. Login reads deactivated rows too, and Django rejects the+ # one row it gets back when that row is inactive, so a deactivated twin that won here would+ # lock the active owner out.+ # Postgres sorts NULLs first on a DESC order, so an account that never logged in would win+ # the tie-break. The account a person still uses is the one that logged in most recently.+ # `-pk` keeps the choice stable when no candidate has ever logged in, so every caller that+ # resolves this address agrees on one account.+ case_insensitive_matches = queryset.order_by(+ F("is_active").desc(), F("last_login").desc(nulls_last=True), "-pk"+ )user_count = case_insensitive_matches.count()last_logged_in_user = case_insensitive_matches.first()@@ -366,13 +392,12 @@ class EmailValidationHelper:"""from posthog.models.user import User- # Compared lowercased because the expression below (and the index backing it) lowercases- # first, so an equality match would otherwise miss legacy mixed-case rows.- stripped = strip_email_alias(email).lower()+ # Postgres folds and strips `email` with the same expression as the column, so this check+ # treats as taken every address that `EmailLookupHandler.users_matching_email` resolves.candidates = (User.objects.filter(is_active=True).annotate(stripped_email=STRIPPED_EMAIL_EXPRESSION)- .filter(stripped_email=stripped)+ .filter(stripped_email=_stripped_email(Value(email))))if exclude_user_id is not None:candidates = candidates.exclude(pk=exclude_user_id)diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.pyindex 4372e0885810..74f5aea0eb0e 100644--- a/posthog/helpers/tests/test_email_utils.py+++ b/posthog/helpers/tests/test_email_utils.py@@ -1,8 +1,10 @@+from datetime import timedeltafrom typing import Optional, castfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, TestCase, override_settings+from django.utils import timezoneimport requestsfrom parameterized import parameterized@@ -72,6 +74,88 @@ class TestEmailLookupHandler(TestCase):finally:user.delete()+ def test_owner_finds_their_account_when_python_and_postgres_fold_differently(self) -> None:+ owner = User(email="owner@İstanbul.example", first_name="Owner", last_name="Account")+ owner.set_password("testpass123")+ owner.save()++ found_user = EmailLookupHandler.get_user_by_email("owner@İstanbul.example")++ self.assertIsNotNone(found_user)+ if found_user is not None:+ self.assertEqual(found_user.id, owner.id)++ @parameterized.expand(+ [+ ("typed_lowercase", "[email protected]"),+ ("typed_stored_case", "[email protected]"),+ ("typed_uppercase", "[email protected]"),+ ]+ )+ def test_case_variants_resolve_to_the_account_used_most_recently(self, _name: str, typed_email: str) -> None:+ abandoned = User(email="[email protected]", first_name="Abandoned", last_name="Twin")+ abandoned.set_password("testpass123")+ abandoned.last_login = timezone.now() - timedelta(days=400)+ abandoned.save()++ in_use = User(email="[email protected]", first_name="In", last_name="Use")+ in_use.set_password("testpass123")+ in_use.last_login = timezone.now()+ in_use.save()++ found_user = EmailLookupHandler.get_user_by_email(typed_email)++ self.assertIsNotNone(found_user)+ if found_user is not None:+ self.assertEqual(found_user.id, in_use.id)++ def test_account_that_never_logged_in_does_not_win_the_tie_break(self) -> None:+ never_used = User(email="[email protected]", first_name="Never", last_name="Used")+ never_used.set_password("testpass123")+ never_used.save()++ in_use = User(email="[email protected]", first_name="In", last_name="Use")+ in_use.set_password("testpass123")+ in_use.last_login = timezone.now()+ in_use.save()++ found_user = EmailLookupHandler.get_user_by_email("[email protected]")++ self.assertIsNotNone(found_user)+ if found_user is not None:+ self.assertEqual(found_user.id, in_use.id)++ @parameterized.expand(+ [+ # Postgres `UPPER` folds these onto ASCII but `LOWER` leaves them alone, so signup's+ # duplicate check accepts them as separate accounts. Resolution has to agree.+ ("dotless_i", "ceo@ıbm.com", "[email protected]"),+ ("long_s", "meſ[email protected]", "[email protected]"),+ ]+ )+ def test_homoglyph_address_does_not_capture_another_account(+ self, _name: str, homoglyph_email: str, ascii_email: str+ ) -> None:+ established = User(email=ascii_email, first_name="Established", last_name="Account")+ established.set_password("testpass123")+ established.last_login = timezone.now() - timedelta(days=30)+ established.save()++ # Signed in more recently, so it would win the tie-break if the two folded together.+ homoglyph = User(email=homoglyph_email, first_name="Homoglyph", last_name="Account")+ homoglyph.set_password("testpass123")+ homoglyph.last_login = timezone.now()+ homoglyph.save()++ found_ascii = EmailLookupHandler.get_user_by_email(ascii_email)+ found_homoglyph = EmailLookupHandler.get_user_by_email(homoglyph_email)++ self.assertIsNotNone(found_ascii)+ self.assertIsNotNone(found_homoglyph)+ if found_ascii is not None and found_homoglyph is not None:+ self.assertEqual(found_ascii.id, established.id)+ self.assertEqual(found_homoglyph.id, homoglyph.id)+class TestEmailValidationHelper(TestCase):def test_user_exists_no_user(self):@@ -155,9 +239,12 @@ class TestUserExistsWithStrippedAlias(TestCase):# Guards the SQL side: the stored column is lowercased before stripping, so a legacy# mixed-case row still matches.("stored_mixed_case", "[email protected]", "[email protected]"),- # Guards the Python side: the compared value is lowercased too. An equality match+ # Guards the input side: the compared value is lowercased too. An equality match# against the lowercased expression silently returns False without it.("looked_up_mixed_case", "[email protected]", "[email protected]"),+ # Guards the fold: Postgres lowercases `İ` (U+0130) to `i`, so login resolves this address+ # to the stored one, and signup and email change must treat it as taken.+ ("looked_up_dotted_capital_i", "[email protected]", "bill@vİctim.example"),])def test_matches_regardless_of_case(self, _name, stored_email, looked_up_email):diff --git a/posthog/migrations/1352_email_lookup_indexes.py b/posthog/migrations/1352_email_lookup_indexes.pynew file mode 100644index 000000000000..70e65ad8e692--- /dev/null+++ b/posthog/migrations/1352_email_lookup_indexes.py@@ -0,0 +1,36 @@+from django.db import migrations, models+from django.db.models.functions import Lower, Upper++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ """+ Case-insensitive email lookups scan the whole table.++ Login, password reset, and the login precheck resolve an address by its `LOWER()` fold.+ The invite lookups use `target_email__iexact`, which Django compiles to `UPPER()`. Neither+ the plain unique btree on `posthog_user.email` nor `posthog_organizationinvite`'s btree on+ `target_email` serves an expression, so each lookup falls back to a sequential scan whose+ cost grows with the table.++ Each index matches the expression its own callers emit, so those lookups become index scans.+ posthog_user is a hot table, so both build with CREATE INDEX CONCURRENTLY via+ SafeAddIndexConcurrently, which takes a SHARE UPDATE EXCLUSIVE lock and does not block reads+ or writes.+ """++ atomic = False++ dependencies = [("posthog", "1351_drop_persistedfolder_table")]++ operations = [+ SafeAddIndexConcurrently(+ model_name="user",+ index=models.Index(Lower("email"), name="posthog_user_lower_email_idx"),+ ),+ SafeAddIndexConcurrently(+ model_name="organizationinvite",+ index=models.Index(Upper("target_email"), name="orginvite_upper_email_idx"),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 6af560e16578..7cbe83dbe09c 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1351_drop_persistedfolder_table+1352_email_lookup_indexesdiff --git a/posthog/models/organization_invite.py b/posthog/models/organization_invite.pyindex 9298db58cc1f..81bfb1ffb25e 100644--- a/posthog/models/organization_invite.py+++ b/posthog/models/organization_invite.py@@ -2,6 +2,7 @@ from datetime import timedeltafrom typing import TYPE_CHECKING, Optional, castfrom django.db import models, transaction+from django.db.models.functions import Upperfrom django.db.models.signals import pre_deletefrom django.dispatch import receiverfrom django.utils import timezone@@ -93,6 +94,12 @@ class OrganizationInvite(ModelActivityMixin, UUIDTModel):),)+ class Meta:+ indexes = [+ # Serves `target_email__iexact`, which Django compiles to `UPPER(target_email::text)`.+ models.Index(Upper("target_email"), name="orginvite_upper_email_idx"),+ ]+def validate(self,*,diff --git a/posthog/models/test/test_user_model.py b/posthog/models/test/test_user_model.pyindex f2e41932cf0a..4f1754ee5977 100644--- a/posthog/models/test/test_user_model.py+++ b/posthog/models/test/test_user_model.py@@ -194,9 +194,21 @@ class TestUser(BaseTest):newer.last_login = datetime.datetime(2025, 1, 1, tzinfo=datetime.UTC)newer.save(update_fields=["last_login"])- # Exact match wins over case-insensitive fallback when a row matches the typed casing.- self.assertEqual(User.objects.get_by_natural_key("[email protected]"), older)- self.assertEqual(User.objects.get_by_natural_key("[email protected]"), newer)-- # When the typed casing matches no row exactly, fallback picks the most recent login.- self.assertEqual(User.objects.get_by_natural_key("[email protected]"), newer)+ # Every typed casing resolves to the account in active use, so a login, a password reset,+ # and the login precheck cannot disagree about who is signing in.+ with self.subTest(email=typed_email):+ self.assertEqual(User.objects.get_by_natural_key(typed_email), newer)++ def test_get_by_natural_key_prefers_the_active_case_variant(self):+ active = User.objects.create(email="[email protected]")+ active.last_login = datetime.datetime(2024, 1, 1, tzinfo=datetime.UTC)+ active.save(update_fields=["last_login"])++ deactivated = User.objects.create(email="[email protected]", is_active=False)+ deactivated.last_login = datetime.datetime(2025, 1, 1, tzinfo=datetime.UTC)+ deactivated.save(update_fields=["last_login"])++ for typed_email in ("[email protected]", "[email protected]"):+ with self.subTest(email=typed_email):+ self.assertEqual(User.objects.get_by_natural_key(typed_email), active)diff --git a/posthog/models/user.py b/posthog/models/user.pyindex 061a37e5d5f7..8c626c4f74eb 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, NoReturn, Optional, TypedDict, castfrom django.contrib.auth.models import AbstractUser, BaseUserManagerfrom django.core.management.base import CommandErrorfrom django.db import models, transaction+from django.db.models.functions import Lowerfrom django.db.models.signals import pre_savefrom django.dispatch import receiverfrom django.utils.translation import gettext_lazy as _@@ -343,6 +344,8 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignoreverbose_name_plural = _("users")indexes = [models.Index(STRIPPED_EMAIL_EXPRESSION, name="user_stripped_alias_idx"),+ # Serves the `LOWER(email)` fold `EmailLookupHandler.get_user_by_email` resolves on.+ models.Index(Lower("email"), name="posthog_user_lower_email_idx"),]# Remove unused attributes from `AbstractUser`diff --git a/posthog/models/webauthn_credential.py b/posthog/models/webauthn_credential.pyindex a521b7ca3457..0651d7353ac8 100644--- a/posthog/models/webauthn_credential.py+++ b/posthog/models/webauthn_credential.py@@ -1,5 +1,6 @@from django.db import models+from posthog.helpers.email_utils import EmailLookupHandlerfrom posthog.models.utils import UUIDModel@@ -12,9 +13,16 @@ class WebAuthnCredentialManager(models.Manager):def get_verified_for_email(self, email: str):"""- Returns all verified credentials for a user by email (single query).+ Returns the verified credentials of the account this email address resolves to.++ Resolves through `EmailLookupHandler`, the same lookup login and the rest of the login+ precheck use, so the passkeys offered belong to the account the precheck describes rather+ than to every case variant of the address."""- return self.filter(user__email__iexact=email, user__is_active=True, verified=True)+ user = EmailLookupHandler.get_user_by_email(email)+ if user is None:+ return self.none()+ return self.filter(user=user, verified=True)class WebauthnCredential(UUIDModel):