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): normalize pasted login codes to digits (#71442)

Eleftheria Trivyzakiee2186f621dc
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index 0852de05bf0e..6d5ea3ccbe95 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -83,6 +83,14 @@ export interface CodeVerificationForm {
code: string
}
+// Email clients and manual entry can wrap the emailed code in whitespace or invisible characters
+// (zero-width family, word joiner, BOM, soft hyphen) or group it as "123-456". Fold compatibility
+// digits (e.g. fullwidth) to ASCII and drop that noise so a pasted code matches the server's 6 digits.
+const CODE_NOISE_RE = /[\s\u200b-\u200d\u2060\ufeff\u00ad-]/g
+function normalizeVerificationCode(code: string): string {
+ return (code ?? '').normalize('NFKC').replace(CODE_NOISE_RE, '')
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface loginLogicValues {
devLoginTimeSavedLabel: string | null // devLoginLogic
@@ -427,14 +435,18 @@ export const loginLogic = kea<loginLogicType>([
codeVerification: {
defaults: { code: '' } as CodeVerificationForm,
errors: ({ code }) => ({
- code: !code ? 'Please enter the code from your email' : undefined,
+ // Accept a code pasted with the whitespace/invisible characters an email client adds;
+ // reject anything that isn't 6 digits once that noise is stripped.
+ code: /^\d{6}$/.test(normalizeVerificationCode(code))
+ ? undefined
+ : 'Enter the 6-digit code from your email',
}),
submit: async ({ code }, breakpoint) => {
breakpoint()
actions.clearGeneralError()
try {
return await api.create<any>('api/login/code-based-verification', {
- code,
+ code: normalizeVerificationCode(code),
email: values.login.email,
})
} catch (e) {
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index 821ca0b9cf68..1d7d69399ef7 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -1,6 +1,8 @@
+import re
import json
import time
import datetime
+import unicodedata
from typing import Any, TypedDict, cast
from urllib.parse import urlencode
from uuid import uuid4
@@ -807,13 +809,32 @@ class TwoFactorPasskeyViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):
return Response(json.loads(options_to_json(options)))
+# Characters an email client or manual entry can inject around/within the code without the
+# user seeing them: whitespace, the zero-width family, word joiner, BOM, soft hyphen, and the
+# hyphen someone types when grouping the code as "123-456".
+_CODE_NOISE_RE = re.compile(r"[\s\u200b-\u200d\u2060\ufeff\u00ad-]")
+
+
class CodeBasedVerificationSerializer(serializers.Serializer):
- code = serializers.CharField(help_text="The 6-digit verification code emailed to the user.")
+ code = serializers.CharField(
+ help_text="The 6-digit verification code emailed to the user. Whitespace, invisible characters, "
+ "and grouping hyphens are removed and compatibility digits (e.g. fullwidth) are folded to ASCII, "
+ "so a copy-pasted code still verifies; anything that isn't then exactly 6 digits is rejected."
+ )
email = serializers.EmailField(
required=False,
help_text="Email the code was sent to. Informational; the pending login session identifies the user.",
)
+ def validate_code(self, value: str) -> str:
+ # Fold compatibility forms (fullwidth digits become ASCII) then drop the noise an email client
+ # or manual grouping injects. Require exactly 6 digits so malformed input is rejected outright
+ # rather than mining digits out of arbitrary text.
+ cleaned = _CODE_NOISE_RE.sub("", unicodedata.normalize("NFKC", value or ""))
+ if not re.fullmatch(r"\d{6}", cleaned):
+ raise serializers.ValidationError("Enter the 6-digit code from your email.")
+ return cleaned
+
class CodeBasedVerificationViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):
"""Verify the emailed login code against the pending login session and complete login."""
@@ -851,7 +872,9 @@ class CodeBasedVerificationViewSet(NonCreatingViewSetMixin, viewsets.GenericView
code="too_many_attempts",
)
- code = request.data.get("code")
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ code = serializer.validated_data.get("code")
user_id = code_based_verifier.get_pending_code_based_verification_user_id(request)
try:
user = User.objects.get(pk=user_id, is_active=True)
diff --git a/posthog/api/test/test_code_based_verification.py b/posthog/api/test/test_code_based_verification.py
index 116ae2380bd5..cb45b22dd99c 100644
--- a/posthog/api/test/test_code_based_verification.py
+++ b/posthog/api/test/test_code_based_verification.py
@@ -5,9 +5,13 @@ from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.test import SimpleTestCase
+
from django_otp.plugins.otp_totp.models import TOTPDevice
+from parameterized import parameterized
from rest_framework import status
+from posthog.api.authentication import CodeBasedVerificationSerializer
from posthog.helpers.email_utils import ESPSuppressionResult
from posthog.helpers.two_factor_session import CODE_MAX_ATTEMPTS
@@ -81,6 +85,16 @@ class TestCodeBasedVerificationAPI(APIBaseTest):
# A subsequent correct code (still under the attempt cap) succeeds.
self.assertEqual(self.client.post(VERIFY_URL, {"code": code}).status_code, status.HTTP_200_OK)
+ @pytest.mark.disable_mock_code_based_verifier
+ def test_correct_code_pasted_with_whitespace_still_verifies(self):
+ # Wiring guard: the endpoint must route the submitted code through the serializer's
+ # digit-normalization, so a code copy-pasted with surrounding whitespace logs in.
+ with enable_code_sending() as mock_send:
+ code = self._trigger(mock_send)
+ response = self.client.post(VERIFY_URL, {"code": f" {code}\n"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True})
+
@pytest.mark.disable_mock_code_based_verifier
def test_locks_out_after_max_attempts_even_with_correct_code(self):
with enable_code_sending() as mock_send:
@@ -154,3 +168,38 @@ class TestCodeBasedVerificationAPI(APIBaseTest):
response = self.client.post(VERIFY_URL, {"code": fresh_code})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["code"], "too_many_attempts")
+
+
+class TestCodeBasedVerificationSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("trailing_newline", "123456\n"),
+ ("leading_and_trailing_spaces", " 123456 "),
+ ("embedded_space", "123 456"),
+ ("grouped_with_spaces", "12 34 56"),
+ ("hyphen_grouped", "123-456"),
+ ("non_breaking_space", "\xa0123456\xa0"),
+ ("zero_width_space", "123456\u200b"),
+ ("word_joiner", "123456\u2060"),
+ ("byte_order_mark", "\ufeff123456"),
+ ("soft_hyphen", "123\u00ad456"),
+ ("fullwidth_digits", "\uff11\uff12\uff13\uff14\uff15\uff16"),
+ ]
+ )
+ def test_strips_noise_so_pasted_codes_normalize(self, _name, raw):
+ serializer = CodeBasedVerificationSerializer(data={"code": raw})
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["code"] == "123456"
+
+ @parameterized.expand(
+ [
+ ("letters_around_digits", "abc123456xyz"),
+ ("digits_embedded_in_text", "your code is 123456!"),
+ ("too_short", "12345"),
+ ("too_long", "1234567"),
+ ]
+ )
+ def test_rejects_anything_that_is_not_six_digits(self, _name, raw):
+ serializer = CodeBasedVerificationSerializer(data={"code": raw})
+ assert not serializer.is_valid()
+ assert "code" in serializer.errors