Merge pull request #2282 from davidism/session-cookie-domain
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Refactor session cookie domain
authored by David Lord · committed by GitHub · parents 716edfd, f75ad9f · Browse files · 4 files·+119 added−21 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+119 added−21 removed
- tests:+36 added−0 removed
- other:+83 added−21 removed
Provenance
- Commit
ff361d3- Tree
3997048- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
716edfd- Parent 2
f75ad9f
4 files changed+119 added−21 removed
modified:flask/helpers.py+22 added
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 import os13+import socket14 import sys15 import pkgutil16 import posixpath17 import mimetypes958 unmodified lines976 :returns: number of seconds977 :rtype: int978 """979 return td.days * 60 * 60 * 24 + td.seconds980+981+982+def is_ip(value):983+ """Determine if the given string is an IP address.984+985+ :param value: value to check986+ :type value: str987+988+ :return: True if string is an IP address989+ :rtype: bool990+ """991+992+ for family in (socket.AF_INET, socket.AF_INET6):993+ try:994+ socket.inet_pton(family, value)995+ except socket.error:996+ pass997+ else:998+ return True999+1000+ return Falsemodified:flask/sessions.py+54 added-21 removed
9 unmodified lines10 """11 12 import uuid13 import hashlib14+import warnings15 from base64 import b64encode, b64decode16 from datetime import datetime17 from werkzeug.http import http_date, parse_date18 from werkzeug.datastructures import CallbackDict19 from . import Markup, json20 from ._compat import iteritems, text_type20-from .helpers import total_seconds21+from .helpers import total_seconds, is_ip22 23 from itsdangerous import URLSafeTimedSerializer, BadSignature24 25 174 unmodified lines200 """201 return isinstance(obj, self.null_session_class)202 203 def get_cookie_domain(self, app):203- """Helpful helper method that returns the cookie domain that should204- 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 """206- if app.config['SESSION_COOKIE_DOMAIN'] is not None:207- return app.config['SESSION_COOKIE_DOMAIN']208- if app.config['SERVER_NAME'] is not None:209- # chop off the port which is usually not supported by browsers210- rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]212 212- # Google chrome does not like cookies set to .localhost, so213- # we just go with no domain then. Flask documents anyways that214- # cross domain cookies need a fully qualified domain name215- if rv == '.localhost':216- rv = None213+ rv = app.config['SESSION_COOKIE_DOMAIN']214 218- # If we infer the cookie domain from the server name we need219- # to check if we are in a subpath. In that case we can't220- # set a cross domain cookie.221- if rv is not None:222- path = self.get_cookie_path(app)223- if path != '/':224- 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 226- 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`` or135 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