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): reject look-alike dots in signup emails and malformed uuids (#125912)

Daniel Marchuk0926baca7821
diff --git a/posthog/api/organization_invite.py b/posthog/api/organization_invite.py
index d83215346b98..97c01dd9a557 100644
--- a/posthog/api/organization_invite.py
+++ b/posthog/api/organization_invite.py
@@ -21,6 +21,7 @@ from posthog.email import is_email_available
from posthog.event_usage import report_bulk_invited, report_team_member_invited
from posthog.helpers.email_utils import (
EmailNormalizer,
+ reject_lookalike_email_characters,
reject_plus_addressed_email,
validate_display_name,
validate_message_body,
@@ -194,6 +195,7 @@ class OrganizationInviteSerializer(serializers.ModelSerializer):
def validate_target_email(self, email: str):
email = EmailNormalizer.normalize(email)
reject_plus_addressed_email(email)
+ reject_lookalike_email_characters(email)
validate_invite_target_email_domain(self.context["get_organization"](), email)
# Validation runs for every bulk row before any row saves, so one existing member
# rejects the batch without a partial set of sent invites.
@@ -394,6 +396,7 @@ class OrganizationInviteDelegateSerializer(serializers.Serializer):
def validate_target_email(self, email: str) -> str:
email = EmailNormalizer.normalize(email)
reject_plus_addressed_email(email)
+ reject_lookalike_email_characters(email)
return email
def validate_message(self, value: str | None) -> str | None:
diff --git a/posthog/api/signup.py b/posthog/api/signup.py
index eb53ed0b5782..6f8c81f3a95c 100644
--- a/posthog/api/signup.py
+++ b/posthog/api/signup.py
@@ -37,6 +37,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import (
EmailLookupHandler,
EmailValidationHelper,
+ reject_lookalike_email_characters,
reject_plus_addressed_email,
validate_display_name,
)
@@ -227,6 +228,7 @@ class SignupSerializer(serializers.Serializer):
value = session_email
+ reject_lookalike_email_characters(value)
if not settings.DEMO:
if not self.is_social_signup:
reject_plus_addressed_email(value)
@@ -465,6 +467,7 @@ 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)
+ reject_lookalike_email_characters(email)
email_exists = (
EmailValidationHelper.user_exists_with_stripped_alias(email)
or EmailValidationHelper.user_exists_with_gmail_canonical(email)
@@ -607,7 +610,7 @@ class InviteSignupSerializer(serializers.Serializer):
try:
# nosemgrep: idor-lookup-without-org, idor-taint-user-input-to-org-model (invite UUID serves as auth token)
invite: OrganizationInvite = OrganizationInvite.objects.select_related("organization").get(id=invite_id)
- except OrganizationInvite.DoesNotExist:
+ except (OrganizationInvite.DoesNotExist, ValidationError):
raise serializers.ValidationError("The provided invite ID is not valid.")
if not user and invite.target_email:
diff --git a/posthog/api/test/test_organization_invites.py b/posthog/api/test/test_organization_invites.py
index 3f23588e51fd..17c5e4a35e4c 100644
--- a/posthog/api/test/test_organization_invites.py
+++ b/posthog/api/test/test_organization_invites.py
@@ -590,13 +590,17 @@ class TestOrganizationInvitesAPI(APIBaseTest):
self.assertEqual(OrganizationInvite.objects.count(), count)
- def test_invite_creation_disallowed_with_plus_addressed_email(self):
+ @parameterized.expand(
+ [
+ ("plus_addressed", "[email protected]", "plus_addressing_not_allowed"),
+ ("zero_width_space", "newperson@posthog\u200b.com", "lookalike_characters_not_allowed"),
+ ]
+ )
+ def test_invite_creation_disallowed_with_unsupported_email(self, _name, target_email, code):
count = OrganizationInvite.objects.count()
- response = self.client.post(
- "/api/organizations/@current/invites/", {"target_email": "[email protected]"}
- )
+ response = self.client.post("/api/organizations/@current/invites/", {"target_email": target_email})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.json()["code"], "plus_addressing_not_allowed")
+ self.assertEqual(response.json()["code"], code)
self.assertEqual(OrganizationInvite.objects.count(), count)
@parameterized.expand(
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index 9acc1be766e0..3248124caadb 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -311,27 +311,58 @@ class TestSignupAPI(APIBaseTest):
existing_user.refresh_from_db()
self.assertEqual(existing_user.first_name, "Hoggy")
+ @parameterized.expand(
+ [
+ (
+ "plus_addressed",
+ "Email addresses with a '+' aren't supported. Please use your primary email address.",
+ "plus_addressing_not_allowed",
+ ),
+ (
+ "lookalike_dot",
+ "john@ph\u3002posthog.com",
+ "Enter an email address using standard dots and no hidden characters.",
+ "lookalike_characters_not_allowed",
+ ),
+ (
+ "zero_width_space",
+ "john@posthog\u200b.com",
+ "Enter an email address using standard dots and no hidden characters.",
+ "lookalike_characters_not_allowed",
+ ),
+ ]
+ )
@pytest.mark.skip_on_multitenancy
- def test_signup_disallowed_with_plus_addressed_email(self):
+ def test_signup_disallowed_with_unsupported_email(self, _name, email, message, code):
response = self.client.post(
"/api/signup/",
{
"first_name": "John",
- "email": "[email protected]",
+ "email": email,
"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.validation_error_response(message, code=code, attr="email"),
)
self.assertEqual(User.objects.count(), 0)
+ @pytest.mark.skip_on_multitenancy
+ def test_signup_allowed_with_internationalized_domain(self):
+ response = self.client.post(
+ "/api/signup/",
+ {
+ "first_name": "John",
+ "email": "john@ex\u00e4mple.com",
+ "password": VALID_TEST_PASSWORD,
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(User.objects.get().email, "john@ex\u00e4mple.com")
+
@pytest.mark.skip_on_multitenancy
def test_signup_disallowed_on_stripped_alias_collision(self):
User.objects.create(email="[email protected]", first_name="Jane")
@@ -3011,13 +3042,14 @@ class TestInviteSignupAPI(APIBaseTest):
self.assertEqual(Team.objects.count(), team_count)
self.assertEqual(Organization.objects.count(), org_count)
- def test_cant_claim_invalid_invite(self):
+ @parameterized.expand([("unknown_uuid", str(uuid.uuid4())), ("malformed", "not-a-uuid")])
+ def test_cant_claim_invalid_invite(self, _name, invite_id):
count: int = User.objects.count()
team_count: int = Team.objects.count()
org_count: int = Organization.objects.count()
response = self.client.post(
- f"/api/signup/{uuid.uuid4()}/",
+ f"/api/signup/{invite_id}/",
{"first_name": "Charlie", "password": VALID_TEST_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 9cadf4d34701..13ee223862d3 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -1225,14 +1225,20 @@ class TestUserAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
mock_report.assert_called_once_with(self.user, field="email", reason="stale_reauth")
- def test_email_change_rejected_when_new_email_is_plus_addressed(self):
+ @parameterized.expand(
+ [
+ ("plus_addressed", "[email protected]", "plus_addressing_not_allowed"),
+ ("lookalike_dot", "alpha@ph\uff0eexample.com", "lookalike_characters_not_allowed"),
+ ]
+ )
+ def test_email_change_rejected_when_new_email_is_unsupported(self, _name, new_email, code):
self.user.email = "[email protected]"
self.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_400_BAD_REQUEST
- assert response.json()["code"] == "plus_addressing_not_allowed"
+ assert response.json()["code"] == code
self.user.refresh_from_db()
assert self.user.email == "[email protected]"
assert self.user.pending_email is None
@@ -3644,6 +3650,21 @@ class TestEmailVerificationCodeAPI(APIBaseTest):
response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": "000000"})
self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ @parameterized.expand([("not_a_uuid", "notauuid"), ("truncated", "0199a1b2-3c4d-7e8f")])
+ def test_malformed_uuid_answers_like_an_unknown_user(self, _name, bad_uuid):
+ response = self.client.post("/api/users/verify_email/", {"uuid": bad_uuid, "code": "123456"})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "invalid_code")
+
+ response = self.client.post("/api/users/request_email_verification/", {"uuid": bad_uuid})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True})
+
+ def test_request_email_verification_without_uuid_is_not_an_error(self):
+ response = self.client.post("/api/users/request_email_verification/", {})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True})
+
def test_numeric_json_code_is_a_normal_guess(self):
# A client that sends the six digits as a JSON number must get a 400, not a 500, and the
# coerced string counts as an ordinary attempt.
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 989d55e77f06..ff6955eb99f7 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -97,6 +97,7 @@ from posthog.helpers.email_utils import (
EmailLookupHandler,
EmailNormalizer,
EmailValidationHelper,
+ reject_lookalike_email_characters,
reject_plus_addressed_email,
validate_display_name,
)
@@ -481,6 +482,7 @@ class UserSerializer(serializers.ModelSerializer):
# verification and so cannot rewrite the address a person signs in with.
return self.instance.email
reject_plus_addressed_email(value)
+ reject_lookalike_email_characters(value)
# Excluding the editor lets a legacy '+' account holder drop their own alias.
exclude_user_id = self.instance.pk if self.instance else None
if EmailValidationHelper.user_exists_with_stripped_alias(
@@ -1296,7 +1298,7 @@ class UserViewSet(
try:
user: Optional[User] = User.objects.filter(is_active=True).get(uuid=user_uuid)
- except User.DoesNotExist:
+ except (User.DoesNotExist, ValidationError):
user = None
# A replay of a spent code (double submit) is not a failure: the address is verified.
@@ -1384,7 +1386,7 @@ class UserViewSet(
throttle_classes=[UserEmailVerificationThrottle],
)
def request_email_verification(self, request, **kwargs):
- uuid = request.data["uuid"]
+ uuid = request.data.get("uuid") if isinstance(request.data, dict) else None
if not is_email_available():
raise serializers.ValidationError(
"Cannot verify email address because email is not configured for your instance. Please contact your administrator.",
@@ -1392,7 +1394,7 @@ class UserViewSet(
)
try:
user = User.objects.filter(is_active=True).get(uuid=uuid)
- except User.DoesNotExist:
+ except (User.DoesNotExist, ValidationError):
user = None
if user:
# Allow re-requests when there's a pending email change that still
diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.py
index df90ffbb2194..9d3cc2a01950 100644
--- a/posthog/helpers/email_utils.py
+++ b/posthog/helpers/email_utils.py
@@ -310,6 +310,23 @@ def reject_plus_addressed_email(value: str) -> None:
)
+# Mail systems fold these dots to "." or drop the hidden characters, so the address that reaches the
+# mail provider is not the one we stored, and it can't receive verification or reset emails.
+# Letters from any script stay allowed: only dot look-alikes and invisible formatting characters are here.
+_LOOKALIKE_EMAIL_CHAR_RE = re.compile(
+ r"[\u2024\u3002\ufe52\uff0e\uff61\u00ad\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]"
+)
+
+
+def reject_lookalike_email_characters(value: str) -> None:
+ """Raise if `value` contains a look-alike dot or a zero-width character."""
+ if _LOOKALIKE_EMAIL_CHAR_RE.search(value):
+ raise serializers.ValidationError(
+ "Enter an email address using standard dots and no hidden characters.",
+ code="lookalike_characters_not_allowed",
+ )
+
+
class EmailLookupHandler:
@staticmethod
def users_matching_email(email: str, queryset: Optional[QuerySet] = None) -> QuerySet:
diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.py
index 263a6be23c39..7168b205b946 100644
--- a/posthog/helpers/tests/test_email_utils.py
+++ b/posthog/helpers/tests/test_email_utils.py
@@ -21,6 +21,7 @@ from posthog.helpers.email_utils import (
ESPSuppressionReason,
_get_esp_suppression_cache_key,
check_esp_suppression,
+ reject_lookalike_email_characters,
reject_plus_addressed_email,
sanitize_display_name,
sanitize_email_string,
@@ -238,6 +239,46 @@ class TestRejectPlusAddressedEmail(SimpleTestCase):
reject_plus_addressed_email("[email protected]")
+class TestRejectLookalikeEmailCharacters(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("ideographic_full_stop", "user@ph\u3002example.com"),
+ ("fullwidth_full_stop", "user@ph\uff0eexample.com"),
+ ("small_full_stop", "user@ph\ufe52example.com"),
+ ("one_dot_leader", "user@ph\u2024example.com"),
+ ("halfwidth_ideographic_full_stop", "user@ph\uff61example.com"),
+ ("zero_width_space", "user@example\u200b.com"),
+ ("zero_width_joiner_in_local_part", "us\[email protected]"),
+ ("word_joiner", "user@exam\u2060ple.com"),
+ ("byte_order_mark", "\[email protected]"),
+ ("soft_hyphen", "user@exa\u00admple.com"),
+ ("right_to_left_mark", "[email protected]\u200f"),
+ ("right_to_left_override", "user@\u202eexample.com"),
+ ]
+ )
+ def test_rejects_lookalike_dots_and_hidden_characters(self, _name: str, email: str) -> None:
+ with self.assertRaises(serializers.ValidationError) as ctx:
+ reject_lookalike_email_characters(email)
+ self.assertEqual(ctx.exception.get_codes(), ["lookalike_characters_not_allowed"])
+
+ @parameterized.expand(
+ [
+ ("ascii", "[email protected]"),
+ ("idn_domain", "user@ex\u00e4mple.com"),
+ ("non_latin_domain", "user@\u4f8b\u3048.jp"),
+ ("vietnamese", "nguy\u1ec5n@v\u00ed-d\u1ee5.vn"),
+ ("polish", "\u0142ukasz@\u017c\u00f3\u0142w.pl"),
+ ("russian", "\u0438\u0432\u0430\u043d@\u043f\u0440\u0438\u043c\u0435\u0440.\u0440\u0444"),
+ (
+ "greek",
+ "user@\u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1.\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae",
+ ),
+ ]
+ )
+ def test_allows_addresses_without_lookalike_characters(self, _name: str, email: str) -> None:
+ reject_lookalike_email_characters(email)
+
+
class TestUserExistsWithStrippedAlias(TestCase):
def test_no_match(self):
self.assertFalse(EmailValidationHelper.user_exists_with_stripped_alias("[email protected]"))