Skip to content
Myr

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

4 files+119 added−21 removed

modified:flask/helpers.py+22 added
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""1112import os13import socket14import sys15import pkgutil16import posixpath17import mimetypes
958 unmodified lines
976 :returns: number of seconds977 :rtype: int978 """979 return td.days * 60 * 60 * 24 + td.seconds980981982def is_ip(value):983 """Determine if the given string is an IP address.984985 :param value: value to check986 :type value: str987988 :return: True if string is an IP address989 :rtype: bool990 """991992 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 True9991000 return False
modified:flask/sessions.py+54 added-21 removed
9 unmodified lines
10"""1112import uuid13import hashlib14import warnings15from base64 import b64encode, b64decode16from datetime import datetime17from werkzeug.http import http_date, parse_date18from werkzeug.datastructures import CallbackDict19from . import Markup, json20from ._compat import iteritems, text_type20from .helpers import total_seconds21from .helpers import total_seconds, is_ip2223from itsdangerous import URLSafeTimedSerializer, BadSignature2425
174 unmodified lines
200 """201 return isinstance(obj, self.null_session_class)202203 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]212212 # 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']214218 # 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 None219226 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
135 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