Encode usernames as UTF-8 bytes for hmac.compare_digest

hmac.compare_digest() on str inputs raises TypeError if either
contains non-ASCII characters. Encode both sides as UTF-8 bytes.
Add test with non-ASCII username to prevent regressions.
This commit is contained in:
J. Nick Koston
2026-02-08 07:49:53 -06:00
parent 30662bc11b
commit 4cdd73904f
2 changed files with 15 additions and 1 deletions
+3 -1
View File
@@ -85,7 +85,9 @@ class DashboardSettings:
if not self.using_auth:
return True
# Compare in constant running time (to prevent timing attacks)
username_matches = hmac.compare_digest(username, self.username)
username_matches = hmac.compare_digest(
username.encode("utf-8"), self.username.encode("utf-8")
)
password_matches = hmac.compare_digest(
self.password_hash, password_hash(password)
)
+12
View File
@@ -258,6 +258,18 @@ def test_check_password_no_auth(dashboard_settings: DashboardSettings) -> None:
assert dashboard_settings.check_password("anyone", "anything") is True
def test_check_password_non_ascii_username(
dashboard_settings: DashboardSettings,
) -> None:
"""Test check_password handles non-ASCII usernames without TypeError."""
dashboard_settings.username = "\u00e9l\u00e8ve"
dashboard_settings.using_password = True
dashboard_settings.password_hash = password_hash("pass")
assert dashboard_settings.check_password("\u00e9l\u00e8ve", "pass") is True
assert dashboard_settings.check_password("\u00e9l\u00e8ve", "wrong") is False
assert dashboard_settings.check_password("other", "pass") is False
def test_check_password_ha_addon_no_password(
dashboard_settings: DashboardSettings,
monkeypatch: pytest.MonkeyPatch,