Skip to content
Myr

refactor session cookie domain logic

Before adoption: this commit came in with the history the project adopted, so no landing records it.

cache result of session cookie domain add warnings for session cookie domain issues add changelog

authored by David Lord · committed by David Lord · parent c3d49e2 · Browse files · 4 files+106 added−32 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+106 added−32 removed

  • tests:+36 added−0 removed
  • other:+70 added−32 removed

4 files+106 added−32 removed

modified:flask/helpers.py+10 added-8 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""1112import os13import socket14import sys15import pkgutil16import posixpath17import mimetypes
959 unmodified lines
977 :rtype: int978 """979 return td.days * 60 * 60 * 24 + td.seconds980980def is_ip(ip):981 """Returns the if the string received is an IP or not.981983 :param string: the string to check if it an IP or not984 :param var_name: the name of the string that is being checked982def is_ip(value):983 """Determine if the given string is an IP address.984986 :returns: True if string is an IP, False if not987 :rtype: boolean985 :param value: value to check986 :type value: str987988 :return: True if string is an IP address989 :rtype: bool990 """989 import socket991992 for family in (socket.AF_INET, socket.AF_INET6):993 try:993 socket.inet_pton(family, ip)994 socket.inet_pton(family, value)995 except socket.error:996 pass997 else:998 return True9991000 return False
modified:flask/sessions.py+53 added-24 removed
9 unmodified lines
10"""1112import uuid13import hashlib14from warnings import warn14import warnings15from base64 import b64encode, b64decode16from datetime import datetime17from werkzeug.http import http_date, parse_date18from werkzeug.datastructures import CallbackDict
181 unmodified lines
200 """201 return isinstance(obj, self.null_session_class)202203 def get_cookie_domain(self, app):204 """Helpful helper method that returns the cookie domain that should205 be used for the session cookie if session cookies are used.204 """Returns the domain that should be set for the session cookie.205 206 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise207 falls back to detecting the domain based on ``SERVER_NAME``.208 209 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is210 updated to avoid re-running the logic.211 """207 if app.config['SESSION_COOKIE_DOMAIN'] is not None:208 return app.config['SESSION_COOKIE_DOMAIN']209 if app.config['SERVER_NAME'] is not None:210 # chop off the port which is usually not supported by browsers211 rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]212213 # Google chrome does not like cookies set to .localhost, so214 # we just go with no domain then. Flask documents anyways that215 # cross domain cookies need a fully qualified domain name216 if rv == '.localhost':217 rv = None213 rv = app.config['SESSION_COOKIE_DOMAIN']214219 # If we infer the cookie domain from the server name we need220 # to check if we are in a subpath. In that case we can't221 # set a cross domain cookie.222 if rv is not None:223 path = self.get_cookie_path(app)224 if path != '/':225 rv = rv.lstrip('.')215 # set explicitly, or cached from SERVER_NAME detection216 # if False, return None217 if rv is not None:218 return rv if rv else None219227 return rv220 rv = app.config['SERVER_NAME']221222 # server name not set, cache False to return none next time223 if not rv:224 app.config['SESSION_COOKIE_DOMAIN'] = False225 return None226227 # chop off the port which is usually not supported by browsers228 # remove any leading '.' since we'll add that later229 rv = rv.rsplit(':', 1)[0].lstrip('.')230231 if '.' not in rv:232 # Chrome doesn't allow names without a '.'233 # this should only come up with localhost234 # hack around this by not setting the name, and show a warning235 warnings.warn(236 '"{rv}" is not a valid cookie domain, it must contain a ".".'237 ' Add an entry to your hosts file, for example'238 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)239 )240 app.config['SESSION_COOKIE_DOMAIN'] = False241 return None242243 ip = is_ip(rv)244245 if ip:246 warnings.warn(247 'The session cookie domain is an IP address. This may not work'248 ' as intended in some browsers. Add an entry to your hosts'249 ' file, for example "localhost.localdomain", and use that'250 ' instead.'251 )252253 # if this is not an ip and app is mounted at the root, allow subdomain254 # matching by adding a '.' prefix255 if self.get_cookie_path(app) == '/' and not ip:256 rv = '.' + rv257258 app.config['SESSION_COOKIE_DOMAIN'] = rv259 return rv260261 def get_cookie_path(self, app):262 """Returns the path for which the cookie should be valid. The263 default implementation uses the value from the ``SESSION_COOKIE_PATH``264 config var if it's set, and falls back to ``APPLICATION_ROOT`` or
103 unmodified lines
368 return self.session_class()369370 def save_session(self, app, session, response):371 domain = self.get_cookie_domain(app)340 if domain is not None:341 if is_ip(domain):342 warnings.warn("IP introduced in SESSION_COOKIE_DOMAIN", RuntimeWarning)372 path = self.get_cookie_path(app)373374 # Delete case. If there is no session we bail early.375 # If the session was modified to be empty we remove the
24 unmodified lines
modified:tests/test_basic.py+36 added
349 unmodified lines
350 assert 'secure' in cookie351 assert 'httponly' not in cookie352353354def test_session_localhost_warning(recwarn):355 app = flask.Flask(__name__)356 app.config.update(357 SECRET_KEY='testing',358 SERVER_NAME='localhost:5000',359 )360361 @app.route('/')362 def index():363 flask.session['testing'] = 42364 return 'testing'365366 rv = app.test_client().get('/', 'http://localhost:5000/')367 assert 'domain' not in rv.headers['set-cookie'].lower()368 w = recwarn.pop(UserWarning)369 assert '"localhost" is not a valid cookie domain' in str(w.message)370371372def test_session_ip_warning(recwarn):373 app = flask.Flask(__name__)374 app.config.update(375 SECRET_KEY='testing',376 SERVER_NAME='127.0.0.1:5000',377 )378379 @app.route('/')380 def index():381 flask.session['testing'] = 42382 return 'testing'383384 rv = app.test_client().get('/', 'http://127.0.0.1:5000/')385 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()386 w = recwarn.pop(UserWarning)387 assert 'cookie domain is an IP' in str(w.message)388389390def test_missing_session():391 app = flask.Flask(__name__)392393 def expect_exception(f, *args, **kwargs):
1493 unmodified lines
modified:CHANGES+7 added
32 unmodified lines
33 bad response types. The error messages have been improved to describe why the34 type is invalid. (`#2256`_)35- Add ``routes`` CLI command to output routes registered on the application.36 (`#2259`_)37- Show warning when session cookie domain is a bare hostname or an IP38 address, as these may not behave properly in some browsers, such as Chrome.39 (`#2282`_)40- Allow IP address as exact session cookie domain. (`#2282`_)41- ``SESSION_COOKIE_DOMAIN`` is set if it is detected through ``SERVER_NAME``.42 (`#2282`_)4344.. _#1489: https://github.com/pallets/flask/pull/148945.. _#1898: https://github.com/pallets/flask/pull/189846.. _#1936: https://github.com/pallets/flask/pull/1936
1 unmodified line
48.. _#2223: https://github.com/pallets/flask/pull/222349.. _#2254: https://github.com/pallets/flask/pull/225450.. _#2256: https://github.com/pallets/flask/pull/225651.. _#2259: https://github.com/pallets/flask/pull/225952.. _#2282: https://github.com/pallets/flask/pull/22825354Version 0.12.155--------------56
608 unmodified lines