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): carry next through email MFA + verification links (#68509)

Yasen0b9c2ce16198
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index 5e25bf18e300..a81e949560d9 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -174,8 +174,12 @@ export const loginLogic = kea<loginLogicType>([
breakpoint()
// Clear any previous passkey errors when submitting with password
actions.clearGeneralError()
+ // Forward `next` so email verification / login-verification links can resume the
+ // original destination (e.g. an /oauth/authorize flow). The link carries `next`, so
+ // it works even when opened in a different browser than the one that started login.
+ const next = getRelativeNextPath(router.values.searchParams['next'], location) || undefined
try {
- return await api.create<any>('api/login', { email, password })
+ return await api.create<any>('api/login', { email, password, ...(next ? { next } : {}) })
} catch (e) {
const { code, detail } = e as Record<string, any>
if (code === '2fa_required') {
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index 523c71c8ec81..a378bec210cc 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -164,7 +164,18 @@ class EmailMFARequired(APIException):
super().__init__(detail=detail, code=self.default_code)
-def is_email_verified_for_login(user: User) -> bool:
+def get_safe_next_url(next_url: str | None, request: Request) -> str | None:
+ """Return next_url only when it's a safe same-origin/relative redirect target, else None.
+
+ The value is embedded into emailed verification links, so an unvalidated next
+ would be an open-redirect / phishing vector.
+ """
+ if next_url and url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}):
+ return next_url
+ return None
+
+
+def is_email_verified_for_login(user: User, next_url: str | None = None) -> bool:
"""
Send a verification email when the login policy requires it.
@@ -180,7 +191,7 @@ def is_email_verified_for_login(user: User) -> bool:
if is_email_verification_disabled(user):
return True
- EmailVerifier.create_token_and_send_email_verification(user)
+ EmailVerifier.create_token_and_send_email_verification(user, next_url)
if user.is_email_verified is False:
return False
@@ -191,6 +202,16 @@ def is_email_verified_for_login(user: User) -> bool:
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
+ next = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ write_only=True,
+ help_text=(
+ "Relative path to resume after login (e.g. an /oauth/authorize URL). "
+ "Embedded into email verification / login-verification links so the flow "
+ "can continue after the email step. Ignored unless it is a safe same-origin path."
+ ),
+ )
def to_representation(self, instance: Any) -> dict[str, Any]:
return {"success": True}
@@ -249,6 +270,7 @@ class LoginSerializer(serializers.Serializer):
)
request = self.context["request"]
+ next_url = get_safe_next_url(validated_data.get("next"), request)
existing_user = User.objects.filter(email__iexact=validated_data["email"]).first()
evaluate_auth_attempt(
@@ -291,7 +313,7 @@ class LoginSerializer(serializers.Serializer):
raise serializers.ValidationError("Invalid email or password.", code="invalid_credentials")
- if not is_email_verified_for_login(user):
+ if not is_email_verified_for_login(user, next_url):
raise serializers.ValidationError(
"Your account is awaiting verification. Please check your email for a verification link.",
code="not_verified",
@@ -316,7 +338,9 @@ class LoginSerializer(serializers.Serializer):
else:
# Email MFA flow - skip if this is a reauth (user already authenticated)
if not was_authenticated_before_login_attempt:
- email_mfa_sent = email_mfa_verifier.create_token_and_send_email_mfa_verification(request, user)
+ email_mfa_sent = email_mfa_verifier.create_token_and_send_email_mfa_verification(
+ request, user, next_url
+ )
if email_mfa_sent:
# Increment the resend throttle counter so the initial send counts towards the limit
resend_throttle = EmailMFAResendThrottle()
@@ -859,7 +883,9 @@ class EmailMFAViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):
except User.DoesNotExist:
raise serializers.ValidationError({"detail": "User not found."}, code="user_not_found")
- email_mfa_sent = email_mfa_verifier.create_token_and_send_email_mfa_verification(request, user)
+ email_mfa_sent = email_mfa_verifier.create_token_and_send_email_mfa_verification(
+ request, user, request.session.get("email_mfa_next")
+ )
if not email_mfa_sent:
raise serializers.ValidationError(
{"detail": "Could not send email MFA verification email."}, code="email_mfa_verification_email_failed"
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 8d7b8f3c0490..d6006bcafcee 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -243,7 +243,29 @@ class TestLoginAPI(APIBaseTest):
mock_is_email_available.assert_called_once()
# Assert the email was sent.
- mock_send_email_verification.assert_called_once_with(self.user)
+ mock_send_email_verification.assert_called_once_with(self.user, None)
+
+ @parameterized.expand(
+ [
+ # A relative `next` (e.g. an /oauth/authorize continuation) must be forwarded so the
+ # verification link can resume the flow.
+ ("safe_relative_next", "/oauth/authorize/?client_id=x", "/oauth/authorize/?client_id=x"),
+ # An off-origin `next` must be dropped.
+ ("unsafe_off_origin_next", "https://evil.example.com/steal", None),
+ ]
+ )
+ @patch("posthog.api.authentication.is_email_available", return_value=True)
+ @patch("posthog.api.authentication.EmailVerifier.create_token_and_send_email_verification")
+ def test_email_verification_link_carries_safe_next(
+ self, _name, next_input, expected, mock_send_email_verification, mock_is_email_available
+ ):
+ self.user.is_email_verified = False
+ self.user.save()
+ self.client.post(
+ "/api/login",
+ {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD, "next": next_input},
+ )
+ mock_send_email_verification.assert_called_once_with(self.user, expected)
@patch("posthog.api.authentication.is_email_available", return_value=True)
@patch("posthog.api.authentication.EmailVerifier.create_token_and_send_email_verification")
@@ -283,7 +305,7 @@ class TestLoginAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
mock_is_email_available.assert_called_once()
# Assert the email was sent.
- mock_send_email_verification.assert_called_once_with(self.user)
+ mock_send_email_verification.assert_called_once_with(self.user, None)
@patch("posthoganalytics.capture")
def test_user_cant_login_with_incorrect_password(self, mock_capture):
diff --git a/posthog/api/test/test_email_mfa.py b/posthog/api/test/test_email_mfa.py
index 221de7d57a55..e71945b43734 100644
--- a/posthog/api/test/test_email_mfa.py
+++ b/posthog/api/test/test_email_mfa.py
@@ -4,6 +4,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django_otp.plugins.otp_totp.models import TOTPDevice
+from parameterized import parameterized
from rest_framework import status
from posthog.helpers.email_utils import ESPSuppressionResult
@@ -47,6 +48,62 @@ class TestEmailMFAAPI(APIBaseTest):
self.assertEqual(call_args[0][0], self.user.id)
self.assertIsNotNone(call_args[0][1]) # Token should be present
+ @parameterized.expand(
+ [
+ # A relative `next` (e.g. an /oauth/authorize continuation) is forwarded into the link
+ # so the emailed login-verification link resumes the flow even in a different browser.
+ ("safe_relative_next", "/oauth/authorize/?client_id=x", "/oauth/authorize/?client_id=x"),
+ # An off-origin `next` must be dropped, never embedded into the emailed link.
+ ("unsafe_off_origin_next", "//evil.example.com/steal", None),
+ ]
+ )
+ @pytest.mark.disable_mock_email_mfa_verifier
+ @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)
+ @patch("posthog.tasks.email.send_email_mfa_link")
+ @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)
+ @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)
+ def test_email_mfa_link_carries_safe_next(
+ self,
+ _name,
+ next_input,
+ expected,
+ mock_is_http_email_available,
+ mock_is_email_available,
+ mock_send_email,
+ mock_esp_suppression,
+ ):
+ self.client.post(
+ "/api/login",
+ {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD, "next": next_input},
+ )
+ self.assertEqual(mock_send_email.call_args[0][2], expected)
+
+ @pytest.mark.disable_mock_email_mfa_verifier
+ @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)
+ @patch("posthog.tasks.email.send_email_mfa_link")
+ @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)
+ @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)
+ def test_email_mfa_resend_reuses_next(
+ self,
+ mock_is_http_email_available,
+ mock_is_email_available,
+ mock_send_email,
+ mock_esp_suppression,
+ ):
+ with freeze_time("2023-01-01T10:00:00"):
+ self.client.post(
+ "/api/login",
+ {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD, "next": "/oauth/authorize/?client_id=x"},
+ )
+ self.assertEqual(mock_send_email.call_args[0][2], "/oauth/authorize/?client_id=x")
+
+ # A resent link must resume the same destination, recovered from the session.
+ with freeze_time("2023-01-01T10:01:01"):
+ mock_send_email.reset_mock()
+ response = self.client.post("/api/login/email-mfa/resend/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(mock_send_email.call_args[0][2], "/oauth/authorize/?client_id=x")
+
@pytest.mark.disable_mock_email_mfa_verifier
@patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)
@patch("posthog.tasks.email.send_email_mfa_link")
diff --git a/posthog/api/test/test_webauthn.py b/posthog/api/test/test_webauthn.py
index 3b8de8c47437..afe0f67e2438 100644
--- a/posthog/api/test/test_webauthn.py
+++ b/posthog/api/test/test_webauthn.py
@@ -277,7 +277,7 @@ class TestWebAuthnLogin(APIBaseTest):
self.assertEqual(me_response.status_code, status.HTTP_401_UNAUTHORIZED)
mock_is_email_available.assert_called_once()
- mock_send_email_verification.assert_called_once_with(self.user)
+ mock_send_email_verification.assert_called_once_with(self.user, None)
@patch("posthog.auth.verify_passkey_authentication_response")
def test_login_with_unverified_credential_fails(self, mock_verify):
diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.py
index 5dc4483b78f8..ef3aff9426af 100644
--- a/posthog/helpers/two_factor_session.py
+++ b/posthog/helpers/two_factor_session.py
@@ -431,7 +431,9 @@ class EmailMFAVerifier:
return EmailMFACheckResult(should_send=True)
- def create_token_and_send_email_mfa_verification(self, request: HttpRequest, user: User) -> bool:
+ def create_token_and_send_email_mfa_verification(
+ self, request: HttpRequest, user: User, next_url: str | None = None
+ ) -> bool:
from posthog.tasks import email
if not self.should_send_email_mfa_verification(user).should_send:
@@ -439,9 +441,11 @@ class EmailMFAVerifier:
try:
token = email_mfa_token_generator.make_token(user)
- email.send_email_mfa_link(user.pk, token)
+ email.send_email_mfa_link(user.pk, token, next_url)
request.session["email_mfa_pending_user_id"] = user.pk
request.session["email_mfa_token_created_at"] = int(time.time())
+ # Stash so the resend endpoint can rebuild a link that resumes the same post-login destination.
+ request.session["email_mfa_next"] = next_url
mfa_logger.info(
"Email MFA verification email sent",
user_id=user.pk,
diff --git a/posthog/management/commands/test/test_set_recorder_script.py b/posthog/management/commands/test/test_set_recorder_script.py
index 3370e8b198c9..ca867c618fe7 100644
--- a/posthog/management/commands/test/test_set_recorder_script.py
+++ b/posthog/management/commands/test/test_set_recorder_script.py
@@ -7,6 +7,7 @@ from django.core.management import call_command
from parameterized import parameterized
from posthog.models import Team
+from posthog.sampling import sample_on_property
class TestSetRecorderScriptCommand(BaseTest):
@@ -115,9 +116,13 @@ class TestSetRecorderScriptCommand(BaseTest):
"--sample-rate=0.5",
)
- updated_teams = Team.objects.filter(extra_settings__has_key="recorder_script").count()
+ # Sampling is deterministic on team id, so the command must update exactly the teams
+ # that hash into the sample. Asserting a rough proportion is flaky: consecutive ids hash
+ # into a narrow band, so the count lands near 0 or near 100 rather than around 50.
+ expected_ids = {team.id for team in Team.objects.all() if sample_on_property(str(team.id), 0.5)}
+ updated_ids = set(Team.objects.filter(extra_settings__has_key="recorder_script").values_list("id", flat=True))
- assert 30 < updated_teams < 70, f"Expected roughly 50 teams updated, got {updated_teams}"
+ assert updated_ids == expected_ids
def test_bulk_updates_in_batches(self):
# Use bulk_create with a shared project to avoid 2500 individual
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index de1ba124c571..82a405bf0e3a 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -469,11 +469,12 @@ def send_email_verification(user_id: int, token: str, next_url: str | None = Non
@shared_task(**EMAIL_TASK_KWARGS)
@skip_team_scope_audit
-def send_email_mfa_link(user_id: int, token: str) -> None:
+def send_email_mfa_link(user_id: int, token: str, next_url: str | None = None) -> None:
"""Send email MFA verification link"""
user: User = User.objects.get(pk=user_id)
- verification_link = f"{settings.SITE_URL}/login/verify?email={quote(user.email)}&token={token}"
+ next_query = f"&next={quote(next_url, safe='')}" if next_url else ""
+ verification_link = f"{settings.SITE_URL}/login/verify?email={quote(user.email)}&token={token}{next_query}"
message = EmailMessage(
use_http=True,