From 09fce7cc15cf2217deba87bb840e19fe035b8990 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89loi=20Rivard?= Date: Mon, 5 May 2025 15:08:48 +0200 Subject: [PATCH] fix: avoid verify to raise an exception when the code argument is non-ascii --- docs/changelog.rst | 7 +++++++ src/otpauth/_rfc4226.py | 5 ++++- src/otpauth/_rfc6238.py | 6 +++++- tests/test_hotp.py | 3 +++ tests/test_totp.py | 1 + 5 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5b36f32..d568c69 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,6 +9,13 @@ Changelog For **v1**, please head over to https://pythonhosted.org/otpauth/ +2.1.2 +----- + +**Unreleased** + +- Avoid ``verify`` to raise an exception when the ``code`` argument is non-ascii. + 2.1.1 ----- diff --git a/src/otpauth/_rfc4226.py b/src/otpauth/_rfc4226.py index 2eb583d..845ef68 100644 --- a/src/otpauth/_rfc4226.py +++ b/src/otpauth/_rfc4226.py @@ -37,7 +37,10 @@ def verify(self, code: int, counter: int) -> bool: """ if len(str(code)) > self.digit: return False - return hmac.compare_digest(self.string_code(self.generate(counter)), self.string_code(code)) + try: + return hmac.compare_digest(self.string_code(self.generate(counter)), self.string_code(code)) + except (TypeError, ValueError): + return False def to_uri(self, label: str, issuer: str, counter: int) -> str: """Generate the otpauth protocal string for HOTP. diff --git a/src/otpauth/_rfc6238.py b/src/otpauth/_rfc6238.py index 0ff21aa..fbc88f9 100644 --- a/src/otpauth/_rfc6238.py +++ b/src/otpauth/_rfc6238.py @@ -42,7 +42,11 @@ def verify(self, code: int, timestamp: t.Optional[int] = None) -> bool: """ if len(str(code)) > self.digit: return False - return hmac.compare_digest(self.string_code(self.generate(timestamp)), self.string_code(code)) + + try: + return hmac.compare_digest(self.string_code(self.generate(timestamp)), self.string_code(code)) + except (TypeError, ValueError): + return False def to_uri(self, label: str, issuer: str) -> str: """Generate the otpauth protocal string for TOTP. diff --git a/tests/test_hotp.py b/tests/test_hotp.py index b87b733..afb9f2e 100644 --- a/tests/test_hotp.py +++ b/tests/test_hotp.py @@ -18,8 +18,11 @@ def test_verify(self): # due to not match self.assertFalse(self.hotp.verify(12345, 0)) + self.assertFalse(self.hotp.verify("●●●●●●", 0)) + self.assertTrue(self.hotp.verify(170566, 0)) + def test_to_uri(self): uri = self.hotp.to_uri("Typlog:lepture.com", "Authlib", 0) expected = ( diff --git a/tests/test_totp.py b/tests/test_totp.py index 2cbffff..fe9de1d 100644 --- a/tests/test_totp.py +++ b/tests/test_totp.py @@ -19,6 +19,7 @@ def test_verify(self): # due to not match self.assertFalse(self.totp.verify(12345, FIXED_TIME)) + self.assertFalse(self.totp.verify("●●●●●●", FIXED_TIME)) self.assertTrue(self.totp.verify(129815, FIXED_TIME))