Skip to content

Commit 4e8f881

Browse files
authored
feat: collect metrics for totp out of sync (#18981)
Similar to invalid codes, collect metrics about sync issue to aid with impact analysis. Refs: #14710 Signed-off-by: Mike Fiedler <miketheman@gmail.com>
1 parent 5af2be9 commit 4e8f881

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

tests/unit/accounts/test_services.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,24 @@ def test_check_totp_value_reused(self, user_service):
634634

635635
assert not user_service.check_totp_value(user.id, b"123456")
636636

637+
def test_check_totp_out_of_sync(self, mocker, metrics, user_service):
638+
user = UserFactory.create()
639+
mocker.patch.object(otp, "verify_totp", side_effect=otp.OutOfSyncTOTPError)
640+
641+
with pytest.raises(otp.OutOfSyncTOTPError):
642+
user_service.check_totp_value(user.id, b"123456")
643+
644+
assert metrics.increment.calls == [
645+
pretend.call(
646+
"warehouse.authentication.two_factor.start",
647+
tags=["mechanism:check_totp_value"],
648+
),
649+
pretend.call(
650+
"warehouse.authentication.two_factor.failure",
651+
tags=["mechanism:check_totp_value", "failure_reason:out_of_sync"],
652+
),
653+
]
654+
637655
def test_check_totp_value_no_secret(self, user_service):
638656
user = UserFactory.create()
639657
with pytest.raises(otp.InvalidTOTPError):

warehouse/accounts/services.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,13 @@ def check_totp_value(self, user_id, totp_value, *, tags=None):
504504
try:
505505
if not (valid := otp.verify_totp(totp_secret, totp_value)):
506506
self._hit_2fa_ratelimits(userid=user_id)
507+
except otp.OutOfSyncTOTPError:
508+
self._metrics.increment(
509+
"warehouse.authentication.two_factor.failure",
510+
tags=tags + ["failure_reason:out_of_sync"],
511+
)
512+
self._hit_2fa_ratelimits(userid=user_id)
513+
raise otp.OutOfSyncTOTPError
507514
except otp.InvalidTOTPError:
508515
self._metrics.increment(
509516
"warehouse.authentication.two_factor.failure",

0 commit comments

Comments
 (0)