From af03867f008fee71112e49ef92e3209eefd2a8ae Mon Sep 17 00:00:00 2001 From: Ramiro Morales Date: Sun, 13 Feb 2011 02:37:52 +0000 Subject: [PATCH] [1.2.X] Fixed #13007 -- Made cookie parsing resilent to the presence of cookies with invalid characters in their names. Thanks Warlax for the report, Ubercore for his work on a fix and Jannis and Luke for review and guidance. Backport of [15523] from trunk. git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.2.X@15524 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/http/__init__.py | 22 ++++++++++++++++++++- tests/regressiontests/httpwrappers/tests.py | 9 ++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/django/http/__init__.py b/django/http/__init__.py index e585a713de..b9e4470d87 100644 --- a/django/http/__init__.py +++ b/django/http/__init__.py @@ -276,13 +276,33 @@ class CompatCookie(SimpleCookie): return val, encoded + def load(self, rawdata, ignore_parse_errors=False): + if ignore_parse_errors: + self.bad_cookies = [] + self._BaseCookie__set = self._loose_set + SimpleCookie.load(self, rawdata) + if ignore_parse_errors: + self._BaseCookie__set = self._strict_set + for key in self.bad_cookies: + del self[key] + + _strict_set = BaseCookie._BaseCookie__set + + def _loose_set(self, key, real_value, coded_value): + try: + self._strict_set(key, real_value, coded_value) + except CookieError: + self.bad_cookies.append(key) + dict.__setitem__(self, key, None) + + def parse_cookie(cookie): if cookie == '': return {} if not isinstance(cookie, BaseCookie): try: c = CompatCookie() - c.load(cookie) + c.load(cookie, ignore_parse_errors=True) except CookieError: # Invalid cookie return {} diff --git a/tests/regressiontests/httpwrappers/tests.py b/tests/regressiontests/httpwrappers/tests.py index 4e946a2f10..336d9a2817 100644 --- a/tests/regressiontests/httpwrappers/tests.py +++ b/tests/regressiontests/httpwrappers/tests.py @@ -2,7 +2,8 @@ import copy import pickle import unittest -from django.http import QueryDict, HttpResponse, CompatCookie, BadHeaderError +from django.http import (QueryDict, HttpResponse, CompatCookie, BadHeaderError, + parse_cookie) class QueryDictTests(unittest.TestCase): @@ -264,3 +265,9 @@ class CookieTests(unittest.TestCase): c2 = CompatCookie() c2.load(c.output()) self.assertEqual(c['test'].value, c2['test'].value) + + def test_nonstandard_keys(self): + """ + Test that a single non-standard cookie name doesn't affect all cookies. Ticket #13007. + """ + self.assertTrue('good_cookie' in parse_cookie('good_cookie=yes;bad:cookie=yes').keys())