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(auth): normalize a staged email and re-check it at promotion (#99939)

Yasen6c14ec08fe33
diff --git a/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.py b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.py
new file mode 100644
index 000000000000..5ec1fa3ac482
--- /dev/null
+++ b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.py
@@ -0,0 +1,40 @@
+# Test cases for user-email-lookups-use-the-shared-fold rule.
+# ruff: noqa: F821, E501
+from posthog.helpers.email_utils import EmailLookupHandler
+from posthog.models import User
+
+
+def flagged_exists_gate(email: str):
+ # ruleid: user-email-lookups-use-the-shared-fold
+ return User.objects.filter(email__iexact=email).exists()
+
+
+def flagged_get(email: str):
+ # ruleid: user-email-lookups-use-the-shared-fold
+ return User.objects.get(email__iexact=email, is_active=True)
+
+
+def flagged_on_a_queryset(queryset, email: str):
+ # ruleid: user-email-lookups-use-the-shared-fold
+ return queryset.filter(email__iexact=email).first()
+
+
+def flagged_exact_match(email: str):
+ # An exact match misses every address that folds onto the same account.
+ # ruleid: user-email-lookups-use-the-shared-fold
+ return User.objects.filter(email=email).first()
+
+
+def ok_shared_fold_queryset(email: str):
+ # ok: user-email-lookups-use-the-shared-fold
+ return EmailLookupHandler.users_matching_email(email).exists()
+
+
+def ok_shared_fold_single_account(email: str):
+ # ok: user-email-lookups-use-the-shared-fold
+ return EmailLookupHandler.get_user_by_email(email, is_active=None)
+
+
+def ok_invite_lookup(organization, target_email: str):
+ # ok: user-email-lookups-use-the-shared-fold
+ return organization.invites.filter(target_email__iexact=target_email).first()
diff --git a/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.yaml b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.yaml
new file mode 100644
index 000000000000..1151ac6d875e
--- /dev/null
+++ b/.semgrep/rules/devex/user-email-lookups-use-the-shared-fold.yaml
@@ -0,0 +1,45 @@
+rules:
+ - id: user-email-lookups-use-the-shared-fold
+ message: |
+ Resolve a `User` by address through `EmailLookupHandler`, not `email__iexact`.
+
+ Django compiles `email__iexact` to Postgres `UPPER`, and every account lookup
+ resolves on `LOWER`. The two folds disagree: `UPPER` maps `ı` (U+0131) to `I` and
+ `ſ` (U+017F) to `S`, while `LOWER` leaves both alone and maps `İ` (U+0130) to a
+ plain `i`. A gate that reads one fold therefore admits an address that the login
+ lookup later resolves onto somebody else's account.
+
+ Use `EmailLookupHandler.get_user_by_email(...)` for one account, or
+ `EmailLookupHandler.users_matching_email(...)` for the queryset. Both fold the
+ way the lookups do, and the `posthog_user_lower_email_idx` index serves them.
+
+ Invites are not in scope: `target_email__iexact` has its own `UPPER` index.
+
+ Suppress a legitimate exception with
+ `# nosemgrep: user-email-lookups-use-the-shared-fold -- <reason>`.
+ languages: [python]
+ severity: ERROR
+ patterns:
+ - pattern-either:
+ - pattern: User.objects.filter(..., email__iexact=$VALUE, ...)
+ - pattern: User.objects.get(..., email__iexact=$VALUE, ...)
+ - pattern: User.objects.filter(..., email=$VALUE, ...)
+ - pattern: User.objects.get(..., email=$VALUE, ...)
+ - pattern: $QS.filter(..., email__iexact=$VALUE, ...)
+ - pattern: $QS.exclude(..., email__iexact=$VALUE, ...)
+ paths:
+ # The paths where an address decides which account a request reaches.
+ include:
+ - /ee/api/agentic_provisioning/**/*.py
+ - /ee/api/authentication.py
+ - /ee/api/scim/**/*.py
+ - /ee/partners/stripe/api/provisioning/**/*.py
+ - /posthog/api/authentication.py
+ - /posthog/api/id_jag.py
+ - /posthog/api/signup.py
+ - /posthog/api/user.py
+ - /posthog/api/webauthn.py
+ - /posthog/models/user.py
+ exclude:
+ - '**/test_*.py'
+ - '**/tests/**'
diff --git a/.semgrep/rules/devex/user-email-writes-use-the-shared-fold.py b/.semgrep/rules/devex/user-email-writes-use-the-shared-fold.py
new file mode 100644
index 000000000000..75dd572b53b3
--- /dev/null
+++ b/.semgrep/rules/devex/user-email-writes-use-the-shared-fold.py
@@ -0,0 +1,39 @@
+# Test cases for user-email-writes-use-the-shared-fold rule.
+# ruff: noqa: F821, E501
+from posthog.helpers.email_utils import EmailNormalizer
+
+
+def flagged_raw_write(user, email: str):
+ # ruleid: user-email-writes-use-the-shared-fold
+ user.email = email
+ user.save()
+
+
+def flagged_python_fold(user, email: str):
+ # ruleid: user-email-writes-use-the-shared-fold
+ user.email = email.lower()
+ user.save()
+
+
+def flagged_staged_write(user, email: str):
+ # ruleid: user-email-writes-use-the-shared-fold
+ user.pending_email = email
+ user.save()
+
+
+def ok_normalized_write(user, email: str):
+ # ok: user-email-writes-use-the-shared-fold
+ user.email = EmailNormalizer.normalize(email)
+ user.save()
+
+
+def ok_clearing_the_staged_address(user):
+ # ok: user-email-writes-use-the-shared-fold
+ user.pending_email = None
+ user.save()
+
+
+class Claims:
+ def __init__(self, email: str):
+ # ok: user-email-writes-use-the-shared-fold
+ self.email = email
diff --git a/.semgrep/rules/devex/user-email-writes-use-the-shared-fold.yaml b/.semgrep/rules/devex/user-email-writes-use-the-shared-fold.yaml
new file mode 100644
index 000000000000..e60a43cd6fa9
--- /dev/null
+++ b/.semgrep/rules/devex/user-email-writes-use-the-shared-fold.yaml
@@ -0,0 +1,46 @@
+rules:
+ - id: user-email-writes-use-the-shared-fold
+ message: |
+ A write to `User.email` must store the fold the lookups resolve on —
+ `EmailNormalizer.normalize(...)`.
+
+ Every address lookup (login, password reset, the login precheck, the duplicate
+ checks) resolves through Postgres `LOWER`. A path that stores the address as
+ typed leaves rows that differ only by case, and those rows then compete for the
+ same lookup. `posthog_user.email` is unique on the exact string, so the database
+ does not stop them.
+
+ Use `EmailNormalizer.normalize(value)` on the write, and resolve any duplicate
+ check through `EmailLookupHandler.users_matching_email(...)` rather than an
+ equality filter, because that helper folds both sides the way Postgres does.
+
+ Do not reach for `str.lower()` instead: it folds `İ` (U+0130) to `i` plus a
+ combining dot where Postgres folds it to a plain `i`, so the stored address then
+ matches nothing a person can type.
+
+ Suppress a legitimate exception with
+ `# nosemgrep: user-email-writes-use-the-shared-fold -- <reason>`.
+ languages: [python]
+ severity: ERROR
+ patterns:
+ - pattern-either:
+ - pattern: $OBJ.email = $VALUE
+ - pattern: $OBJ.pending_email = $VALUE
+ - pattern-not: $OBJ.email = EmailNormalizer.normalize(...)
+ - pattern-not: $OBJ.pending_email = EmailNormalizer.normalize(...)
+ # Clearing a staged address stores no address at all.
+ - pattern-not: $OBJ.pending_email = None
+ # A constructor assigning its own argument holds no `User` row.
+ - pattern-not: self.email = $VALUE
+ - pattern-not: self.pending_email = $VALUE
+ paths:
+ include:
+ - /ee/**/*.py
+ - /posthog/**/*.py
+ - /products/**/*.py
+ exclude:
+ - /posthog/helpers/email_utils.py
+ - /posthog/models/user.py
+ - '**/test_*.py'
+ - '**/tests/**'
+ - /products/posthog_ai/eval_harness/**
diff --git a/ee/api/agentic_provisioning/accounts.py b/ee/api/agentic_provisioning/accounts.py
index d449bdb1737d..36544da7ed05 100644
--- a/ee/api/agentic_provisioning/accounts.py
+++ b/ee/api/agentic_provisioning/accounts.py
@@ -14,6 +14,7 @@ from django.utils import timezone
from posthog.api.authentication import password_reset_token_generator
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.models.oauth import OAuthApplication
from posthog.models.team.team import Team
from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
@@ -242,7 +243,7 @@ def handle_new_user(
is_email_verified=False,
)
except IntegrityError:
- existing = User.objects.filter(email=email).first()
+ existing = EmailLookupHandler.get_user_by_email(email, is_active=None)
if existing:
capture_provisioning_event("account_request", "race_condition_existing_user", region=region)
return handle_existing_user(
diff --git a/ee/api/agentic_provisioning/views/account_requests.py b/ee/api/agentic_provisioning/views/account_requests.py
index a50aad04af0c..ff49d3266967 100644
--- a/ee/api/agentic_provisioning/views/account_requests.py
+++ b/ee/api/agentic_provisioning/views/account_requests.py
@@ -14,7 +14,7 @@ from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.models.user import User
+from posthog.helpers.email_utils import EmailLookupHandler
from posthog.scopes import effective_ceiling
from ee.api.agentic_provisioning.accounts import handle_existing_user, handle_new_user
@@ -95,7 +95,7 @@ class AccountRequestsView(ProvisioningAPIView):
region = (configuration.get("region") or "US").upper()
- existing_user = User.objects.filter(email=email).first()
+ existing_user = EmailLookupHandler.get_user_by_email(email, is_active=None)
if existing_user:
return Response(
diff --git a/ee/api/authentication.py b/ee/api/authentication.py
index 07c59931235e..96e2c40c2472 100644
--- a/ee/api/authentication.py
+++ b/ee/api/authentication.py
@@ -35,6 +35,7 @@ from social_django.utils import load_backend, load_strategy
from posthog.cloud_utils import get_cached_instance_license
from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
+from posthog.helpers.email_utils import EmailLookupHandler
from posthog.models.identity_provider_config import IdentityProviderConfig, has_verified_organization_domain_q
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -49,7 +50,6 @@ saml_logger = structlog.get_logger("posthog.auth.saml")
def _saml_log_context(email: str, organization_id: UUID | None = None) -> dict[str, Any]:
- from posthog.models.user import User
ctx: dict[str, Any] = {
"masked_email": mask_email(email),
@@ -57,7 +57,7 @@ def _saml_log_context(email: str, organization_id: UUID | None = None) -> dict[s
}
try:
- user = User.objects.filter(email__iexact=email).first()
+ user = EmailLookupHandler.get_user_by_email(email, is_active=None)
if user:
ctx["user_id"] = str(user.id)
if organization_id:
diff --git a/ee/api/scim/test/test_users_api.py b/ee/api/scim/test/test_users_api.py
index b2e9aed0f08b..35a002099854 100644
--- a/ee/api/scim/test/test_users_api.py
+++ b/ee/api/scim/test/test_users_api.py
@@ -187,6 +187,28 @@ class TestSCIMUsersAPI(APILicensedTest):
assert scim_user.active is True
assert scim_user.identity_provider == SCIMProvisionedUser.IdentityProvider.OTHER
+ def test_create_resolves_an_address_that_folds_onto_an_existing_account(self):
+ # Postgres LOWER folds `İ` onto a plain `i`, so provisioning this address must reach the
+ # account already holding the ASCII spelling instead of standing up a second row that
+ # competes with it for every login.
+ existing = User.objects.create_user(
+ email="[email protected]", password=None, first_name="Existing", is_email_verified=True
+ )
+ user_data = {
+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ "userName": "İ[email protected]",
+ "name": {"givenName": "New", "familyName": "User"},
+ "emails": [{"value": "İ[email protected]", "primary": True}],
+ "active": True,
+ }
+
+ self.client.post(
+ f"/scim/v2/{self.config.scim_slug}/Users", data=user_data, content_type="application/scim+json"
+ )
+
+ assert User.objects.filter(email__in=["[email protected]", "İ[email protected]"]).count() == 1
+ assert User.objects.get(pk=existing.pk).email == "[email protected]"
+
def test_existing_user_is_added_to_org(self):
# Create user in different org
other_org = Organization.objects.create(name="Other Org")
diff --git a/ee/api/scim/user.py b/ee/api/scim/user.py
index 4a1890e5cdf9..71b0b8751eed 100644
--- a/ee/api/scim/user.py
+++ b/ee/api/scim/user.py
@@ -7,7 +7,7 @@ from django_scim import constants
from django_scim.adapters import SCIMUser
from scim2_filter_parser.attr_paths import AttrPath
-from posthog.helpers.email_utils import EmailLookupHandler
+from posthog.helpers.email_utils import EmailLookupHandler, EmailNormalizer
from posthog.models import Organization, OrganizationMembership, User
from posthog.models.identity_provider_config import IdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
@@ -174,7 +174,7 @@ class PostHogSCIMUser(SCIMUser):
active = data.get("active", True)
with transaction.atomic():
- user = User.objects.filter(email__iexact=email).first()
+ user = EmailLookupHandler.get_user_by_email(email, is_active=None)
# Check if already SCIM-provisioned for this IdP config
if user and SCIMProvisionedUser.objects.record_for(user=user, config=config) is not None:
@@ -248,7 +248,7 @@ class PostHogSCIMUser(SCIMUser):
self.obj.first_name = name_data.get("givenName", "")
self.obj.last_name = name_data.get("familyName", "")
- self.obj.email = email
+ self.obj.email = EmailNormalizer.normalize(email)
self.obj.save()
SCIMProvisionedUser.objects.upsert(
@@ -359,7 +359,7 @@ class PostHogSCIMUser(SCIMUser):
_validate_email_domain_is_verified(email, self._config.organization)
# Org must also own the current email domain to prevent cross-tenant account takeover
_validate_email_domain_is_verified(self.obj.email, self._config.organization)
- self.obj.email = email
+ self.obj.email = EmailNormalizer.normalize(email)
def _write_attribute(self, path: AttrPath, value: Union[str, list, dict]) -> bool:
"""
diff --git a/ee/partners/stripe/api/provisioning/core.py b/ee/partners/stripe/api/provisioning/core.py
index f48f71e1ca09..f4a1cd48196c 100644
--- a/ee/partners/stripe/api/provisioning/core.py
+++ b/ee/partners/stripe/api/provisioning/core.py
@@ -22,6 +22,7 @@ import structlog
from posthog.api.authentication import password_reset_token_generator
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.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.team.team import Team
@@ -265,7 +266,7 @@ def handle_new_user(
is_email_verified=False,
)
except IntegrityError:
- existing = User.objects.filter(email=email).first()
+ existing = EmailLookupHandler.get_user_by_email(email, is_active=None)
if existing:
capture_provisioning_event("account_request", "race_condition_existing_user", region=region)
return handle_existing_user(
diff --git a/ee/partners/stripe/api/provisioning/views.py b/ee/partners/stripe/api/provisioning/views.py
index df2eed4e206a..722027f791b1 100644
--- a/ee/partners/stripe/api/provisioning/views.py
+++ b/ee/partners/stripe/api/provisioning/views.py
@@ -35,6 +35,7 @@ from rest_framework.response import Response
from rest_framework.views import APIView
from posthog.exceptions_capture import capture_exception
+from posthog.helpers.email_utils import EmailLookupHandler
from posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken
from posthog.models.team.team import Team
from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
@@ -240,7 +241,7 @@ class AccountRequestsView(StripeProvisioningAPIView):
except (ValueError, TypeError):
raise SpecError("invalid_request", "configuration.team_id must be an integer", request_id=request_id)
- existing_user = User.objects.filter(email=email).first()
+ existing_user = EmailLookupHandler.get_user_by_email(email, is_active=None)
if existing_user:
return Response(
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index 80169ca825c3..721b91d59e95 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -605,9 +605,8 @@ class DevLoginSerializer(serializers.Serializer):
return self._create_fresh_account()
request = self.context["request"]
- try:
- user = User.objects.get(email__iexact=validated_data["email"], is_active=True)
- except User.DoesNotExist:
+ user = EmailLookupHandler.get_user_by_email(validated_data["email"])
+ if user is None:
raise serializers.ValidationError("User not found", code="user_not_found")
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index de43d52f193b..f5b2bd793f28 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -23,6 +23,7 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.dataclasses import frozen
+from posthog.helpers.email_utils import EmailLookupHandler
from posthog.models.identity_provider_config import IdentityProviderConfig
from posthog.models.user import User
from posthog.scopes import get_oauth_scopes_supported
@@ -401,10 +402,12 @@ def _verify_and_extract_id_jag_token(assertion: str) -> _VerifiedIdJag:
verified_email = claims.get("email") or claims.get("sub") or ""
# Membership must match the configuration's organization because the access token is scoped to it.
- is_member = User.objects.filter(
- is_active=True,
- email__iexact=verified_email,
- organization_membership__organization_id=idp_config.organization_id,
+ is_member = EmailLookupHandler.users_matching_email(
+ verified_email,
+ User.objects.filter(
+ is_active=True,
+ organization_membership__organization_id=idp_config.organization_id,
+ ),
).exists()
if not is_member:
raise InvalidGrantError(
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index da79f42a3b18..3df9aaa477cb 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -1012,6 +1012,63 @@ class TestUserAPI(APIBaseTest):
assert self.user.email == "[email protected]"
assert self.user.pending_email is None
+ @patch("posthog.api.user.is_email_available", return_value=True)
+ @patch("posthog.api.email_verification.send_email_verification_code")
+ def test_email_change_stages_the_normalized_address(self, mock_send_code, _mock_is_email_available):
+ self.user.email = "[email protected]"
+ self.user.save()
+
+ response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})
+
+ assert response.status_code == status.HTTP_200_OK
+ self.user.refresh_from_db()
+ assert self.user.pending_email == "[email protected]"
+ assert mock_send_code.call_args[0][2] == "[email protected]"
+
+ @patch("posthog.api.user.is_email_available", return_value=False)
+ def test_email_change_without_email_configured_writes_the_normalized_address(self, _mock_is_email_available):
+ self.user.email = "[email protected]"
+ self.user.save()
+
+ response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})
+
+ assert response.status_code == status.HTTP_200_OK
+ self.user.refresh_from_db()
+ assert self.user.email == "[email protected]"
+
+ @patch("posthog.api.user.is_email_available", return_value=True)
+ @patch("posthog.api.email_verification.send_email_verification_code")
+ def test_email_edit_differing_by_a_non_ascii_capital_still_needs_verification(
+ self, mock_send_code, _mock_is_email_available
+ ):
+ # Python lowercases `É`, so a guard that compares on `str.lower()` reads this edit as
+ # unchanged and writes it straight to `email`, with no code and no SSO check.
+ self.user.email = "bill@josé.example"
+ self.user.save()
+
+ response = self.client.patch("/api/users/@me/", {"email": "bill@JOSÉ.example"})
+
+ assert response.status_code == status.HTTP_200_OK
+ self.user.refresh_from_db()
+ assert self.user.email == "bill@josé.example"
+ assert self.user.pending_email == "bill@josÉ.example"
+ mock_send_code.assert_called_once()
+
+ @parameterized.expand([("email_configured", True), ("no_email_configured", False)])
+ def test_email_change_rejected_when_a_deactivated_account_holds_the_folded_address(self, _name, email_available):
+ self.user.email = "[email protected]"
+ self.user.save()
+ User.objects.create(email="[email protected]", first_name="Gone", is_active=False)
+
+ with patch("posthog.api.user.is_email_available", return_value=email_available):
+ response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "unique"
+ self.user.refresh_from_db()
+ assert self.user.email == "[email protected]"
+ assert self.user.pending_email is None
+
@patch("posthog.api.user.is_email_available", return_value=False)
def test_email_change_allowed_when_dropping_own_plus_alias(self, _mock_is_email_available):
# The collision check must skip the editor's own row, or a legacy alias holder can never clean it up.
@@ -1268,26 +1325,35 @@ class TestUserAPI(APIBaseTest):
assert self.user.is_email_verified is True
mock_login.assert_not_called()
- @patch("posthog.api.user.is_email_available", return_value=True)
+ @parameterized.expand(
+ [
+ ("email_configured", True, "[email protected]"),
+ ("no_email_configured", False, "[email protected]"),
+ # A legacy row holds the address in the case it was typed in years ago.
+ ("legacy_stored_uppercase", True, "[email protected]"),
+ ]
+ )
@patch("posthog.tasks.email.send_email_change_emails.delay")
def test_no_notifications_when_user_email_is_changed_and_only_case_differs(
- self, mock_send_email_change_emails, mock_is_email_available
+ self, _name, email_available, stored_email, mock_send_email_change_emails
):
- self.user.email = "[email protected]"
+ self.user.email = stored_email
self.user.save()
- response = self.client.patch(
- "/api/users/@me/",
- {
- "email": "[email protected]",
- },
- )
+ with patch("posthog.api.user.is_email_available", return_value=email_available) as mock_is_email_available:
+ response = self.client.patch(
+ "/api/users/@me/",
+ {
+ "email": "[email protected]",
+ },
+ )
response_data = response.json()
self.user.refresh_from_db()
assert response.status_code == status.HTTP_200_OK
- assert response_data["email"] == "[email protected]"
- assert self.user.email == "[email protected]"
+ assert response_data["email"] == stored_email
+ assert self.user.email == stored_email
+ assert self.user.pending_email is None
mock_is_email_available.assert_not_called()
mock_send_email_change_emails.assert_not_called()
@@ -3269,10 +3335,18 @@ class TestEmailVerificationCodeAPI(APIBaseTest):
self.assertEqual(response.json(), {"success": True, "requires_login": True})
assert self.client.session.get("_auth_user_id") is None
- @parameterized.expand([("verified", True), ("legacy_never_verified", None)])
- def test_email_change_code_goes_to_the_pending_address_and_completes_the_swap(self, _name, is_email_verified):
+ @parameterized.expand(
+ [
+ ("verified", True, "[email protected]"),
+ ("legacy_never_verified", None, "[email protected]"),
+ ("staged_before_normalization", True, "[email protected]"),
+ ]
+ )
+ def test_email_change_code_goes_to_the_pending_address_and_completes_the_swap(
+ self, _name, is_email_verified, staged_email
+ ):
self.user.is_email_verified = is_email_verified
- self.user.pending_email = "[email protected]"
+ self.user.pending_email = staged_email
self.user.save()
with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:
@@ -3280,7 +3354,7 @@ class TestEmailVerificationCodeAPI(APIBaseTest):
response = self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})
self.assertEqual(response.status_code, status.HTTP_200_OK)
code = mock_send.call_args[0][1]
- assert mock_send.call_args[0][2] == "[email protected]"
+ assert mock_send.call_args[0][2] == staged_email
response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -3288,6 +3362,42 @@ class TestEmailVerificationCodeAPI(APIBaseTest):
assert self.user.email == "[email protected]"
assert self.user.pending_email is None
+ @parameterized.expand(
+ [
+ # A case variant passes the unique index on `email`, so only the fold check catches it.
+ ("active_case_variant", "[email protected]", True),
+ # An exact match reaches the write, because the fold check reads active accounts only.
+ ("deactivated_exact_match", "[email protected]", False),
+ ]
+ )
+ def test_pending_address_taken_while_the_change_waited_is_not_promoted(self, _name, other_email, other_is_active):
+ self.user.is_email_verified = True
+ self.user.pending_email = "[email protected]"
+ self.user.save()
+ account_email = self.user.email
+
+ with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:
+ with self.settings(CELERY_TASK_ALWAYS_EAGER=True):
+ self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})
+ code = mock_send.call_args[0][1]
+
+ User.objects.create(email=other_email, first_name="Other", is_active=other_is_active)
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "email_taken")
+ self.user.refresh_from_db()
+ assert self.user.email == account_email
+ # The staged address stays, so a repeat request cannot read as a completed change.
+ assert self.user.pending_email == "[email protected]"
+
+ repeat = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+
+ self.assertEqual(repeat.status_code, status.HTTP_400_BAD_REQUEST)
+ self.user.refresh_from_db()
+ assert self.user.email == account_email
+
def test_signup_code_does_not_authorize_an_email_change(self):
code = self._request_code()
self.user.is_email_verified = True
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 3a35b4e4f3a8..1ba880bfc2c6 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -7,14 +7,14 @@ import urllib.parse
from base64 import b32encode
from binascii import unhexlify
from datetime import UTC, datetime, timedelta
-from typing import Any, Optional, cast
+from typing import Any, NoReturn, Optional, cast
from django.conf import settings
from django.contrib.auth import login, update_session_auth_hash
from django.contrib.auth.password_validation import validate_password
from django.core.cache import cache
from django.core.exceptions import ValidationError
-from django.db import transaction
+from django.db import IntegrityError, transaction
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.utils import timezone as django_timezone
@@ -86,6 +86,7 @@ from posthog.event_usage import (
)
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import (
+ EmailLookupHandler,
EmailNormalizer,
EmailValidationHelper,
reject_plus_addressed_email,
@@ -403,16 +404,26 @@ class UserSerializer(serializers.ModelSerializer):
return validate_display_name(value)
def validate_email(self, value: str) -> str:
- if self.instance and value.lower() == self.instance.email.lower():
- # Unchanged — don't re-validate a legacy '+' address on an unrelated profile edit.
- return value
+ normalized = EmailNormalizer.normalize(value)
+ if self.instance and normalized == EmailNormalizer.normalize(self.instance.email):
+ # Unchanged — don't re-validate a legacy '+' address on an unrelated profile edit. The
+ # stored string is returned as it is, because an edit of the case alone reaches no
+ # verification and so cannot rewrite the address a person signs in with.
+ return self.instance.email
reject_plus_addressed_email(value)
# Excluding the editor lets a legacy '+' account holder drop their own alias.
if EmailValidationHelper.user_exists_with_stripped_alias(
value, exclude_user_id=self.instance.pk if self.instance else None
):
raise serializers.ValidationError("There is already an account with this email address.", code="unique")
- return value
+ # The alias check above reads active accounts, so a deactivated holder of the same folded
+ # address passes it. Resolve on the fold every lookup shares, across every account.
+ holders = EmailLookupHandler.users_matching_email(normalized, User.objects.all())
+ if self.instance:
+ holders = holders.exclude(pk=self.instance.pk)
+ if holders.exists():
+ raise serializers.ValidationError("There is already an account with this email address.", code="unique")
+ return normalized
def get_has_password(self, instance: User) -> bool:
return bool(instance.password) and instance.has_usable_password()
@@ -698,9 +709,11 @@ class UserSerializer(serializers.ModelSerializer):
validated_data["current_team"] = current_team
validated_data["current_organization"] = current_team.organization
+ # Fold both sides: `validate_email` hands back the stored address for an edit of the case
+ # alone, and a legacy row can hold that address in any case.
if (
"email" in validated_data
- and validated_data["email"].lower() != instance.email.lower()
+ and EmailNormalizer.normalize(validated_data["email"]) != EmailNormalizer.normalize(instance.email)
and is_email_available()
):
new_email = validated_data["email"]
@@ -731,7 +744,7 @@ class UserSerializer(serializers.ModelSerializer):
code="sso_enforced_new_email",
)
validated_data.pop("email", None) # staged as pending_email below, not written to `email` directly
- instance.pending_email = new_email
+ instance.pending_email = EmailNormalizer.normalize(new_email)
instance.save(update_fields=["pending_email"])
# The code is bound to the captured address, so a concurrent email change cannot
# redirect this code: once a different address is staged, the code stops verifying.
@@ -915,6 +928,20 @@ class UserGithubLoginSerializer(serializers.Serializer):
)
+def refuse_pending_email_promotion() -> NoReturn:
+ """Refuse the change, because the address is no longer free.
+
+ The staged address stays. Clearing it would leave a verified account with nothing staged, which
+ is the state the replay shortcut in `verify_email` reads as a completed change, so the next
+ request would report success for a change that never happened. Keeping it staged also keeps
+ `cancel_email_change_request` available as the way out.
+ """
+ raise serializers.ValidationError(
+ {"email": ["Another account now uses this email address. Start the change again with a different address."]},
+ code="email_taken",
+ )
+
+
@extend_schema(extensions={"x-product": "core"})
@extend_schema_view(
retrieve=extend_schema(
@@ -1135,12 +1162,26 @@ class UserViewSet(
# and in the verifier.
if user.pending_email and user.is_email_verified is not False:
old_email = user.email
- with transaction.atomic():
- user.email = user.pending_email
- user.pending_email = None
- user.save(update_fields=["email", "pending_email"])
- # Delete social auth so the old external identity can't keep logging in.
- UserSocialAuth.objects.filter(user=user).delete()
+ # `pending_email` holds whatever case the change was staged in.
+ new_email = EmailNormalizer.normalize(user.pending_email)
+ # Anyone can claim the address while the change waits for this code.
+ taken = (
+ EmailValidationHelper.user_exists_with_stripped_alias(new_email, exclude_user_id=user.pk)
+ or EmailLookupHandler.users_matching_email(new_email, User.objects.all()).exclude(pk=user.pk).exists()
+ )
+ if taken:
+ refuse_pending_email_promotion()
+ try:
+ with transaction.atomic():
+ user.email = EmailNormalizer.normalize(new_email)
+ user.pending_email = None
+ user.save(update_fields=["email", "pending_email"])
+ # Delete social auth so the old external identity can't keep logging in.
+ UserSocialAuth.objects.filter(user=user).delete()
+ except IntegrityError:
+ # A row that appeared since the check above reaches this write.
+ user.refresh_from_db()
+ refuse_pending_email_promotion()
send_email_change_emails.delay(datetime.now(UTC).isoformat(), user.first_name, old_email, user.email)
revoke_other_sessions_for_request(request, user)
diff --git a/posthog/api/webauthn.py b/posthog/api/webauthn.py
index 201b927f96ae..d08ec07de3cc 100644
--- a/posthog/api/webauthn.py
+++ b/posthog/api/webauthn.py
@@ -20,6 +20,7 @@ from webauthn.helpers.structs import AuthenticatorTransport, PublicKeyCredential
from posthog.api.authentication import EmailVerificationPending, axes_locked_out, is_email_verified_for_login
from posthog.auth import SessionAuthentication, WebAuthnAuthenticationResponse, WebauthnBackend
from posthog.event_usage import report_user_logged_in
+from posthog.helpers.email_utils import EmailLookupHandler
from posthog.helpers.two_factor_session import set_two_factor_verified_in_session
from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, resolve_login_organization
from posthog.models import User
@@ -489,7 +490,7 @@ class WebAuthnSignupRegistrationViewSet(viewsets.ViewSet):
)
# Check if email is already registered
- if User.objects.filter(email__iexact=email).exists():
+ if EmailLookupHandler.users_matching_email(email).exists():
return Response(
{"error": "An account with this email already exists."},
status=status.HTTP_400_BAD_REQUEST,
diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.py
index 90baa34f7f66..6c7479f4c1df 100644
--- a/posthog/helpers/email_utils.py
+++ b/posthog/helpers/email_utils.py
@@ -5,6 +5,7 @@ lookup by email, and display-name / message validation.
import re
import html
+import string
import hashlib
import unicodedata
from collections.abc import Callable
@@ -239,13 +240,24 @@ def sanitize_email_string(value: str) -> str:
return _BARE_DOMAIN_RE.sub(_defang_match, defanged)
+_ASCII_UPPER_TO_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)
+
+
class EmailNormalizer:
@staticmethod
def normalize(email: str) -> str:
+ """Fold an address into the form `User.email` stores.
+
+ Only `A-Z` folds. Every lookup resolves an address through Postgres `LOWER`, and `A-Z` is
+ the range where Python and Postgres agree. `str.lower()` maps `İ` (U+0130) to `i` plus a
+ combining dot, where Postgres maps it to a plain `i`, so folding it here would store an
+ address that no string a person can type folds onto. Postgres still folds the untouched
+ characters at lookup time, so an address stays resolvable from any case it is typed in.
+ """
if not email:
return email
- return email.lower()
+ return email.translate(_ASCII_UPPER_TO_LOWER)
def strip_email_alias(email: str) -> str:
diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.py
index 74f5aea0eb0e..812556437fc8 100644
--- a/posthog/helpers/tests/test_email_utils.py
+++ b/posthog/helpers/tests/test_email_utils.py
@@ -3,6 +3,7 @@ from typing import Optional, cast
from unittest.mock import MagicMock, patch
+from django.db import connection
from django.test import SimpleTestCase, TestCase, override_settings
from django.utils import timezone
@@ -49,6 +50,34 @@ class TestEmailNormalizer(TestCase):
result = EmailNormalizer.normalize(input_email)
self.assertEqual(result, expected)
+ @parameterized.expand(
+ [
+ ("dotted_capital_i", "owner@İstanbul.example"),
+ ("dotless_i", "ownerı@example.com"),
+ ("long_s", "owner@ſtrasse.example"),
+ ("kelvin_sign", "owner@Klvin.example"),
+ ("capital_sharp_s", "owner@ẞtrasse.example"),
+ ("accented_capital", "Ö[email protected]"),
+ ("plain_ascii", "[email protected]"),
+ ]
+ )
+ def test_normalizing_does_not_change_what_postgres_folds_the_address_to(self, _name: str, typed: str) -> None:
+ # Every lookup resolves through Postgres LOWER. An address a person types must therefore
+ # still fold onto the row that normalizing wrote, whatever characters it holds.
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT LOWER(%s), LOWER(%s)", [EmailNormalizer.normalize(typed), typed])
+ folded_stored, folded_typed = cursor.fetchone()
+
+ self.assertEqual(folded_stored, folded_typed)
+
+ def test_account_created_with_a_dotted_capital_i_resolves_from_the_typed_address(self) -> None:
+ user = User.objects.create_user(email="Owner@İstanbul.example", password="testpass123", first_name="Owner")
+
+ self.assertEqual(user.email, "owner@İstanbul.example")
+ self.assertEqual(EmailLookupHandler.get_user_by_email("Owner@İstanbul.example"), user)
+ # Postgres folds `İ` onto a plain `i`, so the ASCII spelling reaches the same row.
+ self.assertEqual(EmailLookupHandler.get_user_by_email("[email protected]"), user)
+
class TestEmailLookupHandler(TestCase):
def test_get_user_by_email_no_user(self):
diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
index 8bcfcd0031d8..8a1d9fb0aa88 100644
--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
@@ -107,7 +107,6 @@ posthog/clickhouse/client/test/test_limit.py::TestRateLimit
posthog/clickhouse/test/test_deletion_coverage.py::TestDeletionCoverage
posthog/clickhouse/test/test_query_tagging.py::TestAddFallbackQueryTags
posthog/helpers/test_markdown_safety.py::TestStripExternalLinks
-posthog/helpers/tests/test_email_utils.py::TestEmailNormalizer
posthog/helpers/tests/test_encrypted_fields.py::TestEncryptedFields
posthog/helpers/tests/test_geoip.py::TestGeoIPDBError
posthog/helpers/tests/test_geoip.py::TestGeoIPError