Skip to content

Commit

Permalink
Merge pull request #997 from alex/samesite
Browse files Browse the repository at this point in the history
Added support for samesite cookies

Author: alex

Reviewers: markrwilliams

Fixes: ticket:9387

Added support for SameSite cookies in `http.Request.addCookie`.
  • Loading branch information
markrwilliams committed Apr 14, 2018
2 parents de597aa + b84d152 commit 1504c34
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/twisted/web/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -1112,7 +1112,8 @@ def write(self, data):
self.channel.write(data)

def addCookie(self, k, v, expires=None, domain=None, path=None,
max_age=None, comment=None, secure=None, httpOnly=False):
max_age=None, comment=None, secure=None, httpOnly=False,
samesite=None):
"""
Set an outgoing HTTP cookie.
Expand Down Expand Up @@ -1150,6 +1151,10 @@ def addCookie(self, k, v, expires=None, domain=None, path=None,
other than HTTP (and HTTPS) requests
@type httpOnly: L{bool}
@param samesite: direct browsers not to send this cookie on
cross-origin requests
@type samesite: L{bytes} or L{unicode}
@raises: L{DeprecationWarning} if an argument is not L{bytes} or
L{unicode}.
"""
Expand Down Expand Up @@ -1190,6 +1195,12 @@ def _ensureBytes(val):
cookie = cookie + b"; Secure"
if httpOnly:
cookie = cookie + b"; HttpOnly"
if samesite:
samesite = _ensureBytes(samesite).lower()
if samesite not in [b"lax", b"strict"]:
raise ValueError(
"Invalid value for samesite: " + repr(samesite))
cookie += b"; SameSite=" + samesite
self.cookies.append(cookie)

def setResponseCode(self, code, message=None):
Expand Down
1 change: 1 addition & 0 deletions src/twisted/web/newsfragments/9387.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added support for SameSite cookies in ``http.Request.addCookie``.
17 changes: 17 additions & 0 deletions src/twisted/web/test/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -2510,6 +2510,23 @@ def test_addCookieNonStringArgument(self):
"deprecated since Twisted 16.1.")


def test_addCookieSameSite(self):
"""
L{http.Request.setCookie} supports a C{samesite} argument.
"""
self._checkCookie(
b"foo=bar; SameSite=lax", b"foo", b"bar", samesite="lax")
self._checkCookie(
b"foo=bar; SameSite=lax", b"foo", b"bar", samesite="Lax")
self._checkCookie(
b"foo=bar; SameSite=strict", b"foo", b"bar", samesite="strict")

self.assertRaises(
ValueError,
self._checkCookie,
b"", b"foo", b"bar", samesite="anything-else")


def test_firstWrite(self):
"""
For an HTTP 1.0 request, L{http.Request.write} sends an HTTP 1.0
Expand Down

0 comments on commit 1504c34

Please sign in to comment.