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(users): serialize email change and pin verification email recipient (#73010)

Tom Piccirelloa37fecfd5407
diff --git a/posthog/api/email_verification.py b/posthog/api/email_verification.py
index 9d4c7ffcf02e..7543fb27638f 100644
--- a/posthog/api/email_verification.py
+++ b/posthog/api/email_verification.py
@@ -38,8 +38,16 @@ class EmailVerifier:
@staticmethod
def create_token_and_send_email_verification(user: User, next_url: str | None = None) -> None:
token = email_verification_token_generator.make_token(user)
+ EmailVerifier.send_verification_email(user, token, next_url=next_url)
+
+ @staticmethod
+ def send_verification_email(
+ user: User, token: str, next_url: str | None = None, target_email: str | None = None
+ ) -> None:
+ # `target_email` pins the recipient to the address the token authorizes; callers with a
+ # stable email leave it None and the recipient falls back to the user's pending_email.
try:
- send_email_verification(user.pk, token, next_url)
+ send_email_verification(user.pk, token, next_url, target_email)
except Exception as e:
capture_exception(Exception(f"Verification email failed: {e}"))
raise exceptions.APIException(
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 7c14a274bd43..d2b3e704a4a7 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -843,7 +843,7 @@ class TestUserAPI(APIBaseTest):
mock_send_email_change_emails.assert_not_called()
@patch("posthog.api.user.is_email_available", return_value=True)
- @patch("posthog.api.user.EmailVerifier.create_token_and_send_email_verification")
+ @patch("posthog.api.user.EmailVerifier.send_verification_email")
def test_email_change_allowed_between_two_sso_enforced_domains_of_same_org(
self,
mock_send_email_verification,
diff --git a/posthog/api/user.py b/posthog/api/user.py
index e9a18f43c71e..161efb483d99 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -43,7 +43,7 @@ from social_django.models import UserSocialAuth
from two_factor.forms import TOTPDeviceForm
from two_factor.utils import default_device
-from posthog.api.email_verification import EmailVerifier
+from posthog.api.email_verification import EmailVerifier, email_verification_token_generator
from posthog.api.oauth.toolbar_service import (
ToolbarOAuthError,
ToolbarOAuthState,
@@ -724,9 +724,19 @@ class UserSerializer(serializers.ModelSerializer):
"You can't change your email to a domain where SSO is enforced.",
code="sso_enforced_new_email",
)
- instance.pending_email = validated_data.pop("email", None)
- instance.save()
- EmailVerifier.create_token_and_send_email_verification(instance)
+ validated_data.pop("email", None) # staged as pending_email below, not written to `email` directly
+ # Serialize concurrent email changes for this user under a row lock so the token is
+ # minted against one consistent pending_email. Without it, interleaved requests can
+ # bind a token to one address but deliver its verification email to another.
+ with transaction.atomic():
+ User.objects.select_for_update().get(pk=instance.pk)
+ instance.pending_email = new_email
+ instance.save(update_fields=["pending_email"])
+ token = email_verification_token_generator.make_token(instance)
+ # Send after the transaction commits (never inside the atomic block), pinning the
+ # recipient to the captured address so a later pending_email change can't redirect
+ # this token's verification email.
+ EmailVerifier.send_verification_email(instance, token, target_email=new_email)
if validated_data.get("notification_settings"):
validated_data["partial_notification_settings"] = validated_data.pop("notification_settings")
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 5cef069ae415..6f41bd8a2123 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -467,7 +467,9 @@ def send_password_changed_email(user_id: int) -> None:
@shared_task(**EMAIL_TASK_KWARGS)
@skip_team_scope_audit
-def send_email_verification(user_id: int, token: str, next_url: str | None = None) -> None:
+def send_email_verification(
+ user_id: int, token: str, next_url: str | None = None, target_email: str | None = None
+) -> None:
user: User = User.objects.get(pk=user_id)
next_query = f"?next={quote(next_url, safe='')}" if next_url else ""
message = EmailMessage(
@@ -482,7 +484,9 @@ def send_email_verification(user_id: int, token: str, next_url: str | None = Non
"url": f"{settings.SITE_URL}/verify_email/{user.uuid}/{token}{next_query}",
},
)
- message.add_user_recipient(user, email_override=user.pending_email)
+ # Pin the recipient to the email the token authorizes (the caller-captured `target_email`)
+ # rather than re-reading `pending_email`, which a concurrent email change could have drifted.
+ message.add_user_recipient(user, email_override=target_email if target_email is not None else user.pending_email)
message.send(send_async=False)
posthoganalytics.capture(
distinct_id=str(user.distinct_id),
diff --git a/posthog/tasks/test/test_email_verification.py b/posthog/tasks/test/test_email_verification.py
new file mode 100644
index 000000000000..0429bcd9b5fd
--- /dev/null
+++ b/posthog/tasks/test/test_email_verification.py
@@ -0,0 +1,41 @@
+from types import SimpleNamespace
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.tasks.email import send_email_verification
+
+
+class TestEmailVerificationRecipient(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # (db_pending_email, target_email, expected_recipient)
+ # A concurrent email change may have drifted pending_email to an attacker-controlled
+ # address; the verification must still go only to the address the token authorizes.
+ ("pinned_target_wins_over_drifted_pending_email", "[email protected]", "[email protected]", "[email protected]"),
+ # Callers that don't pin a target (signup, auth, admin) keep the existing behavior.
+ ("defaults_to_pending_email_without_target", "[email protected]", None, "[email protected]"),
+ ]
+ )
+ def test_verification_recipient(
+ self, _name: str, db_pending_email: str, target_email: str | None, expected: str
+ ) -> None:
+ user = SimpleNamespace(
+ pk=1,
+ uuid="u",
+ pending_email=db_pending_email,
+ distinct_id="d",
+ current_organization=SimpleNamespace(id="org"),
+ )
+ with (
+ patch("posthog.tasks.email.User.objects.get", return_value=user),
+ patch("posthog.tasks.email.posthoganalytics.capture"),
+ patch("posthog.tasks.email.EmailMessage") as MockEmailMessage,
+ ):
+ send_email_verification(user.pk, "token", target_email=target_email)
+
+ MockEmailMessage.return_value.add_user_recipient.assert_called_once_with(user, email_override=expected)