: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): check gmail mailbox collisions on email changes (#108223)
Alessandro Pogliaghiee111d9c183f
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 977ec8db2295..092d6e0eefb0 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -1188,12 +1188,22 @@ class TestUserAPI(APIBaseTest):assert self.user.email == "[email protected]"assert self.user.first_name == "Newname"- def test_email_change_rejected_when_another_account_holds_the_aliased_form(self):+ @parameterized.expand(+ [+ ("plus_alias", "[email protected]", "[email protected]"),+ ("gmail_dots", "[email protected]", "[email protected]"),+ ("gmail_stored_dots_and_alias", "[email protected]", "[email protected]"),+ ("googlemail", "[email protected]", "[email protected]"),+ ]+ )+ def test_email_change_rejected_when_another_account_holds_the_same_mailbox(+ self, _name: str, other_email: str, new_email: str+ ) -> None:self.user.email = "[email protected]"self.user.save()- User.objects.create(email="[email protected]", first_name="Beta")+ User.objects.create(email=other_email, first_name="Beta")- response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})+ response = self.client.patch("/api/users/@me/", {"email": new_email})assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json()["code"] == "unique"@@ -1258,17 +1268,26 @@ class TestUserAPI(APIBaseTest):assert self.user.email == "[email protected]"assert self.user.pending_email is None+ @parameterized.expand(+ [+ ("plus_alias", "[email protected]", "[email protected]"),+ ("gmail_dots", "[email protected]", "[email protected]"),+ ("googlemail", "[email protected]", "[email protected]"),+ ]+ )@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):+ def test_email_change_allowed_within_own_mailbox(+ self, _name: str, current_email: str, new_email: str, _mock_is_email_available: mock.Mock+ ) -> None:# The collision check must skip the editor's own row, or a legacy alias holder can never clean it up.- self.user.email = "[email protected]"+ self.user.email = current_emailself.user.save()- response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})+ response = self.client.patch("/api/users/@me/", {"email": new_email})assert response.status_code == status.HTTP_200_OKself.user.refresh_from_db()- assert self.user.email == "[email protected]"+ assert self.user.email == new_email@parameterized.expand([@@ -3599,14 +3618,17 @@ class TestEmailVerificationCodeAPI(APIBaseTest):@parameterized.expand([- ("verified", True, "[email protected]"),- ("legacy_never_verified", None, "[email protected]"),- ("staged_before_normalization", True, "[email protected]"),+ ("verified", True, "[email protected]", "[email protected]"),+ ("legacy_never_verified", None, "[email protected]", "[email protected]"),+ ("staged_before_normalization", True, "[email protected]", "[email protected]"),+ ("own_gmail_dots", True, "[email protected]", "[email protected]"),+ ("own_googlemail", True, "[email protected]", "[email protected]"),])def test_email_change_code_goes_to_the_pending_address_and_completes_the_swap(- self, _name, is_email_verified, staged_email- ):+ self, _name: str, is_email_verified: bool | None, staged_email: str, current_email: str+ ) -> None:+ self.user.email = current_emailself.user.is_email_verified = is_email_verifiedself.user.pending_email = staged_emailself.user.save()@@ -3621,20 +3643,24 @@ class TestEmailVerificationCodeAPI(APIBaseTest):response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})self.assertEqual(response.status_code, status.HTTP_200_OK)self.user.refresh_from_db()- assert self.user.email == "[email protected]"+ assert self.user.email == staged_email.lower()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),+ ("active_case_variant", "[email protected]", True, "[email protected]"),# An exact match reaches the write, because the fold check reads active accounts only.- ("deactivated_exact_match", "[email protected]", False),+ ("deactivated_exact_match", "[email protected]", False, "[email protected]"),+ ("gmail_dots", "[email protected]", True, "[email protected]"),+ ("googlemail", "[email protected]", True, "[email protected]"),])- def test_pending_address_taken_while_the_change_waited_is_not_promoted(self, _name, other_email, other_is_active):+ def test_pending_address_taken_while_the_change_waited_is_not_promoted(+ self, _name: str, other_email: str, other_is_active: bool, staged_email: str+ ) -> None:self.user.is_email_verified = True- self.user.pending_email = "[email protected]"+ self.user.pending_email = staged_emailself.user.save()account_email = self.user.email@@ -3652,7 +3678,7 @@ class TestEmailVerificationCodeAPI(APIBaseTest):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]"+ assert self.user.pending_email == staged_emailrepeat = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 1fd723ed1cc2..58a37194efe0 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -437,9 +437,10 @@ class UserSerializer(serializers.ModelSerializer):return self.instance.emailreject_plus_addressed_email(value)# Excluding the editor lets a legacy '+' account holder drop their own alias.+ exclude_user_id = self.instance.pk if self.instance else Noneif EmailValidationHelper.user_exists_with_stripped_alias(- value, exclude_user_id=self.instance.pk if self.instance else None- ):+ value, exclude_user_id=exclude_user_id+ ) or EmailValidationHelper.user_exists_with_gmail_canonical(value, exclude_user_id=exclude_user_id):raise serializers.ValidationError("There is already an account with this email address.", code="unique")# 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.@@ -1268,6 +1269,7 @@ class UserViewSet(# 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 EmailValidationHelper.user_exists_with_gmail_canonical(new_email, exclude_user_id=user.pk)or EmailLookupHandler.users_matching_email(new_email, User.objects.all()).exclude(pk=user.pk).exists())if taken:diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.pyindex fcc7ecb06fba..df90ffbb2194 100644--- a/posthog/helpers/email_utils.py+++ b/posthog/helpers/email_utils.py@@ -432,7 +432,7 @@ class EmailValidationHelper:return candidates.exists()@staticmethod- def user_exists_with_gmail_canonical(email: str) -> bool:+ def user_exists_with_gmail_canonical(email: str, exclude_user_id: Optional[int] = None) -> bool:from posthog.models.user import Usercanonical_local = gmail_canonical_local_part(email)@@ -441,12 +441,14 @@ class EmailValidationHelper:gmail_domains = Q()for domain in GMAIL_DOMAINS:gmail_domains |= Q(email__iendswith=f"@{domain}")- return (+ candidates = (User.objects.filter(gmail_domains, is_active=True).annotate(gmail_canonical_local=GMAIL_CANONICAL_LOCAL_EXPRESSION).filter(gmail_canonical_local=canonical_local)- .exists())+ if exclude_user_id is not None:+ candidates = candidates.exclude(pk=exclude_user_id)+ return candidates.exists()ESP_SUPPRESSION_CACHE_TTL_IN_SECONDS = 86400 # 1 day