From bdae19cf6395d6bfee80864d9e87c4aec241eceb Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Tue, 2 Oct 2018 21:04:12 -0700 Subject: [PATCH] Refs #27795 -- Removed force_bytes() usage in sessions. SessionBase.decode() is the inverse operation to SessionBase.encode(). As SessionBase.encode() always returns a string, SessionBase.decode() should always be passed a string argument. Fixed the file backend, which was the only backend still passing a bytestring. --- django/contrib/sessions/backends/base.py | 3 +-- django/contrib/sessions/backends/file.py | 2 +- tests/sessions_tests/tests.py | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py index 3049d39ac7..5c50f87e34 100644 --- a/django/contrib/sessions/backends/base.py +++ b/django/contrib/sessions/backends/base.py @@ -10,7 +10,6 @@ from django.utils import timezone from django.utils.crypto import ( constant_time_compare, get_random_string, salted_hmac, ) -from django.utils.encoding import force_bytes from django.utils.module_loading import import_string # session_key should not be case sensitive because some backends can store it @@ -98,7 +97,7 @@ class SessionBase: return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii') def decode(self, session_data): - encoded_data = base64.b64decode(force_bytes(session_data)) + encoded_data = base64.b64decode(session_data.encode('ascii')) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) diff --git a/django/contrib/sessions/backends/file.py b/django/contrib/sessions/backends/file.py index fe34dea56e..25887fcf20 100644 --- a/django/contrib/sessions/backends/file.py +++ b/django/contrib/sessions/backends/file.py @@ -75,7 +75,7 @@ class SessionStore(SessionBase): def load(self): session_data = {} try: - with open(self._key_to_file(), "rb") as session_file: + with open(self._key_to_file(), "r", encoding="ascii") as session_file: file_data = session_file.read() # Don't fail if there is no data in the session file. # We may have opened the empty placeholder file. diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py index dbbde133c1..c213628dbb 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -311,7 +311,7 @@ class SessionTestsMixin: self.assertEqual(self.session.decode(encoded), data) def test_decode_failure_logged_to_security(self): - bad_encode = base64.b64encode(b'flaskdj:alkdjf') + bad_encode = base64.b64encode(b'flaskdj:alkdjf').decode('ascii') with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm: self.assertEqual({}, self.session.decode(bad_encode)) # The failed decode is logged.