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
Provenance
- Commit
f75ad9f- Tree
3997048- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
c3d49e2
4 files changed+106 added−32 removed
modified:flask/helpers.py+10 added-8 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 import os13+import socket14 import sys15 import pkgutil16 import posixpath17 import mimetypes959 unmodified lines977 :rtype: int978 """979 return td.days * 60 * 60 * 24 + td.seconds980 980-def is_ip(ip):981- """Returns the if the string received is an IP or not.981 983- :param string: the string to check if it an IP or not984- :param var_name: the name of the string that is being checked982+def is_ip(value):983+ """Determine if the given string is an IP address.984 986- :returns: True if string is an IP, False if not987- :rtype: boolean985+ :param value: value to check986+ :type value: str987+988+ :return: True if string is an IP address989+ :rtype: bool990 """989- import socket991 992 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 True999+1000 return Falsemodified:flask/sessions.py+53 added-24 removed
9 unmodified lines10 """11 12 import uuid13 import hashlib14-from warnings import warn14+import warnings15 from base64 import b64encode, b64decode16 from datetime import datetime17 from werkzeug.http import http_date, parse_date18 from werkzeug.datastructures import CallbackDict181 unmodified lines200 """201 return isinstance(obj, self.null_session_class)202 203 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]212 213- # 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']214 219- # 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 None219 227- return rv220+ rv = app.config['SERVER_NAME']221 222+ # server name not set, cache False to return none next time223+ if not rv:224+ app.config['SESSION_COOKIE_DOMAIN'] = False225+ return None226+227+ # 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('.')230+231+ 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 None242+243+ ip = is_ip(rv)244+245+ 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+ )252+253+ # 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 = '.' + rv257+258+ app.config['SESSION_COOKIE_DOMAIN'] = rv259+ return rv260+261 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`` or103 unmodified lines368 return self.session_class()369 370 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)373 374 # Delete case. If there is no session we bail early.375 # If the session was modified to be empty we remove the24 unmodified linesmodified:tests/test_basic.py+36 added
349 unmodified lines350 assert 'secure' in cookie351 assert 'httponly' not in cookie352 353 354+def test_session_localhost_warning(recwarn):355+ app = flask.Flask(__name__)356+ app.config.update(357+ SECRET_KEY='testing',358+ SERVER_NAME='localhost:5000',359+ )360+361+ @app.route('/')362+ def index():363+ flask.session['testing'] = 42364+ return 'testing'365+366+ 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)370+371+372+def 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+ )378+379+ @app.route('/')380+ def index():381+ flask.session['testing'] = 42382+ return 'testing'383+384+ 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)388+389+390 def test_missing_session():391 app = flask.Flask(__name__)392 393 def expect_exception(f, *args, **kwargs):1493 unmodified linesmodified:CHANGES+7 added
32 unmodified lines33 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`_)43 44 .. _#1489: https://github.com/pallets/flask/pull/148945 .. _#1898: https://github.com/pallets/flask/pull/189846 .. _#1936: https://github.com/pallets/flask/pull/19361 unmodified line48 .. _#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/228253 54 Version 0.12.155 --------------56 608 unmodified lines