[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
This commit is contained in:
Ramiro Morales 2011-02-13 02:37:52 +00:00
parent 4bcc5012b1
commit af03867f00
2 changed files with 29 additions and 2 deletions

View File

@ -276,13 +276,33 @@ class CompatCookie(SimpleCookie):
return val, encoded 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): def parse_cookie(cookie):
if cookie == '': if cookie == '':
return {} return {}
if not isinstance(cookie, BaseCookie): if not isinstance(cookie, BaseCookie):
try: try:
c = CompatCookie() c = CompatCookie()
c.load(cookie) c.load(cookie, ignore_parse_errors=True)
except CookieError: except CookieError:
# Invalid cookie # Invalid cookie
return {} return {}

View File

@ -2,7 +2,8 @@ import copy
import pickle import pickle
import unittest import unittest
from django.http import QueryDict, HttpResponse, CompatCookie, BadHeaderError from django.http import (QueryDict, HttpResponse, CompatCookie, BadHeaderError,
parse_cookie)
class QueryDictTests(unittest.TestCase): class QueryDictTests(unittest.TestCase):
@ -264,3 +265,9 @@ class CookieTests(unittest.TestCase):
c2 = CompatCookie() c2 = CompatCookie()
c2.load(c.output()) c2.load(c.output())
self.assertEqual(c['test'].value, c2['test'].value) 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())