Python not recognizing cookies in request header
Question: At work we've been developing a python application (django specifically) that
intermittently seem to behave as if it is not recognizing some of the cookies
being sent in the request.

The issue does not always occur, but once it does it seems to persist
indefinitely. Sometimes the issue can be resolved by clearing the cookies and
reloading the page.

The cookies are all valid (though there are quite a few 3rd-party ones in the
mix) and within the maximum size supported by both the servers and the
browsers.


Answer: # Solution

If your application needs to interpret the "Cookie" header in Python using
"SimpleCookie" (widely used by Python libraries and frameworks), and your
website's domain has cookies set that are outside of your control, avoid
versions of Python where Issue #22931 (<https://bugs.python.org/issue22931>)
was in play.

The bug existed in several versions of 3.3.x, 3.4.x and 3.5.x as well as
2.7.9.

# Details

The issue's diagnosis ended up being fairly simple, but I thought I'd share it
here using more general language since searching for the issue didn't yield
any useful results until it had been narrowed down to the existence of
specific **valid** characters in a few cookies.

In Python 2.7.9 (and several versions of 3.x) there is a bug where cookies
with "[" or "]" in their values causes the parsing of the "Cookie" header to
fail silently. Since the square brackets are valid characters for a cookie
value (<http://www.rfc-editor.org/rfc/rfc6265.txt>), and commonly used in 3rd
party libraries the issue can be detrimental to cookie driven functionality in
a web application.

It is particularly elusive because termination of the cookie parsing only
appears to occur once it attempts to parse the first cookie with a square
bracket in the value. This means that if the cookies happen to be sent in a
different order the issue may not occur.

**For example**

If the request header is formatted as `Cookie: important_cookie=foobar;
bad_character=[` than "important_cookie"'s value would be available in the
application -- however it would not have been if the request header had been
`Cookie: bad_character=[; important_cookie=foobar`.

* * *

Once you know that the square brackets are causing the issue, it is fairly
easy to find the underlying bug that was reported in Python, but honing in on
the underlying issue can be a chore.

