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(signup): treat dotted gmail addresses as the same mailbox (#107552)

Alessandro Pogliaghief0045086253
diff --git a/posthog/api/signup.py b/posthog/api/signup.py
index 34f08996c71c..3ea9cc9ee98a 100644
--- a/posthog/api/signup.py
+++ b/posthog/api/signup.py
@@ -194,7 +194,9 @@ class SignupSerializer(serializers.Serializer):
if not settings.DEMO:
if not self.is_social_signup:
reject_plus_addressed_email(value)
- if EmailValidationHelper.user_exists_with_stripped_alias(value):
+ if EmailValidationHelper.user_exists_with_stripped_alias(
+ value
+ ) or EmailValidationHelper.user_exists_with_gmail_canonical(value):
raise serializers.ValidationError(
"There is already an account with this email address.", code="unique"
)
@@ -419,7 +421,9 @@ class SignupEmailPrecheckViewset(generics.GenericAPIView):
# Mirror SignupSerializer.validate_email. Without this the form clears the email step,
# the user fills in the rest, and only then hits the rejection on submit.
reject_plus_addressed_email(email)
- email_exists = EmailValidationHelper.user_exists_with_stripped_alias(email)
+ email_exists = EmailValidationHelper.user_exists_with_stripped_alias(
+ email
+ ) or EmailValidationHelper.user_exists_with_gmail_canonical(email)
if email_exists:
return response.Response(
{
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index f46a02408913..2361f43c6cfb 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -352,6 +352,29 @@ class TestSignupAPI(APIBaseTest):
)
self.assertEqual(User.objects.count(), 1)
+ @pytest.mark.skip_on_multitenancy
+ def test_signup_disallowed_on_gmail_dot_collision(self) -> None:
+ User.objects.create(email="[email protected]", first_name="Jane")
+
+ response = self.client.post(
+ "/api/signup/",
+ {
+ "first_name": "John",
+ "email": "[email protected]",
+ "password": VALID_TEST_PASSWORD,
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
+ self.validation_error_response(
+ "There is already an account with this email address.",
+ code="unique",
+ attr="email",
+ ),
+ )
+ self.assertEqual(User.objects.count(), 1)
+
@pytest.mark.skip_on_multitenancy
def test_social_signup_allows_plus_addressed_email(self):
# Social signup is deliberately out of scope for the plus-addressing rules.
@@ -3359,9 +3382,17 @@ class TestSignupPrecheckPendingInvite(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["code"], "plus_addressing_not_allowed")
- def test_precheck_reports_collision_with_an_aliased_account(self):
- User.objects.create_user(email="[email protected]", password=None, first_name="Dupe")
- response = self.client.post("/api/signup/precheck", {"email": "[email protected]"})
+ @parameterized.expand(
+ [
+ ("aliased_account", "[email protected]", "[email protected]"),
+ ("dotted_gmail_account", "[email protected]", "[email protected]"),
+ ]
+ )
+ def test_precheck_reports_collision_with_the_same_mailbox(
+ self, _name: str, stored_email: str, looked_up_email: str
+ ) -> None:
+ User.objects.create_user(email=stored_email, password=None, first_name="Dupe")
+ response = self.client.post("/api/signup/precheck", {"email": looked_up_email})
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
self.assertTrue(response.json()["email_exists"])
diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.py
index 6c7479f4c1df..fcc7ecb06fba 100644
--- a/posthog/helpers/email_utils.py
+++ b/posthog/helpers/email_utils.py
@@ -18,8 +18,8 @@ from urllib.parse import quote
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import MultipleObjectsReturned
-from django.db.models import F, Func, QuerySet, Value
-from django.db.models.functions import Lower
+from django.db.models import CharField, F, Func, Q, QuerySet, Value
+from django.db.models.functions import Lower, Replace
import requests
import structlog
@@ -283,6 +283,22 @@ def _stripped_email(expression: "str | Value") -> Func:
# the query filters on the identical expression, so these must not drift apart.
STRIPPED_EMAIL_EXPRESSION = _stripped_email("email")
+GMAIL_DOMAINS = frozenset({"gmail.com", "googlemail.com"})
+
+
+def gmail_canonical_local_part(email: str) -> str | None:
+ local, _, domain = strip_email_alias(EmailNormalizer.normalize(email)).rpartition("@")
+ if domain not in GMAIL_DOMAINS:
+ return None
+ return local.replace(".", "")
+
+
+GMAIL_CANONICAL_LOCAL_EXPRESSION = Replace(
+ Func(STRIPPED_EMAIL_EXPRESSION, Value("@"), Value(1), function="split_part", output_field=CharField()),
+ Value("."),
+ Value(""),
+)
+
def reject_plus_addressed_email(value: str) -> None:
"""Raise if the local part of `value` contains '+'."""
@@ -415,6 +431,23 @@ class EmailValidationHelper:
candidates = candidates.exclude(pk=exclude_user_id)
return candidates.exists()
+ @staticmethod
+ def user_exists_with_gmail_canonical(email: str) -> bool:
+ from posthog.models.user import User
+
+ canonical_local = gmail_canonical_local_part(email)
+ if canonical_local is None:
+ return False
+ gmail_domains = Q()
+ for domain in GMAIL_DOMAINS:
+ gmail_domains |= Q(email__iendswith=f"@{domain}")
+ return (
+ User.objects.filter(gmail_domains, is_active=True)
+ .annotate(gmail_canonical_local=GMAIL_CANONICAL_LOCAL_EXPRESSION)
+ .filter(gmail_canonical_local=canonical_local)
+ .exists()
+ )
+
ESP_SUPPRESSION_CACHE_TTL_IN_SECONDS = 86400 # 1 day
ESP_SUPPRESSION_ERROR_CACHE_TTL_IN_SECONDS = (
diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.py
index 812556437fc8..263a6be23c39 100644
--- a/posthog/helpers/tests/test_email_utils.py
+++ b/posthog/helpers/tests/test_email_utils.py
@@ -285,6 +285,29 @@ class TestUserExistsWithStrippedAlias(TestCase):
user.delete()
+class TestUserExistsWithGmailCanonical(TestCase):
+ @parameterized.expand(
+ [
+ ("dotted_lookup_plain_stored", "[email protected]", "[email protected]", True),
+ ("plain_lookup_dotted_stored", "[email protected]", "[email protected]", True),
+ ("alias_and_dots_stored", "[email protected]", "[email protected]", True),
+ ("alias_and_dots_looked_up", "[email protected]", "[email protected]", True),
+ ("googlemail_is_gmail", "[email protected]", "[email protected]", True),
+ ("mixed_case_stored", "[email protected]", "[email protected]", True),
+ ("other_domain_keeps_dots", "[email protected]", "[email protected]", False),
+ ("different_mailbox", "[email protected]", "[email protected]", False),
+ ]
+ )
+ def test_collapses_dots_and_alias_only_for_gmail(
+ self, _name: str, stored_email: str, looked_up_email: str, expected: bool
+ ) -> None:
+ user = User.objects.create(email=stored_email, first_name="Base")
+ try:
+ self.assertEqual(EmailValidationHelper.user_exists_with_gmail_canonical(looked_up_email), expected)
+ finally:
+ user.delete()
+
+
class TestESPSuppressionCheck(SimpleTestCase):
def test_returns_not_suppressed_for_empty_email(self):
result = check_esp_suppression("")
diff --git a/posthog/migrations/1387_user_gmail_canonical_index.py b/posthog/migrations/1387_user_gmail_canonical_index.py
new file mode 100644
index 000000000000..92d4b5dfca47
--- /dev/null
+++ b/posthog/migrations/1387_user_gmail_canonical_index.py
@@ -0,0 +1,37 @@
+import django.db.models.functions.text
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("posthog", "1386_taggeditem_drop_legacy_columns"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="user",
+ index=models.Index(
+ django.db.models.functions.text.Replace(
+ models.Func(
+ models.Func(
+ django.db.models.functions.text.Lower("email"),
+ models.Value("\\+[^@]*@"),
+ models.Value("@"),
+ function="regexp_replace",
+ ),
+ models.Value("@"),
+ models.Value(1),
+ function="split_part",
+ output_field=models.CharField(),
+ ),
+ models.Value("."),
+ models.Value(""),
+ ),
+ name="user_gmail_canonical_idx",
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index bb95295696f1..b6020554d824 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1386_taggeditem_drop_legacy_columns
+1387_user_gmail_canonical_index
diff --git a/posthog/models/user.py b/posthog/models/user.py
index ab964e7dbb04..3a28f4868524 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -15,7 +15,12 @@ from rest_framework.exceptions import ValidationError
from posthog.cloud_utils import get_cached_instance_license, is_cloud
from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
-from posthog.helpers.email_utils import STRIPPED_EMAIL_EXPRESSION, EmailLookupHandler, EmailNormalizer
+from posthog.helpers.email_utils import (
+ GMAIL_CANONICAL_LOCAL_EXPRESSION,
+ STRIPPED_EMAIL_EXPRESSION,
+ EmailLookupHandler,
+ EmailNormalizer,
+)
from posthog.migration_helpers import deprecate_field
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.organization_notification_lock import GovernedSetting, effective_notification_settings
@@ -348,6 +353,7 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore
verbose_name_plural = _("users")
indexes = [
models.Index(STRIPPED_EMAIL_EXPRESSION, name="user_stripped_alias_idx"),
+ models.Index(GMAIL_CANONICAL_LOCAL_EXPRESSION, name="user_gmail_canonical_idx"),
# Serves the `LOWER(email)` fold `EmailLookupHandler.get_user_by_email` resolves on.
models.Index(Lower("email"), name="posthog_user_lower_email_idx"),
]