: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): reject plus-addressed emails at the signup email step (#81710)
Yasen0c52b842abcb
diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 3b787dbbe406..7dfc402f5f22 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -399,7 +399,12 @@ class SignupEmailPrecheckViewset(generics.GenericAPIView):serializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)email = serializer.validated_data["email"]- email_exists = False if settings.DEMO else EmailValidationHelper.user_exists(email)+ email_exists = False+ if not settings.DEMO:+ # 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)if email_exists:return response.Response({diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 017060a7812b..0958d35063f4 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -3284,6 +3284,17 @@ class TestSignupPrecheckPendingInvite(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)self.assertNotIn("pending_invite", response.json())+ def test_precheck_rejects_plus_addressed_email(self):+ response = self.client.post("/api/signup/precheck", {"email": "[email protected]"})+ 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]"})+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertTrue(response.json()["email_exists"])+class TestSignupResendInvite(APIBaseTest):def setUp(self):diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.pyindex 1b4aa34e4752..98858245bc59 100644--- a/posthog/helpers/email_utils.py+++ b/posthog/helpers/email_utils.py@@ -17,7 +17,8 @@ from urllib.parse import quotefrom django.conf import settingsfrom django.core.cache import cachefrom django.core.exceptions import MultipleObjectsReturned-from django.db.models import Q, QuerySet+from django.db.models import Func, QuerySet, Value+from django.db.models.functions import Lowerimport requestsimport structlog@@ -260,6 +261,13 @@ def strip_email_alias(email: str) -> str:return f"{local}@{domain}"+# 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")++def reject_plus_addressed_email(value: str) -> None:"""Raise if the local part of `value` contains '+'."""local = value.split("@", 1)[0]@@ -358,10 +366,13 @@ class EmailValidationHelper:"""from posthog.models.user import User- stripped = strip_email_alias(email)- local, _, domain = stripped.rpartition("@")- candidates = User.objects.filter(is_active=True).filter(- Q(email__iexact=stripped) | (Q(email__istartswith=f"{local}+") & Q(email__iendswith=f"@{domain}"))+ # 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()+ candidates = (+ User.objects.filter(is_active=True)+ .annotate(stripped_email=STRIPPED_EMAIL_EXPRESSION)+ .filter(stripped_email=stripped))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 e9033414c8ae..4372e0885810 100644--- a/posthog/helpers/tests/test_email_utils.py+++ b/posthog/helpers/tests/test_email_utils.py@@ -150,6 +150,24 @@ class TestUserExistsWithStrippedAlias(TestCase):finally:user.delete()+ @parameterized.expand(+ [+ # 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+ # against the lowercased expression silently returns False without it.+ ("looked_up_mixed_case", "[email protected]", "[email protected]"),+ ]+ )+ def test_matches_regardless_of_case(self, _name, stored_email, looked_up_email):+ # create() rather than create_user() so the stored value keeps its original casing.+ user = User.objects.create(email=stored_email, first_name="Base")+ try:+ self.assertTrue(EmailValidationHelper.user_exists_with_stripped_alias(looked_up_email))+ finally:+ user.delete()+class TestESPSuppressionCheck(SimpleTestCase):def test_returns_not_suppressed_for_empty_email(self):diff --git a/posthog/models/user.py b/posthog/models/user.pyindex d621f46f0337..4fd2ad2f75c9 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -5,8 +5,6 @@ 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 import Func, Value-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 _@@ -17,7 +15,7 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.cloud_utils import get_cached_instance_license, is_cloudfrom posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exception-from posthog.helpers.email_utils import EmailLookupHandler, EmailNormalizer+from posthog.helpers.email_utils import STRIPPED_EMAIL_EXPRESSION, EmailLookupHandler, EmailNormalizerfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.settings import INSTANCE_TAG, SITE_URLfrom posthog.utils import get_instance_realm@@ -339,10 +337,7 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignoreverbose_name = _("user")verbose_name_plural = _("users")indexes = [- models.Index(- Func(Lower("email"), Value(r"\+[^@]*@"), Value("@"), function="regexp_replace"),- name="user_stripped_alias_idx",- ),+ models.Index(STRIPPED_EMAIL_EXPRESSION, name="user_stripped_alias_idx"),]# Remove unused attributes from `AbstractUser`