Skip to content

Commit

Permalink
Merge pull request #2866 from hmpf/vendor-session-serializer
Browse files Browse the repository at this point in the history
Vendor the PickleSerializer
  • Loading branch information
hmpf authored Mar 8, 2024
2 parents ac8e94e + 2234aa7 commit 7187a2d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion python/nav/django/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@
'django.contrib.messages.middleware.MessageMiddleware',
)

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
SESSION_SERIALIZER = 'nav.web.session_serializer.PickleSerializer'
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_COOKIE_AGE = int(_webfront_config.get('sessions', {}).get('timeout', 3600))
SESSION_COOKIE_NAME = 'nav_sessionid'
Expand Down
38 changes: 38 additions & 0 deletions python/nav/web/session_serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import pickle

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured


class PickleSerializer:
"""
Simple wrapper around pickle to be used for serializing data to be put in
cookies.
This was vendored from the version found in Django 4.2. JSONSerializer has
been the default in Django since 1.6, deprecated since 4.1 and purged from
the codebase since 5.0. What Django did not provide is a migration path:
a test showed that any access of a cookie after the serializer had been
changed lead to a rather useless exception.
PickleSerializer was removed due to it being danegerous in the
signed_cookie session backend. NAV doesn't use that see we can keep the old
serializer.
Changes from the original: A deprecation warning has been removed and
a check that it is not used with the signed_cookie session backend has been
added.
"""

def __init__(self, protocol=None):
if settings.SESSION_ENGINE == 'django.contrib.sessions.backends.signed_cookies':
raise ImproperlyConfigured(
"PickleSerializer cannot be used with signed_cookies SESSION_ENGINE"
)
self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol

def dumps(self, obj):
return pickle.dumps(obj, self.protocol)

def loads(self, data):
return pickle.loads(data)

0 comments on commit 7187a2d

Please sign in to comment.