: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): let a throttled 2fa login still use a backup code (#112469)
posthog[bot]10f9ad720e7a
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 0cfab1428527..21fca8393d51 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -75,6 +75,7 @@ from posthog.helpers.two_factor_session import (clear_two_factor_session_flags,code_based_verifier,has_passkeys,+ is_backup_code_attempt,normalize_verification_code,set_two_factor_verified_in_session,)@@ -89,6 +90,7 @@ from posthog.rate_limit import (CodeBasedVerificationThrottle,LoginPrecheckThrottle,SSOLoginThrottle,+ TwoFactorBackupCodeThrottle,TwoFactorThrottle,UserPasswordResetThrottle,)@@ -771,7 +773,7 @@ class TwoFactorViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):serializer_class = TwoFactorSerializerqueryset = User.objects.none()permission_classes = (permissions.AllowAny,)- throttle_classes = [TwoFactorThrottle]+ throttle_classes = [TwoFactorThrottle, TwoFactorBackupCodeThrottle]def _token_is_valid(self, request, user: User, device) -> Response:login(request, user, backend="django.contrib.auth.backends.ModelBackend")@@ -888,6 +890,22 @@ class TwoFactorViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):detail="Passkey verification failed. Please try again.", code="2fa_passkey_failed")+ @staticmethod+ def _too_many_attempts_message(throttle_info: dict[str, Any] | None, can_use_backup_code: bool) -> str:+ locked_until = (throttle_info or {}).get("locked_until")+ if locked_until is None:+ wait = "in a moment"+ else:+ seconds = max(1, math.ceil((locked_until - timezone.now()).total_seconds()))+ if seconds < 60:+ wait = f"in {seconds} second{'s' if seconds != 1 else ''}"+ else:+ minutes = math.ceil(seconds / 60)+ wait = f"in {minutes} minute{'s' if minutes != 1 else ''}"+ if can_use_backup_code:+ return f"Too many attempts. Try again {wait}, or enter one of your backup codes."+ return f"Too many attempts. Try again {wait}."+def _handle_totp_2fa(self, request: Request, user: User, token: str) -> Response:"""Handle TOTP token or backup code 2FA authentication.@@ -904,26 +922,34 @@ class TwoFactorViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):ValidationError: If token verification fails"""with transaction.atomic():- # First try TOTP devicetotp_device = default_device(user)- if totp_device:- is_allowed = totp_device.verify_is_allowed()- if not is_allowed[0]:- raise serializers.ValidationError(detail="Too many attempts.", code="2fa_too_many_attempts")- if totp_device.verify_token(token):- return self._token_is_valid(request, user, totp_device)- totp_device.throttle_increment()-- # Then try backup codes# Backup codes are in place in case a user's device is lost or unavailable.# They can be consumed in any order; each token will be removed from the# database as soon as it is used.static_device = StaticDevice.objects.filter(user=user).first()- if static_device and static_device.verify_token(token):- # Send email notification when backup code is used- send_two_factor_auth_backup_code_used_email.delay(user.id)- return self._token_is_valid(request, user, static_device)+ # Check the token against one device only. A wrong code then counts against that+ # device's throttle alone, and a locked authenticator leaves the backup codes usable.+ if totp_device and not is_backup_code_attempt(token):+ device, other_device = totp_device, static_device+ else:+ device, other_device = static_device, totp_device++ is_allowed, throttle_info = device.verify_is_allowed() if device else (True, None)+ if device and is_allowed and device.verify_token(token):+ if other_device:+ other_device.throttle_reset()+ if device is static_device:+ send_two_factor_auth_backup_code_used_email.delay(user.id)+ return self._token_is_valid(request, user, device)++ # Raise after the transaction commits, so the failed attempt verify_token recorded is kept.+ if not is_allowed:+ can_use_backup_code = device is totp_device and static_device and static_device.token_set.exists()+ raise serializers.ValidationError(+ detail=self._too_many_attempts_message(throttle_info, bool(can_use_backup_code)),+ code="2fa_too_many_attempts",+ )raise serializers.ValidationError(detail="Invalid authentication code", code="2fa_invalid")def create(self, request: Request, *args: Any, **kwargs: Any) -> Any:diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 5e2d5b6553be..8add530d90b2 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -1,5 +1,4 @@import json-import timeimport uuidfrom collections.abc import Callablefrom datetime import UTC, datetime, timedelta@@ -989,24 +988,26 @@ class TestTwoFactorAPI(APIBaseTest):response = self.client.get("/api/users/@me/")assert response.status_code == status.HTTP_401_UNAUTHORIZED, response.json()- def test_2fa_throttling(self):+ @parameterized.expand([("authenticator_code", "000000"), ("backup_code", "zzzz7777")])+ def test_2fa_throttling(self, _name: str, wrong_token: str) -> None:self.user.totpdevice_set.create(name="default", key=random_hex(), digits=6) # type: ignore+ StaticDevice.objects.create(user=self.user, name="backup").token_set.create(token="abcd2345")self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(- self.client.post("/api/login/token", {"token": "abcdefg"}).json()["code"],- "2fa_invalid",- )- self.assertEqual(- self.client.post("/api/login/token", {"token": "abcdefg"}).json()["code"],- "2fa_too_many_attempts",- )+ with time_machine.travel(timezone.now(), tick=False):+ self.assertEqual(+ self.client.post("/api/login/token", {"token": wrong_token}).json()["code"],+ "2fa_invalid",+ )+ response = self.client.post("/api/login/token", {"token": wrong_token}).json()+ self.assertEqual(response["code"], "2fa_too_many_attempts")+ self.assertTrue(response["detail"].startswith("Too many attempts. Try again in 1 second"))@patch("posthog.api.authentication.send_two_factor_auth_backup_code_used_email")def test_login_with_backup_code(self, mock_send_email):"""Test that a user can log in using a backup code instead of TOTP"""self.user.totpdevice_set.create(name="default", key=random_hex(), digits=6) # type: ignorestatic_device = StaticDevice.objects.create(user=self.user, name="backup")- static_device.token_set.create(token="123456")+ static_device.token_set.create(token="abcd2345")# First authenticate with username/passwordresponse = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})@@ -1014,7 +1015,7 @@ class TestTwoFactorAPI(APIBaseTest):self.assertEqual(response.json()["code"], "2fa_required")# Then authenticate with backup code- response = self.client.post("/api/login/token", {"token": "123456"})+ response = self.client.post("/api/login/token", {"token": "abcd2345"})self.assertEqual(response.status_code, status.HTTP_200_OK)# Verify we're logged in@@ -1023,7 +1024,7 @@ class TestTwoFactorAPI(APIBaseTest):self.assertEqual(response.json()["email"], self.user.email)# Verify the backup code was consumed (can't be reused)- self.assertFalse(static_device.token_set.filter(token="123456").exists())+ self.assertFalse(static_device.token_set.filter(token="abcd2345").exists())# Verify email was triggeredmock_send_email.delay.assert_called_once_with(self.user.id)@@ -1033,13 +1034,13 @@ class TestTwoFactorAPI(APIBaseTest):"""Test that backup codes are one-time use only"""self.user.totpdevice_set.create(name="default", key=random_hex(), digits=6) # type: ignorestatic_device = StaticDevice.objects.create(user=self.user, name="backup")- static_device.token_set.create(token="123456")+ static_device.token_set.create(token="abcd2345")# First authenticate with username/passwordself.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})# Use backup code once- response = self.client.post("/api/login/token", {"token": "123456"})+ response = self.client.post("/api/login/token", {"token": "abcd2345"})self.assertEqual(response.status_code, status.HTTP_200_OK)# Verify email was triggered@@ -1048,41 +1049,35 @@ class TestTwoFactorAPI(APIBaseTest):# Log outself.client.logout()- # Wait for throttling to expire- time.sleep(2)-# Try to authenticate again with same backup codeself.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- response = self.client.post("/api/login/token", {"token": "123456"})+ response = self.client.post("/api/login/token", {"token": "abcd2345"})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["code"], "2fa_invalid")@patch("posthog.api.authentication.send_two_factor_auth_backup_code_used_email")def test_backup_codes_work_when_totp_device_is_throttled(self, mock_send_email):- """Test that backup codes still work even if TOTP device is throttled"""- self.user.totpdevice_set.create(name="default", key=random_hex(), digits=6) # type: ignore+ totp_device = self.user.totpdevice_set.create(name="default", key=random_hex(), digits=6) # type: ignorestatic_device = StaticDevice.objects.create(user=self.user, name="backup")- static_device.token_set.create(token="123456")+ static_device.token_set.create(token="abcd2345")- # First authenticate with username/passwordself.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- # Trigger TOTP throttling with invalid attempts- self.client.post("/api/login/token", {"token": "000000"})- self.client.post("/api/login/token", {"token": "000000"})-- # Wait for throttling to expire- import time-- time.sleep(2)+ with time_machine.travel(timezone.now(), tick=False):+ self.client.post("/api/login/token", {"token": "000000"})+ response = self.client.post("/api/login/token", {"token": "000000"})+ self.assertEqual(+ response.json()["detail"],+ "Too many attempts. Try again in 1 second, or enter one of your backup codes.",+ )- # Backup code should still work- response = self.client.post("/api/login/token", {"token": "123456"})+ response = self.client.post("/api/login/token", {"token": "abcd2345"})self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Verify email was triggeredmock_send_email.delay.assert_called_once_with(self.user.id)+ totp_device.refresh_from_db()+ self.assertEqual(totp_device.throttling_failure_count, 0)+def test_passkey_2fa_begin_requires_pending_session(self):"""Test that passkey 2FA begin requires a pending login session"""from posthog.models.webauthn_credential import WebauthnCredentialdiff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.pyindex daa00c2b842c..969505087fab 100644--- a/posthog/helpers/two_factor_session.py+++ b/posthog/helpers/two_factor_session.py@@ -247,6 +247,17 @@ def normalize_verification_code(value: str) -> str:return CODE_NOISE_RE.sub("", unicodedata.normalize("NFKC", value or ""))+# Authenticator apps show 6 digits, while StaticToken.random_token() backup codes are 8 base32+# characters, so the shape of a 2FA login token is enough to tell which device it is for.+TOTP_TOKEN_RE = re.compile(r"[0-9]{6}")+++def is_backup_code_attempt(token: object) -> bool:+ """Whether a 2FA login token is checked against the backup codes rather than the authenticator.+ Each device then keeps its own throttle, so a locked authenticator does not lock the backup codes."""+ return isinstance(token, str) and bool(token) and not TOTP_TOKEN_RE.fullmatch(token)++# Failed-attempt budget for a pending login is tracked in Redis so the cap is enforced atomically# (INCR) rather than via a raceable session read-modify-write, which parallel guesses could sidestep.CODE_ATTEMPTS_REDIS_KEY_PREFIX = "code_based_verification_attempts"diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 9ca758c7072f..171399a94233 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -1169,14 +1169,25 @@ class CodeBasedVerificationResendThrottle(UserOrEmailRateThrottle):class TwoFactorThrottle(UserOrEmailRateThrottle):"""- Rate limiting for TOTP/backup code verification during 2FA login.+ Rate limiting for TOTP and passkey verification during 2FA login.Uses the pending 2FA user ID from session to throttle per-user.+ Backup codes count against TwoFactorBackupCodeThrottle instead, so a user who runs out of+ authenticator attempts can still recover with a backup code."""scope = "two_factor"rate = "6/20minutes"+ def applies_to(self, request) -> bool:+ from posthog.helpers.two_factor_session import is_backup_code_attempt++ token = request.data.get("token") if isinstance(request.data, dict) else None+ return not is_backup_code_attempt(token)+def get_cache_key(self, request, view):+ if not self.applies_to(request):+ return None+user_id = request.session.get("user_authenticated_but_no_2fa")if user_id:ident = hashlib.sha256(str(user_id).encode()).hexdigest()@@ -1185,6 +1196,14 @@ class TwoFactorThrottle(UserOrEmailRateThrottle):return super().get_cache_key(request, view)+class TwoFactorBackupCodeThrottle(TwoFactorThrottle):+ scope = "two_factor_backup_code"+ rate = "6/20minutes"++ def applies_to(self, request) -> bool:+ return not super().applies_to(request)++class UserAuthenticationThrottle(UserOrEmailRateThrottle):scope = "user_authentication"rate = "5/minute"diff --git a/posthog/test/test_two_factor_enforcement.py b/posthog/test/test_two_factor_enforcement.pyindex 8535338042b6..edb1cf36bf98 100644--- a/posthog/test/test_two_factor_enforcement.py+++ b/posthog/test/test_two_factor_enforcement.py@@ -685,3 +685,6 @@ class TestUserTwoFactorSessionIntegration(TestCase):response = client.post("/api/login/token/", {"token": "123456"})self.assertEqual(response.status_code, 429)++ response = client.post("/api/login/token/", {"token": "abcd2345"})+ self.assertEqual(response.status_code, 400, "Backup codes have their own rate limit")