From 4511d1459810037b91faa5b506e4f75c77aa72be Mon Sep 17 00:00:00 2001 From: Florian Apolloner Date: Wed, 14 Apr 2021 13:45:24 +0200 Subject: [PATCH] Fixed #32643 -- Fixed decoding of messages in the pre-Django 3.2 format. Thanks Jan Pieter Waagmeester for the report. Regression in 2d6179c819010f6a9d00835d5893c4593c0b85a0. --- django/contrib/messages/storage/cookie.py | 3 ++- docs/releases/3.2.1.txt | 4 ++++ tests/messages_tests/test_cookie.py | 7 +++++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py index 482ac5b27b..81c436fa04 100644 --- a/django/contrib/messages/storage/cookie.py +++ b/django/contrib/messages/storage/cookie.py @@ -1,3 +1,4 @@ +import binascii import json from django.conf import settings @@ -166,7 +167,7 @@ class CookieStorage(BaseStorage): # pass except signing.BadSignature: decoded = None - except json.JSONDecodeError: + except (binascii.Error, json.JSONDecodeError): decoded = self.signer.unsign(data) if decoded: diff --git a/docs/releases/3.2.1.txt b/docs/releases/3.2.1.txt index 3de4b385c9..6b0b1576cf 100644 --- a/docs/releases/3.2.1.txt +++ b/docs/releases/3.2.1.txt @@ -40,3 +40,7 @@ Bugfixes * Fixed a regression in Django 3.2 that caused a crash of ``QuerySet.update()`` on a queryset ordered by inherited or joined fields on MySQL and MariaDB (:ticket:`32645`). + +* Fixed a regression in Django 3.2 that caused a crash when decoding a cookie + value, used by ``django.contrib.messages.storage.cookie.CookieStorage``, in + the pre-Django 3.2 format (:ticket:`32643`). diff --git a/tests/messages_tests/test_cookie.py b/tests/messages_tests/test_cookie.py index 4bc6f119af..b622b7159b 100644 --- a/tests/messages_tests/test_cookie.py +++ b/tests/messages_tests/test_cookie.py @@ -1,3 +1,4 @@ +import binascii import json import random @@ -7,7 +8,7 @@ from django.contrib.messages.storage.base import Message from django.contrib.messages.storage.cookie import ( CookieStorage, MessageDecoder, MessageEncoder, ) -from django.core.signing import get_cookie_signer +from django.core.signing import b64_decode, get_cookie_signer from django.test import SimpleTestCase, override_settings from django.utils.crypto import get_random_string from django.utils.safestring import SafeData, mark_safe @@ -183,10 +184,12 @@ class CookieTests(BaseTests, SimpleTestCase): # RemovedInDjango41Warning: pre-Django 3.2 encoded messages will be # invalid. storage = self.storage_class(self.get_request()) - messages = ['this', 'that'] + messages = ['this', Message(0, 'Successfully signed in as admin@example.org')] # Encode/decode a message using the pre-Django 3.2 format. encoder = MessageEncoder() value = encoder.encode(messages) + with self.assertRaises(binascii.Error): + b64_decode(value.encode()) signer = get_cookie_signer(salt=storage.key_salt) encoded_messages = signer.sign(value) decoded_messages = storage._decode(encoded_messages)