: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
feat(auth): reject plus-addressed emails to stop duplicate signups (#79523)
Yasen959bce932a7f
diff --git a/playwright/e2e/signup.spec.ts b/playwright/e2e/signup.spec.tsindex 36677ee9dfdc..2a6491d04186 100644--- a/playwright/e2e/signup.spec.ts+++ b/playwright/e2e/signup.spec.ts@@ -67,7 +67,7 @@ test.describe('Signup', () => {await route.continue()})- const email = `new_user+${Math.floor(Math.random() * 10000)}@posthog.com`+ const email = `new_user-${Math.floor(Math.random() * 10000)}@posthog.com`await startSignupFlow(page, email, VALID_PASSWORD)await page.locator('[data-attr=signup-name]').fill('Alice Bob')await expect(page.locator('[data-attr=signup-name]')).toHaveValue('Alice Bob')@@ -88,7 +88,7 @@ test.describe('Signup', () => {test('Can submit the signup form multiple times if there is a generic email set', async ({ page }) => {let signupRequestBody: string | null = null- const email = `new_user+generic_error_test_${Math.floor(Math.random() * 10000)}@posthog.com`+ const email = `new_user-generic_error_test_${Math.floor(Math.random() * 10000)}@posthog.com`await page.route('/api/signup/', async (route) => {signupRequestBody = route.request().postData()@@ -122,7 +122,7 @@ test.describe('Signup', () => {await submitEmailAndExpectExistingAccount(page, email)// Update email to generic email and retry- const newEmail = `new_user+${Math.floor(Math.random() * 10000)}@posthog.com`+ const newEmail = `new_user-${Math.floor(Math.random() * 10000)}@posthog.com`await startSignupFlow(page, newEmail, VALID_PASSWORD)await page.locator('[data-attr=signup-name]').fill('Alice Bob')await expect(page.locator('[data-attr=signup-name]')).toHaveValue('Alice Bob')@@ -196,7 +196,7 @@ test.describe('Signup', () => {// Start signup with next parameterawait page.goto('/signup?next=/custom_path')- const email = `new_user+${Math.floor(Math.random() * 10000)}@posthog.com`+ const email = `new_user-${Math.floor(Math.random() * 10000)}@posthog.com`await startSignupFlow(page, email, VALID_PASSWORD)await page.locator('[data-attr=signup-name]').fill('Alice Bob')await expect(page.locator('[data-attr=signup-name]')).toHaveValue('Alice Bob')diff --git a/posthog/api/organization_invite.py b/posthog/api/organization_invite.pyindex 048ad82aa2d0..5a3378e5ed6f 100644--- a/posthog/api/organization_invite.py+++ b/posthog/api/organization_invite.py@@ -18,7 +18,12 @@ from posthog.api.utils import actionfrom posthog.constants import INVITE_DAYS_VALIDITYfrom posthog.email import is_email_availablefrom posthog.event_usage import report_bulk_invited, report_team_member_invited-from posthog.helpers.email_utils import EmailNormalizer, validate_display_name, validate_message_body+from posthog.helpers.email_utils import (+ EmailNormalizer,+ reject_plus_addressed_email,+ validate_display_name,+ validate_message_body,+)from posthog.models import OrganizationDomain, OrganizationInvite, OrganizationMembershipfrom posthog.models.onboarding_delegation import (get_existing_pending_delegation_invite,@@ -189,6 +194,7 @@ class OrganizationInviteSerializer(serializers.ModelSerializer):def validate_target_email(self, email: str):email = EmailNormalizer.normalize(email)+ reject_plus_addressed_email(email)validate_invite_target_email_domain(self.context["get_organization"](), email)return email@@ -373,7 +379,9 @@ class OrganizationInviteDelegateSerializer(serializers.Serializer):)def validate_target_email(self, email: str) -> str:- return EmailNormalizer.normalize(email)+ email = EmailNormalizer.normalize(email)+ reject_plus_addressed_email(email)+ return emaildef validate_message(self, value: str | None) -> str | None:# Mirror the standard invite serializer's body validation so URLs / control charsdiff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 8e4209555c0c..ad5d4140fc10 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -32,7 +32,7 @@ from posthog.api.webauthn import (from posthog.email import is_email_availablefrom posthog.event_usage import alias_invite_id, report_user_joined_organization, report_user_signed_upfrom posthog.exceptions_capture import capture_exception-from posthog.helpers.email_utils import EmailValidationHelper, validate_display_name+from posthog.helpers.email_utils import EmailValidationHelper, reject_plus_addressed_email, validate_display_namefrom posthog.helpers.verified_domain_enforcement import resolve_login_organizationfrom posthog.models import InviteExpiredException, Organization, OrganizationDomain, OrganizationInvite, Team, Userfrom posthog.models.organization_invite import INVITE_DAYS_VALIDITY@@ -183,8 +183,15 @@ class SignupSerializer(serializers.Serializer):value = session_email- if not settings.DEMO and EmailValidationHelper.user_exists(value):- raise serializers.ValidationError("There is already an account with this email address.", code="unique")+ if not settings.DEMO:+ if not self.is_social_signup:+ reject_plus_addressed_email(value)+ if EmailValidationHelper.user_exists_with_stripped_alias(value):+ raise serializers.ValidationError(+ "There is already an account with this email address.", code="unique"+ )+ elif EmailValidationHelper.user_exists(value):+ raise serializers.ValidationError("There is already an account with this email address.", code="unique")return valuedef is_email_auto_verified(self):diff --git a/posthog/api/test/test_organization_invites.py b/posthog/api/test/test_organization_invites.pyindex 2ad822d299c3..74b58f765f62 100644--- a/posthog/api/test/test_organization_invites.py+++ b/posthog/api/test/test_organization_invites.py@@ -58,7 +58,7 @@ class TestOrganizationInvitesAPI(APIBaseTest):for i in range(0, count):payload.append({- "target_email": f"test+{random.randint(1000000, 9999999)}@posthog.com",+ "target_email": f"test-{random.randint(1000000, 9999999)}@posthog.com","first_name": NAME_SEEDS[i % len(NAME_SEEDS)],})@@ -545,6 +545,15 @@ class TestOrganizationInvitesAPI(APIBaseTest):self.assertEqual(OrganizationInvite.objects.count(), count)+ def test_invite_creation_disallowed_with_plus_addressed_email(self):+ count = OrganizationInvite.objects.count()+ response = self.client.post(+ "/api/organizations/@current/invites/", {"target_email": "[email protected]"}+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "plus_addressing_not_allowed")+ self.assertEqual(OrganizationInvite.objects.count(), count)+@parameterized.expand([("blocks_unverified_domain", "[email protected]", status.HTTP_400_BAD_REQUEST),@@ -1606,6 +1615,12 @@ class TestOnboardingDelegationInviteAPI(APIBaseTest):response = self.client.post(self._delegate_url(), {"target_email": "not-an-email"})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_delegate_rejects_plus_addressed_email(self):+ response = self.client.post(self._delegate_url(), {"target_email": "[email protected]"})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "plus_addressing_not_allowed")+ self.assertFalse(OrganizationInvite.objects.filter(target_email="[email protected]").exists())+def test_delegate_rejects_self_delegation(self):response = self.client.post(self._delegate_url(), {"target_email": self.user.email})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)@@ -1840,7 +1855,7 @@ class TestOnboardingDelegationStateTransitionTable(APIBaseTest):self._assert_user_state(**expected)def _run_delegate_only(self) -> None:- self._last_delegate_email = f"engineer+{random.randint(100000, 999999)}@example.com"+ self._last_delegate_email = f"engineer-{random.randint(100000, 999999)}@example.com"response = self.client.post(self._delegate_url(), {"target_email": self._last_delegate_email})self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)@@ -1896,7 +1911,7 @@ class TestOrganizationInviteRateLimits(APIBaseTest):cache.clear()def _payload(self, count: int, seed: str = "burst") -> list[dict]:- return [{"target_email": f"test+{seed}_{i}@posthog.com"} for i in range(count)]+ return [{"target_email": f"test-{seed}_{i}@posthog.com"} for i in range(count)]@patch("posthog.rate_limit.OrganizationInviteBurstThrottle.rate", new="3/hour")def test_burst_limit_rejects_single_invites_over_cap(self, _rate_limit_enabled_mock, _time_sensitive_mock):diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 322c14a07bc1..83cf7ed5bc7f 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -307,6 +307,70 @@ class TestSignupAPI(APIBaseTest):existing_user.refresh_from_db()self.assertEqual(existing_user.first_name, "Hoggy")+ @pytest.mark.skip_on_multitenancy+ def test_signup_disallowed_with_plus_addressed_email(self):+ 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(+ "Email addresses with a '+' aren't supported. Please use your primary email address.",+ code="plus_addressing_not_allowed",+ attr="email",+ ),+ )+ self.assertEqual(User.objects.count(), 0)++ @pytest.mark.skip_on_multitenancy+ def test_signup_disallowed_on_stripped_alias_collision(self):+ 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.+ session = self.client.session+ session["backend"] = "google-oauth2"+ session["email"] = "[email protected]"+ session["user_name"] = "Social User"+ session.save()++ response = self.client.post(+ "/api/social_signup/",+ {+ "first_name": "Social",+ "organization_name": "Social Org",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertTrue(User.objects.filter(email="[email protected]").exists())+@pytest.mark.skip_on_multitenancydef test_signup_normalizes_email_to_lowercase(self):"""Test that new signups normalize email addresses to lowercase."""diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex d686cfe3297d..d9540d4f1a89 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -777,6 +777,55 @@ class TestUserAPI(APIBaseTest):)+ def test_email_change_rejected_when_new_email_is_plus_addressed(self):+ self.user.email = "[email protected]"+ self.user.save()++ response = self.client.patch("/api/users/@me/", {"email": "[email protected]"})++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "plus_addressing_not_allowed"+ self.user.refresh_from_db()+ assert self.user.email == "[email protected]"+ assert self.user.pending_email is None++ def test_email_change_allowed_when_current_plus_addressed_email_is_unchanged(self):+ # Grandfathers legacy plus-addressed accounts, which can't edit their profile otherwise.+ self.user.email = "[email protected]"+ self.user.save()++ response = self.client.patch("/api/users/@me/", {"email": "[email protected]", "first_name": "Newname"})++ assert response.status_code == status.HTTP_200_OK+ self.user.refresh_from_db()+ 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):+ self.user.email = "[email protected]"+ self.user.save()+ User.objects.create(email="[email protected]", first_name="Beta")++ 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.+ 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]"+@parameterized.expand([("single_google", [("google-oauth2", "google-sub-1")]),diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 153c979af5e8..58ebbf59ab1d 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -84,7 +84,12 @@ from posthog.event_usage import (report_user_verified_email,)from posthog.exceptions_capture import capture_exception-from posthog.helpers.email_utils import EmailNormalizer, validate_display_name+from posthog.helpers.email_utils import (+ EmailNormalizer,+ EmailValidationHelper,+ reject_plus_addressed_email,+ validate_display_name,+)from posthog.helpers.session_cache import SessionCachefrom posthog.helpers.two_factor_session import has_passkeys, set_two_factor_verified_in_sessionfrom posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, resolve_login_organization@@ -380,6 +385,18 @@ class UserSerializer(serializers.ModelSerializer):def validate_last_name(self, value: str) -> str: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+ 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+def get_has_password(self, instance: User) -> bool:return bool(instance.password) and instance.has_usable_password()diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.pyindex a2ea1d788f9c..1b4aa34e4752 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 QuerySet+from django.db.models import Q, QuerySetimport requestsimport structlog@@ -247,6 +247,29 @@ class EmailNormalizer:return email.lower()+def strip_email_alias(email: str) -> str:+ """+ Strip a Gmail-style '+suffix' from the local part of an email (e.g.+ '[email protected]' -> '[email protected]'). Comparison-only —+ never use this for the email that actually gets stored.+ """+ if not email:+ return email+ local, _, domain = email.rpartition("@")+ local = local.split("+", 1)[0]+ return f"{local}@{domain}"+++def reject_plus_addressed_email(value: str) -> None:+ """Raise if the local part of `value` contains '+'."""+ local = value.split("@", 1)[0]+ if "+" in local:+ raise serializers.ValidationError(+ "Email addresses with a '+' aren't supported. Please use your primary email address.",+ code="plus_addressing_not_allowed",+ )++class EmailLookupHandler:@staticmethoddef get_user_by_email(email: str, is_active: Optional[bool] = True) -> Optional["User"]:@@ -327,6 +350,23 @@ class EmailValidationHelper:def user_exists(email: str) -> bool:return EmailLookupHandler.get_user_by_email(email) is not None+ @staticmethod+ def user_exists_with_stripped_alias(email: str, exclude_user_id: Optional[int] = None) -> bool:+ """+ True if any existing active user's email, once its '+alias' is stripped, equals `email`.+ `exclude_user_id` skips one account, so a user dropping their own '+alias' isn't blocked by themselves.+ """+ 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}"))+ )+ 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 dayESP_SUPPRESSION_ERROR_CACHE_TTL_IN_SECONDS = (diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.pyindex d295d6cdbada..e9033414c8ae 100644--- a/posthog/helpers/tests/test_email_utils.py+++ b/posthog/helpers/tests/test_email_utils.py@@ -18,9 +18,11 @@ from posthog.helpers.email_utils import (ESPSuppressionReason,_get_esp_suppression_cache_key,check_esp_suppression,+ reject_plus_addressed_email,sanitize_display_name,sanitize_email_string,sanitize_message_body,+ strip_email_alias,validate_display_name,validate_message_body,)@@ -97,6 +99,58 @@ class TestEmailValidationHelper(TestCase):user.delete()+class TestStripEmailAlias(SimpleTestCase):+ def test_strip_email_alias(self):+ test_cases = [+ ("[email protected]", "[email protected]"),+ ("[email protected]", "[email protected]"),+ ("[email protected]", "[email protected]"),+ ("[email protected]", "[email protected]"),+ ("", ""),+ ]++ for input_email, expected in test_cases:+ with self.subTest(input_email=input_email):+ self.assertEqual(strip_email_alias(input_email), expected)+++class TestRejectPlusAddressedEmail(SimpleTestCase):+ def test_rejects_plus_in_local_part(self):+ with self.assertRaises(serializers.ValidationError) as ctx:+ reject_plus_addressed_email("[email protected]")+ self.assertEqual(ctx.exception.get_codes(), ["plus_addressing_not_allowed"])++ def test_allows_email_without_plus(self):+ # Should not raise.+ reject_plus_addressed_email("[email protected]")+++class TestUserExistsWithStrippedAlias(TestCase):+ def test_no_match(self):+ self.assertFalse(EmailValidationHelper.user_exists_with_stripped_alias("[email protected]"))++ def test_matches_existing_plain_email(self):+ user = User.objects.create_user(email="[email protected]", password=None, first_name="Base")+ try:+ self.assertTrue(EmailValidationHelper.user_exists_with_stripped_alias("[email protected]"))+ finally:+ user.delete()++ def test_matches_existing_aliased_email(self):+ user = User.objects.create_user(email="[email protected]", password=None, first_name="Base")+ try:+ self.assertTrue(EmailValidationHelper.user_exists_with_stripped_alias("[email protected]"))+ finally:+ user.delete()++ def test_does_not_match_different_local_part(self):+ user = User.objects.create_user(email="[email protected]", password=None, first_name="Base")+ try:+ self.assertFalse(EmailValidationHelper.user_exists_with_stripped_alias("[email protected]"))+ finally:+ user.delete()++class TestESPSuppressionCheck(SimpleTestCase):def test_returns_not_suppressed_for_empty_email(self):result = check_esp_suppression("")