Skip to content

Commit bc5429b

Browse files
brnosouzaBruno Souza
andauthored
Add support for using utf8 compatible keys (#109)
* Add support for using utf8 compatible keys - Change: cache key arguments accept utf8 strings * Improve testcase readability --------- Co-authored-by: Bruno Souza <[email protected]>
1 parent 1eefb84 commit bc5429b

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

security/auth_throttling/__init__.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import hashlib
22
import logging
33
import time
4+
import urllib.parse
45
from math import ceil
56

67
from django.contrib.auth import REDIRECT_FIELD_NAME
@@ -43,15 +44,22 @@ def delay_message(remainder):
4344
return _("%d seconds") % ceil(remainder)
4445

4546

47+
def _to_ascii_compatible(value: str):
48+
if not value.isascii():
49+
value = urllib.parse.quote(value)
50+
51+
return value
52+
53+
4654
def _key(counter_type, counter_name):
4755
"""
4856
We store a hashed version of the key because what we generate can be
4957
too long, and it's possible the POST data we get could contain characters
5058
that memcache doesn't like.
5159
"""
5260
key = "security.authentication_throttling.%s:%s" % (
53-
counter_type,
54-
counter_name,
61+
_to_ascii_compatible(counter_type),
62+
_to_ascii_compatible(counter_name),
5563
)
5664
return hashlib.sha256(key.encode("ascii")).hexdigest()
5765

tests/tests.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from security.auth_throttling import Middleware as AuthThrottlingMiddleware
1919
from security.auth_throttling import (attempt_count, default_delay_function,
2020
delay_message, increment_counters,
21-
reset_counters)
21+
reset_counters, throttling_delay)
2222
from security.middleware import (BaseMiddleware,
2323
ContentSecurityPolicyMiddleware,
2424
DoNotTrackMiddleware,
@@ -1071,3 +1071,20 @@ def test_improper_configuration_raises(self):
10711071
"REFERRER_POLICY",
10721072
"invalid",
10731073
)
1074+
1075+
1076+
class UnicodeDataTests(TestCase):
1077+
USERNAME = "ñoñó1234"
1078+
IP_ADDRESS = "127.0.0.1"
1079+
1080+
def test_unicode_data_in_cache_key(self):
1081+
self._execute_with_unicode_data(self.USERNAME, self.IP_ADDRESS)
1082+
1083+
def _execute_with_unicode_data(self, username, ip):
1084+
try:
1085+
increment_counters(username=username, ip=ip)
1086+
reset_counters(username=username, ip=ip)
1087+
throttling_delay(username=username, ip=ip)
1088+
attempt_count(attempt_type="auth", id=username)
1089+
except Exception:
1090+
self.fail("Unicode data not allowed")

0 commit comments

Comments
 (0)