: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): bind the email verification code to its target address (#91816)
Alex Lidera8f5fb85d601
diff --git a/posthog/api/email_verification.py b/posthog/api/email_verification.pyindex 9cddb4c6830e..10a80cc17702 100644--- a/posthog/api/email_verification.py+++ b/posthog/api/email_verification.py@@ -90,7 +90,10 @@ class EmailVerificationCodeVerifier:if target is None and user.is_email_verified is not False:target = user.pending_emailissued_at = int(time.time())- code = code_based_verification_token_generator.make_code(user, issued_at)+ # Bind the code to the address it is mailed to. Without this, two email changes in the+ # same second derive the same code. A code sent to an address the user owns could then+ # verify a different staged address.+ code = code_based_verification_token_generator.make_code(user, issued_at, target or "")# Write the state before the send, so a delivered code can always verify.get_client().set(self._state_key(user.pk), f"{issued_at}:{target or ''}", ex=CODE_TTL_SECONDS)send_email_verification_code(user.pk, code, target)@@ -140,7 +143,7 @@ class EmailVerificationCodeVerifier:expected_target = (user.pending_email or "") if user.is_email_verified is not False else ""if target != expected_target:return False- return code_based_verification_token_generator.check_code(user, code, issued_at)+ return code_based_verification_token_generator.check_code(user, code, issued_at, target)def invalidate(self, user: User) -> None:try:diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 66d552257ea3..783ef858be4c 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -29,6 +29,7 @@ from posthog.api.email_verification import email_verification_code_verifier, emafrom posthog.api.oauth.toolbar_service import ToolbarOAuthState, build_toolbar_oauth_state, new_state_noncefrom posthog.api.user import UserSerializerfrom posthog.constants import AvailableFeature+from posthog.helpers.two_factor_session import code_based_verification_token_generatorfrom posthog.models import Team, Userfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthRefreshToken@@ -3327,6 +3328,18 @@ class TestEmailVerificationCodeAPI(APIBaseTest):assert self.user.is_email_verifiedassert self.user.email != "[email protected]"+ def test_codes_for_different_addresses_in_the_same_second_do_not_collide(self):+ # Two email changes in the same second must not derive the same code. The code binds to the+ # address it authorizes. So a code mailed to an address the user owns cannot verify a+ # different staged address.+ issued_at = 1_700_000_000+ code_owned = code_based_verification_token_generator.make_code(self.user, issued_at, "[email protected]")+ code_victim = code_based_verification_token_generator.make_code(self.user, issued_at, "[email protected]")+ assert code_owned != code_victim+ assert not code_based_verification_token_generator.check_code(+ self.user, code_owned, issued_at, "[email protected]"+ )+def test_code_dies_when_a_different_pending_address_is_staged(self):self.user.is_email_verified = Trueself.user.pending_email = "[email protected]"diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.pyindex 2ea335e212cd..f0bcdfee5122 100644--- a/posthog/helpers/two_factor_session.py+++ b/posthog/helpers/two_factor_session.py@@ -316,17 +316,22 @@ class CodeBasedVerificationTokenGenerator(PasswordResetTokenGenerator):the login attempt's issuance time, valid for CODE_TTL_SECONDS, and rotatesautomatically on login, password change, email change, or deactivation."""- def make_code(self, user: AbstractBaseUser, issued_at: int) -> str:- """Deterministic CODE_LENGTH-digit code for this user and issuance time."""+ def make_code(self, user: AbstractBaseUser, issued_at: int, target: str = "") -> str:+ """Deterministic CODE_LENGTH-digit code for this user and issuance time.++ `target` binds the code to the address it authorizes. Without it, two sends for the same+ user in the same second derive the same code. A code mailed to one address could then+ verify another. Login and signup have no target and use the default.+ """digest = salted_hmac(self.key_salt,- self._make_hash_value(user, issued_at),+ self._make_hash_value(user, issued_at, target),secret=self.secret,algorithm=self.algorithm,).hexdigest()return f"{int(digest, 16) % (10**CODE_LENGTH):0{CODE_LENGTH}d}"- def check_code(self, user: AbstractBaseUser, code: str, issued_at: int) -> bool:+ def check_code(self, user: AbstractBaseUser, code: str, issued_at: int, target: str = "") -> bool:"""Constant-time compare against the expected code, rejecting expired codes.Brute-force resistance does not come from the code's entropy (6 digits is@@ -337,15 +342,19 @@ class CodeBasedVerificationTokenGenerator(PasswordResetTokenGenerator):return Falseif int(time.time()) - issued_at > CODE_TTL_SECONDS:return False- return constant_time_compare(self.make_code(user, issued_at), code)+ return constant_time_compare(self.make_code(user, issued_at, target), code)- def _make_hash_value(self, user: AbstractBaseUser, timestamp: int) -> str:- """Include last_login and is_active to invalidate tokens after use or deactivation."""+ def _make_hash_value(self, user: AbstractBaseUser, timestamp: int, target: str = "") -> str:+ """Include last_login and is_active to invalidate tokens after use or deactivation.++ `target` is the address an email change code authorizes, so a code cannot verify a+ different address. Login and signup leave it empty.+ """from posthog.models.user import Userusable_user: User = User.objects.get(pk=user.pk)login_timestamp = "" if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None)- return f"{usable_user.pk}{usable_user.email}{usable_user.password}{usable_user.is_active}{login_timestamp}{timestamp}"+ return f"{usable_user.pk}{usable_user.email}{usable_user.password}{usable_user.is_active}{login_timestamp}{timestamp}{target}"code_based_verification_token_generator = CodeBasedVerificationTokenGenerator()