Skip to content

Commit

Permalink
ignore malformed cookie instead of raising an exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Aviram Hassan authored and aviramha committed Mar 18, 2020
1 parent 0cb2d90 commit c63f22f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 2 additions & 0 deletions docs/requests.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ Cookies are exposed as a regular dictionary interface.

For example: `request.cookies.get('mycookie')`

Cookies are ignored in case of an invalid cookie. (RFC2109)

#### Body

There are a few different interfaces for returning the body of the request:
Expand Down
5 changes: 4 additions & 1 deletion starlette/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ def cookies(self) -> typing.Dict[str, str]:
cookie_header = self.headers.get("cookie")
if cookie_header:
cookie = http.cookies.SimpleCookie() # type: http.cookies.BaseCookie
cookie.load(cookie_header)
try:
cookie.load(cookie_header)
except http.cookies.CookieError:
pass
for key, morsel in cookie.items():
cookies[key] = morsel.value
self._cookies = cookies
Expand Down
17 changes: 17 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,23 @@ async def app(scope, receive, send):
assert response.text == "Hello, cookies!"


def test_invalid_cookie():
async def app(scope, receive, send):
request = Request(scope, receive)
if not request.cookies:
response = Response("ok", media_type="text/plain")
else:
response = Response("not", media_type="text/plain")
await response(scope, receive, send)

client = TestClient(app)
response = client.get("/", cookies={"invalid/cookie": "test", "valid": "test2"})
assert response.text == "ok"

response = client.get("/", cookies={"valid": "test2"})
assert response.text == "not"


def test_chunked_encoding():
async def app(scope, receive, send):
request = Request(scope, receive)
Expand Down

0 comments on commit c63f22f

Please sign in to comment.