Merge pull request #2607 from FadhelC/SameSite-cookie-feature
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Added support for cookie SameSite attribute
authored by David Lord · committed by GitHub · parents 8ff0cef, 382b135 · Browse files · 6 files·+67 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+67 added−7 removed
- tests:+29 added−0 removed
- other:+38 added−7 removed
Provenance
- Commit
e21abd9- Tree
cf6f997- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
8ff0cef- Parent 2
382b135
6 files changed+67 added−7 removed
modified:docs/config.rst+13 added-2 removed
206 unmodified lines207 sense.208 209 Default: ``False``210 211+.. py:data:: SESSION_COOKIE_SAMESITE212+213+ Restrict how cookies are sent with requests from external sites. Can214+ be set to ``'Lax'`` (recommended) or ``'Strict'``.215+ See :ref:`security-cookie`.216+217+ Default: ``None``218+219+ .. versionadded:: 1.0220+221 .. py:data:: PERMANENT_SESSION_LIFETIME222 223 If ``session.permanent`` is true, the cookie's expiration will be set this224 number of seconds in the future. Can either be a145 unmodified lines370 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,371 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``372 373 .. versionchanged:: 1.0364-374 ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See375 :ref:`logging` for information about configuration.376 377 Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment378 variable.379 380+ Added :data:`SESSION_COOKIE_SAMESITE` to control the session381+ cookie's ``SameSite`` option.382 383+384 Configuring from Files385 ----------------------386 387 Configuration becomes more useful if you can store it in a separate file,258 unmodified lines646 647 # or via open_instance_resource:648 with app.open_instance_resource('application.cfg') as f:649 config = f.read()638-modified:docs/security.rst+13 added-3 removed
182 unmodified lines183 response.headers['X-XSS-Protection'] = '1; mode=block'184 185 - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection186 187+188+.. _security-cookie:189+190 Set-Cookie options191 ~~~~~~~~~~~~~~~~~~192 193 These options can be added to a ``Set-Cookie`` header to improve their2 unmodified lines196 197 - ``Secure`` limits cookies to HTTPS traffic only.198 - ``HttpOnly`` protects the contents of cookies from being read with199 JavaScript.197-- ``SameSite`` ensures that cookies can only be requested from the same198- domain that created them. It is not supported by Flask yet.200+- ``SameSite`` restricts how cookies are sent with requests from201+ external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``.202+ ``Lax`` prevents sending cookies with CSRF-prone requests from203+ external sites, such as submitting a form. ``Strict`` prevents sending204+ cookies with all external requests, including following regular links.205 206 ::207 208 app.config.update(209 SESSION_COOKIE_SECURE=True,210 SESSION_COOKIE_HTTPONLY=True,211+ SESSION_COOKIE_SAMESITE='Lax',212 )213 207- response.set_cookie('username', 'flask', secure=True, httponly=True)214+ response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax')215 216 Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after217 the given time, or the current time plus the age, respectively. If neither218 option is set, the cookie will be removed when the browser is closed. ::24 unmodified lines243 244 - https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies245 - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie246 247+.. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attribute248+249+250 HTTP Public Key Pinning (HPKP)251 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~252 253 This tells the browser to authenticate with the server using only the specific7 unmodified linesmodified:flask/app.py+1 added
282 unmodified lines283 'SESSION_COOKIE_DOMAIN': None,284 'SESSION_COOKIE_PATH': None,285 'SESSION_COOKIE_HTTPONLY': True,286 'SESSION_COOKIE_SECURE': False,287+ 'SESSION_COOKIE_SAMESITE': None,288 'SESSION_REFRESH_EACH_REQUEST': True,289 'MAX_CONTENT_LENGTH': None,290 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),291 'TRAP_BAD_REQUEST_ERRORS': None,1922 unmodified linesmodified:flask/sessions.py+10 added-1 removed
247 unmodified lines248 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.249 """250 return app.config['SESSION_COOKIE_SECURE']251 252+ def get_cookie_samesite(self, app):253+ """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the254+ ``SameSite`` attribute. This currently just returns the value of255+ the :data:`SESSION_COOKIE_SAMESITE` setting.256+ """257+ return app.config['SESSION_COOKIE_SAMESITE']258+259 def get_expiration_time(self, app, session):260 """A helper method that returns an expiration date for the session261 or ``None`` if the session is linked to the browser session. The262 default implementation returns now + the permanent session105 unmodified lines368 return369 370 httponly = self.get_cookie_httponly(app)371 secure = self.get_cookie_secure(app)372+ samesite = self.get_cookie_samesite(app)373 expires = self.get_expiration_time(app, session)374 val = self.get_signing_serializer(app).dumps(dict(session))375 response.set_cookie(376 app.session_cookie_name,1 unmodified line378 expires=expires,379 httponly=httponly,380 domain=domain,381 path=path,374- secure=secure382+ secure=secure,383+ samesite=samesite384 )modified:tests/test_basic.py+29 added
317 unmodified lines318 APPLICATION_ROOT='/test',319 SESSION_COOKIE_DOMAIN='.example.com',320 SESSION_COOKIE_HTTPONLY=False,321 SESSION_COOKIE_SECURE=True,322+ SESSION_COOKIE_SAMESITE='Lax',323 SESSION_COOKIE_PATH='/'324 )325 326 @app.route('/')6 unmodified lines333 assert 'domain=.example.com' in cookie334 assert 'path=/' in cookie335 assert 'secure' in cookie336 assert 'httponly' not in cookie337+ assert 'samesite' in cookie338 339 340+def test_session_using_samesite_attribute(app, client):341+ @app.route('/')342+ def index():343+ flask.session['testing'] = 42344+ return 'Hello World'345+346+ app.config.update(SESSION_COOKIE_SAMESITE='invalid')347+348+ with pytest.raises(ValueError):349+ client.get('/')350+351+ app.config.update(SESSION_COOKIE_SAMESITE=None)352+ rv = client.get('/')353+ cookie = rv.headers['set-cookie'].lower()354+ assert 'samesite' not in cookie355+356+ app.config.update(SESSION_COOKIE_SAMESITE='Strict')357+ rv = client.get('/')358+ cookie = rv.headers['set-cookie'].lower()359+ assert 'samesite=strict' in cookie360+361+ app.config.update(SESSION_COOKIE_SAMESITE='Lax')362+ rv = client.get('/')363+ cookie = rv.headers['set-cookie'].lower()364+ assert 'samesite=lax' in cookie365+366+367 def test_session_localhost_warning(recwarn, app, client):368 app.config.update(369 SERVER_NAME='localhost:5000',370 )1522 unmodified linesmodified:tox.ini+1 added-1 removed
14 unmodified lines15 greenlet16 blinker17 python-dotenv18 19- lowest: Werkzeug==0.919+ lowest: Werkzeug==0.1420 lowest: Jinja2==2.421 lowest: itsdangerous==0.2122 lowest: Click==4.023 41 unmodified lines