: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): show a support error when workflows refuses the login code (#129716)
Meikel Ratzd12f1e0a0658
diff --git a/frontend/src/scenes/authentication/auth/Auth.stories.tsx b/frontend/src/scenes/authentication/auth/Auth.stories.tsxindex fcee41724d91..a2055e5fa981 100644--- a/frontend/src/scenes/authentication/auth/Auth.stories.tsx+++ b/frontend/src/scenes/authentication/auth/Auth.stories.tsx@@ -47,7 +47,7 @@ type StoryArgs = {gitlab: booleansamlAvailable: booleanssoEnforcement: 'none' | 'google-oauth2' | 'github' | 'gitlab' | 'saml'- generalError: 'none' | 'invalid_credentials' | 'no_new_organizations'+ generalError: 'none' | 'invalid_credentials' | 'no_new_organizations' | 'login_code_email_undeliverable'pendingOAuthConnection: booleanhasLoggedInBefore: booleansignedOutForSessionRisk: boolean@@ -87,7 +87,7 @@ const meta: Meta<StoryArgs> = {generalError: {control: 'select',name: 'General error',- options: ['none', 'invalid_credentials', 'no_new_organizations'],+ options: ['none', 'invalid_credentials', 'no_new_organizations', 'login_code_email_undeliverable'],},pendingOAuthConnection: { control: 'boolean', name: 'Pending OAuth connection' },hasLoggedInBefore: { control: 'boolean', name: 'Has logged in before' },@@ -121,6 +121,7 @@ export default metaconst ERROR_DETAILS: Record<string, string> = {invalid_credentials: 'Invalid email or password.',+ login_code_email_undeliverable: "We can't send email to this address, so we can't send you a login code.",}const Template: StoryFn<StoryArgs> = ({@@ -273,6 +274,10 @@ LoginStepFromSignupEntry.args = { step: 'Login', entry: 'signup' }export const LoginError: StoryFn<StoryArgs> = Template.bind({})LoginError.args = { step: 'Login', generalError: 'invalid_credentials' }+export const LoginCodeEmailUndeliverable: StoryFn<StoryArgs> = Template.bind({})+LoginCodeEmailUndeliverable.storyName = 'Login code email undeliverable'+LoginCodeEmailUndeliverable.args = { step: 'Login', generalError: 'login_code_email_undeliverable' }+export const SSOEnforced: StoryFn<StoryArgs> = Template.bind({})SSOEnforced.args = { step: 'Login', ssoEnforcement: 'google-oauth2' }diff --git a/frontend/src/scenes/authentication/auth/components/LoginErrorBanner.tsx b/frontend/src/scenes/authentication/auth/components/LoginErrorBanner.tsxindex dd2572e6c7a5..6e22b9dba457 100644--- a/frontend/src/scenes/authentication/auth/components/LoginErrorBanner.tsx+++ b/frontend/src/scenes/authentication/auth/components/LoginErrorBanner.tsx@@ -120,7 +120,9 @@ export function LoginErrorBanner(): JSX.Element | null {}}className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning">- Need help?+ {generalError.code === 'login_code_email_undeliverable'+ ? 'Contact support to get back into your account.'+ : 'Need help?'}</Link></>)}diff --git a/frontend/src/scenes/authentication/auth/loginLogic.test.ts b/frontend/src/scenes/authentication/auth/loginLogic.test.tsindex 514949136120..871c30e859d3 100644--- a/frontend/src/scenes/authentication/auth/loginLogic.test.ts+++ b/frontend/src/scenes/authentication/auth/loginLogic.test.ts@@ -215,6 +215,33 @@ describe('loginLogic', () => {expect(logic.values.codeVerificationRequired).toBe(false)expect(logic.values.codeVerificationEmail).toBe(null)})++ it('shows an undeliverable address on resend as a login error, and clears it once a resend goes out', async () => {+ const detail = "We can't send email to this address."+ useMocks({+ post: {+ '/api/login/code-based-verification/resend': () => [+ 400,+ { type: 'server_error', code: 'login_code_email_undeliverable', detail },+ ],+ },+ })++ logic.actions.resendCodeBasedVerification(null)+ await expectLogic(logic).toDispatchActions(['resendCodeBasedVerificationSuccess'])++ expect(logic.values.resendResponse).toBe(null)+ expect(logic.values.generalError).toEqual({ code: 'login_code_email_undeliverable', detail })++ const sent = { success: true, message: 'sent' }+ useMocks({ post: { '/api/login/code-based-verification/resend': () => [200, sent] } })++ logic.actions.resendCodeBasedVerification(null)+ await expectLogic(logic).toDispatchActions(['resendCodeBasedVerificationSuccess'])++ expect(logic.values.resendResponse).toEqual(sent)+ expect(logic.values.generalError).toBe(null)+ })})describe('opaque login failure', () => {diff --git a/frontend/src/scenes/authentication/auth/loginLogic.ts b/frontend/src/scenes/authentication/auth/loginLogic.tsindex 3c48705fa306..fb5c735438c5 100644--- a/frontend/src/scenes/authentication/auth/loginLogic.ts+++ b/frontend/src/scenes/authentication/auth/loginLogic.ts@@ -82,6 +82,13 @@ function precheckFallback(email: string): PrecheckResponseType {}}+function resendFailureMessage(code: string | undefined, detail: string | undefined): string {+ if (detail) {+ return detail+ }+ return code === 'too_soon' ? 'Please wait before requesting another email' : 'Failed to resend email'+}+export interface LoginForm {email: stringpassword: string@@ -407,7 +414,7 @@ export const loginLogic = kea<loginLogicType>([},],}),- loaders(({ values, cache }) => ({+ loaders(({ actions, values, cache }) => ({precheckResponse: [{ status: 'pending' } as PrecheckResponseType,{@@ -489,14 +496,15 @@ export const loginLogic = kea<loginLogicType>([try {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.const response = await api.create<any>('api/login/code-based-verification/resend')+ actions.clearGeneralError()lemonToast.success('Verification email resent')return response} catch (e) {const { code, detail } = e as Record<string, any>- if (code === 'too_soon') {- lemonToast.error(detail || 'Please wait before requesting another email')+ if (code === 'login_code_email_undeliverable') {+ actions.setGeneralError(code, detail)} else {- lemonToast.error(detail || 'Failed to resend email')+ lemonToast.error(resendFailureMessage(code, detail))}return null}diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex f7f957713780..41ca2936a6ad 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -57,7 +57,7 @@ from posthog.api.email_verification import email_verification_code_verifier, is_from posthog.auth import ACCOUNT_BLOCKED_DETAILfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, POSTHOG_INTERNAL_EMAIL_SUFFIX-from posthog.email import is_email_available+from posthog.email import EmailRecipientUndeliverableError, is_email_availablefrom posthog.event_usage import report_user_logged_in, report_user_password_resetfrom posthog.exceptions_capture import capture_exceptionfrom posthog.geoip import get_geoip_properties@@ -264,6 +264,19 @@ class CodeBasedVerificationRequired(APIException):super().__init__(detail=detail, code=self.default_code)+class LoginCodeEmailUndeliverable(APIException):+ status_code = 400+ default_detail = "We can't send email to this address, so we can't send you a login code."+ default_code = "login_code_email_undeliverable"+++def _send_login_code(request: HttpRequest, user: User, *, is_resend: bool = False) -> bool:+ try:+ return code_based_verifier.create_and_send_code_based_verification(request, user, is_resend=is_resend)+ except EmailRecipientUndeliverableError:+ raise LoginCodeEmailUndeliverable()++class EmailVerificationPending(APIException):"""Login blocked because the signup email is unverified and a fresh code was just sent.Like CodeBasedVerificationRequired, `detail` carries data (the user uuid) so the frontend@@ -451,9 +464,7 @@ class LoginSerializer(serializers.Serializer):else:# Code-based verification - skip if this is a reauth (user already authenticated)if not was_authenticated_before_login_attempt:- code_based_verification_sent = code_based_verifier.create_and_send_code_based_verification(- request, user- )+ code_based_verification_sent = _send_login_code(request, user)if code_based_verification_sent:# Increment the resend throttle counter so the initial send counts towards the limitresend_throttle = CodeBasedVerificationResendThrottle()@@ -1240,7 +1251,7 @@ class CodeBasedVerificationViewSet(NonCreatingViewSetMixin, viewsets.GenericViewexcept User.DoesNotExist:raise serializers.ValidationError({"detail": "User not found."}, code="user_not_found")- if not code_based_verifier.create_and_send_code_based_verification(request, user, is_resend=True):+ if not _send_login_code(request, user, is_resend=True):raise serializers.ValidationError({"detail": "Could not send verification code."},code="code_based_verification_email_failed",diff --git a/posthog/api/test/test_code_based_verification.py b/posthog/api/test/test_code_based_verification.pyindex a338a4047a54..4b8ac283e800 100644--- a/posthog/api/test/test_code_based_verification.py+++ b/posthog/api/test/test_code_based_verification.py@@ -1,11 +1,12 @@+from collections.abc import Iteratorfrom contextlib import contextmanagerimport pytestimport time_machinefrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patch-from django.test import SimpleTestCase+from django.test import SimpleTestCase, override_settingsfrom django_otp.plugins.otp_totp.models import TOTPDevicefrom parameterized import parameterized@@ -14,6 +15,7 @@ from rest_framework import statusfrom posthog.api.authentication import CodeBasedVerificationSerializerfrom posthog.helpers.email_utils import ESPSuppressionResultfrom posthog.helpers.two_factor_session import CODE_MAX_ATTEMPTS+from posthog.models.instance_setting import override_instance_configVERIFY_URL = "/api/login/code-based-verification/"RESEND_URL = "/api/login/code-based-verification/resend/"@@ -35,6 +37,27 @@ def enable_code_sending():yield mock_send+@contextmanager+def workflows_refuses_the_recipient() -> Iterator[None]:+ refusal = MagicMock(status_code=422, text="error")+ refusal.json.return_value = {"type": "invalid_request", "code": "recipient_suppressed"}+ with (+ patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed),+ 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),+ override_instance_config("EMAIL_HOST", "localhost"),+ override_settings(+ CUSTOMER_IO_API_KEY="cio-key",+ POSTHOG_TRANSACTIONAL_EMAIL_API_KEY="phs_test",+ POSTHOG_HOST="https://us.posthog.com",+ ),+ patch.dict("posthog.email.WORKFLOWS_TEMPLATE_ID_MAP", {"code_based_verification": "tmpl-1"}),+ patch("posthog.email.posthoganalytics.feature_enabled", return_value=True),+ patch("posthog.email.requests.post", return_value=refusal),+ ):+ yield++class TestCodeBasedVerificationAPI(APIBaseTest):CONFIG_AUTO_LOGIN = False@@ -71,6 +94,15 @@ class TestCodeBasedVerificationAPI(APIBaseTest):response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})self.assertEqual(response.status_code, status.HTTP_200_OK)+ @pytest.mark.disable_mock_code_based_verifier+ def test_login_is_refused_when_the_code_email_cannot_be_delivered(self):+ with workflows_refuses_the_recipient():+ response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "login_code_email_undeliverable")+ self.assertEqual(self.client.get("/api/users/@me/").status_code, status.HTTP_401_UNAUTHORIZED)+@pytest.mark.disable_mock_code_based_verifierdef test_wrong_code_is_rejected_but_correct_code_still_works(self):with enable_code_sending() as mock_send:@@ -148,6 +180,18 @@ class TestCodeBasedVerificationAPI(APIBaseTest):)self.assertEqual(self.client.post(VERIFY_URL, {"code": second_code}).status_code, status.HTTP_200_OK)+ @pytest.mark.disable_mock_code_based_verifier+ def test_resend_reports_an_undeliverable_address_instead_of_sent(self):+ with time_machine.travel("2024-01-01T10:00:00", tick=False) as frozen:+ with enable_code_sending() as mock_send:+ self._trigger(mock_send)+ frozen.move_to("2024-01-01T10:01:01") # past the 1/min resend throttle+ with workflows_refuses_the_recipient():+ response = self.client.post(RESEND_URL)++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "login_code_email_undeliverable")+@pytest.mark.disable_mock_code_based_verifierdef test_resend_does_not_reset_the_failed_attempt_cap(self):with time_machine.travel("2024-01-01T10:00:00", tick=False) as frozen, enable_code_sending() as mock_send:diff --git a/posthog/email.py b/posthog/email.pyindex e7950ccbb720..09651bd76f61 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -567,7 +567,7 @@ def _send_via_http(template_name: str,properties: dict,will_retry: bool = True,-) -> None:+) -> list[str]:"""Sends emails using the Customer.io API, or the Workflows transactional email API where the flag matches"""if not is_http_email_service_available():raise Exception("Missing Customer.io API key")@@ -575,12 +575,13 @@ def _send_via_http(if not current_task or current_task.request.is_eager:# The dedicated client blocks on its flush, which would hold the request. The web process keeps running,# so the global client delivers in the background. ScopedCapture keeps the cloud-only guard.- _send_via_http_batch(ScopedCapture(posthoganalytics), to, campaign_key, template_name, properties, will_retry)- return+ return _send_via_http_batch(+ ScopedCapture(posthoganalytics), to, campaign_key, template_name, properties, will_retry+ )# A dedicated client, because the global one may never flush before a Celery worker exits.with ph_scoped_capture(event_region=get_instance_region()) as capture:- _send_via_http_batch(capture, to, campaign_key, template_name, properties, will_retry)+ return _send_via_http_batch(capture, to, campaign_key, template_name, properties, will_retry)def _send_via_http_batch(@@ -590,10 +591,10 @@ def _send_via_http_batch(template_name: str,properties: dict,will_retry: bool = True,-) -> None:+) -> list[str]:sent_count = 0already_sent_count = 0 # delivered in a prior run — not a failure if the batch later aborts- undeliverable_count = 0+ undeliverable: list[str] = []dest: dict[str, str] | None = Nonetry:for dest in to:@@ -611,7 +612,7 @@ def _send_via_http_batch(if sent is None:# sent_at stays unset, so raise_if_delivery_rejected tells a synchronous caller nothing went out.EMAIL_SEND_COUNTER.labels(outcome="undeliverable", transport="http").inc()- undeliverable_count += 1+ undeliverable.append(dest["raw_email"])continueprovider, provider_response = sent@@ -656,7 +657,7 @@ def _send_via_http_batch()# Count every recipient that did not get through (the failing one + any not yet attempted),# so `failed` shares the per-recipient unit with `sent` instead of registering once per batch.- unsent_count = len(to) - already_sent_count - sent_count - undeliverable_count+ unsent_count = len(to) - already_sent_count - sent_count - len(undeliverable)EMAIL_SEND_COUNTER.labels(outcome="failed", transport="http").inc(unsent_count)if not retrying:EMAIL_SEND_DROPPED_COUNTER.labels(transport="http").inc(unsent_count)@@ -664,6 +665,7 @@ def _send_via_http_batch(# The retry sends the same idempotency key, so Workflows returns an email it already queued instead of# sending a second one, and recipients already marked sent are skipped.raise+ return undeliverabledef _send_via_smtp(@@ -773,6 +775,10 @@ class EmailDeliveryError(Exception):"""A synchronous send returned without the provider accepting the email."""+class EmailRecipientUndeliverableError(Exception):+ """The provider refused the address as undeliverable, such as after a hard bounce, so no email went out."""++def was_email_delivered(campaign_key: str, email: str) -> bool:"""Return whether the provider accepted this campaign for this recipient (MessagingRecord.sent_at set)."""return MessagingRecord.objects.filter(@@ -914,10 +920,10 @@ def _send_email_now(use_http: Optional[bool] = False,properties: Optional[dict] = None,retry_in_worker: bool = False,-) -> None:+) -> list[str]:if use_http and is_http_email_service_available():try:- _send_via_http(+ return _send_via_http(to=to,campaign_key=campaign_key,template_name=template_name,@@ -951,6 +957,7 @@ def _send_email_now("properties": properties,})+ return []elif is_smtp_email_service_available():_send_via_smtp(to=to,@@ -961,6 +968,7 @@ def _send_email_now(headers=headers,reply_to=reply_to,)+ return []else:raise Exception("Email is not enabled in this instance.")@@ -1021,8 +1029,12 @@ class EmailMessage:email = email_override or user.emailself.add_recipient(email=email, name=user.first_name, distinct_id=str(user.distinct_id))- def send(self, send_async: bool = True, *, retry: bool = True) -> None:- """Synchronous callers can disable eager retries to own transport failure handling."""+ def send(self, send_async: bool = True, *, retry: bool = True) -> list[str]:+ """Synchronous callers can disable eager retries to own transport failure handling.++ Returns the addresses the provider refused as undeliverable. Only a synchronous send learns them, so an+ asynchronous send returns an empty list.+ """if not self.to:raise ValueError("No recipients provided! Use EmailMessage.add_recipient() first!")@@ -1041,19 +1053,20 @@ class EmailMessage:if send_async:_send_email.apply_async(kwargs=kwargs)- elif retry:+ return []+ if retry:# Celery runs eager retries at once, so each Workflows timeout would hold the request for another 10s.- _send_email.apply(kwargs={**kwargs, "retry_in_worker": True})- else:- _send_email_now(- campaign_key=self.campaign_key,- to=self.to,- subject=self.subject,- headers=self.headers,- txt_body=self.txt_body,- html_body=self.html_body,- template_name=self.template_name,- reply_to=self.reply_to,- use_http=self.use_http,- properties=self.properties,- )+ outcome = _send_email.apply(kwargs={**kwargs, "retry_in_worker": True})+ return outcome.result if outcome.successful() else []+ return _send_email_now(+ campaign_key=self.campaign_key,+ to=self.to,+ subject=self.subject,+ headers=self.headers,+ txt_body=self.txt_body,+ html_body=self.html_body,+ template_name=self.template_name,+ reply_to=self.reply_to,+ use_http=self.use_http,+ properties=self.properties,+ )diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.pyindex 52e79fc4ab23..ed73435e6f92 100644--- a/posthog/helpers/two_factor_session.py+++ b/posthog/helpers/two_factor_session.py@@ -20,7 +20,7 @@ from rest_framework.exceptions import PermissionDeniedfrom two_factor.utils import default_devicefrom posthog.cloud_utils import is_dev_mode-from posthog.email import is_email_available, is_http_email_service_available+from posthog.email import EmailRecipientUndeliverableError, is_email_available, is_http_email_service_availablefrom posthog.helpers.email_utils import ESPSuppressionReason, check_esp_suppressionfrom posthog.models.organization import Organizationfrom posthog.models.user import User@@ -55,7 +55,7 @@ mfa_logger = structlog.get_logger("posthog.auth.mfa")LOGIN_CODE_VERIFICATION_COUNTER = Counter("login_code_verification_total","Transitions in the code-based login-verification flow.",- labelnames=["result"], # sent | resent | send_failed | success | invalid | locked_out+ labelnames=["result"], # sent | resent | send_failed | undeliverable | success | invalid | locked_out)@@ -418,6 +418,7 @@ class CodeBasedVerifier:def create_and_send_code_based_verification(self, request: HttpRequest, user: User, *, is_resend: bool = False) -> bool:+ """Raises EmailRecipientUndeliverableError when the address cannot receive the code."""from posthog.tasks import emailif not self.should_send_code_based_verification(user).should_send:@@ -442,6 +443,10 @@ class CodeBasedVerifier:user_last_login=str(user.last_login) if user.last_login else None,)return True+ except EmailRecipientUndeliverableError:+ LOGIN_CODE_VERIFICATION_COUNTER.labels(result="undeliverable").inc()+ mfa_logger.info("Code-based verification email refused as undeliverable", user_id=user.pk)+ raiseexcept Exception as e:LOGIN_CODE_VERIFICATION_COUNTER.labels(result="send_failed").inc()mfa_logger.exception(diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 32cc7e503649..7396ceb4e778 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -24,6 +24,7 @@ from posthog.dataclasses import frozenfrom posthog.email import (EMAIL_TASK_KWARGS,EmailMessage,+ EmailRecipientUndeliverableError,get_email_team_and_org_context,is_email_available,is_http_email_service_available,@@ -734,7 +735,8 @@ def send_code_based_verification(user_id: int, code: str) -> None:},)message.add_user_recipient(user)- message.send(send_async=False)+ if message.send(send_async=False):+ raise EmailRecipientUndeliverableError("the login code email was refused as undeliverable")posthoganalytics.capture(distinct_id=str(user.distinct_id),event="login verification code sent",diff --git a/posthog/test/test_email.py b/posthog/test/test_email.pyindex f57a6b652426..b18e7ea5354a 100644--- a/posthog/test/test_email.py+++ b/posthog/test/test_email.py@@ -645,7 +645,9 @@ class TestEmail(BaseTest):with self.assertRaises(WorkflowsEmailError):message.send(send_async=False, retry=False)else:- message.send(send_async=False, retry=False)+ undeliverable = message.send(send_async=False, retry=False)+ refused = "transactional email workflows rejected" in expected_events+ self.assertEqual(undeliverable, ["[email protected]"] if refused else [])providers = ["workflows" if call.args[0].startswith("https://us.posthog.com") else "customer_io"