From 8b9a9626ec89fda3dbbaae75bbac4a903f8ca386 Mon Sep 17 00:00:00 2001 From: Changaco Date: Tue, 5 Jun 2018 10:02:51 +0200 Subject: [PATCH] restrict cookies to same-site requests by default --- liberapay/main.py | 8 ++++++++ liberapay/utils/__init__.py | 4 +++- tests/py/test_state_chain.py | 1 + 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/liberapay/main.py b/liberapay/main.py index b9ac2439d5..4bf72dd8bf 100644 --- a/liberapay/main.py +++ b/liberapay/main.py @@ -171,6 +171,14 @@ def _assert(x): ] +# Monkey patch python's stdlib +# ============================ + +from six.moves.http_cookies import Morsel + +Morsel._reserved[str('samesite')] = str('SameSite') + + # Monkey patch aspen and pando # ============================ diff --git a/liberapay/utils/__init__.py b/liberapay/utils/__init__.py index ae7e0c8c06..8ccc3676d6 100644 --- a/liberapay/utils/__init__.py +++ b/liberapay/utils/__init__.py @@ -286,7 +286,7 @@ def ensure_str(s): return s.decode('ascii') if isinstance(s, bytes) else s.encode('ascii') -def set_cookie(cookies, key, value, expires=None, httponly=True, path='/'): +def set_cookie(cookies, key, value, expires=None, httponly=True, path='/', samesite='lax'): key = ensure_str(key) cookies[key] = ensure_str(value) cookie = cookies[key] @@ -300,6 +300,8 @@ def set_cookie(cookies, key, value, expires=None, httponly=True, path='/'): cookie[str('httponly')] = True if path: cookie[str('path')] = ensure_str(path) + if samesite: + cookie[str('samesite')] = ensure_str(samesite) if website.cookie_domain: cookie[str('domain')] = ensure_str(website.cookie_domain) if website.canonical_scheme == 'https': diff --git a/tests/py/test_state_chain.py b/tests/py/test_state_chain.py index b6270f924e..f4aac95bd8 100644 --- a/tests/py/test_state_chain.py +++ b/tests/py/test_state_chain.py @@ -94,6 +94,7 @@ def test_csrf_cookie_properties(self): assert cookie[str('expires')][-4:] == str(' GMT') assert cookie[str('path')] == str('/') assert cookie[str('secure')] is True + assert cookie[str('samesite')] == str('lax') class Tests2(Harness):