Skip to content
Myr

Merge pull request #5054 from pallets/session-domain

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

no cookie domain by default

authored by David Lord · committed by GitHub · parents fa0ceb6, c24f8c8 · Browse files · 5 files+34 added−125 removed
This commit

State

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

Diff stats

5 files+34 added−125 removed

  • tests:+2 added−60 removed
  • other:+32 added−65 removed

5 files+34 added−125 removed

modified:docs/config.rst+11 added-11 removed
132 unmodified lines
133 Default: ``'session'``134135.. py:data:: SESSION_COOKIE_DOMAIN136137 The domain match rule that the session cookie will be valid for. If not138 set, the cookie will be valid for all subdomains of :data:`SERVER_NAME`.139 If ``False``, the cookie's domain will not be set.137 The value of the ``Domain`` parameter on the session cookie. If not set, browsers138 will only send the cookie to the exact domain it was set from. Otherwise, they139 will send it to any subdomain of the given value as well.140141 Not setting this value is more restricted and secure than setting it.142143 Default: ``None``144145 .. versionchanged:: 2.3146 Not set by default, does not fall back to ``SERVER_NAME``.147148.. py:data:: SESSION_COOKIE_PATH149150 The path that the session cookie will be valid for. If not set, the cookie151 will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.
71 unmodified lines
223224 Inform the application what host and port it is bound to. Required225 for subdomain route matching support.226222 If set, will be used for the session cookie domain if223 :data:`SESSION_COOKIE_DOMAIN` is not set. Modern web browsers will224 not allow setting cookies for domains without a dot. To use a domain225 locally, add any names that should route to the app to your226 ``hosts`` file. ::227228 127.0.0.1 localhost.dev229227 If set, ``url_for`` can generate external URLs with only an application228 context instead of a request context.229230 Default: ``None``231232 .. versionchanged:: 2.3233 Does not affect ``SESSION_COOKIE_DOMAIN``.234235.. py:data:: APPLICATION_ROOT236237 Inform the application what path it is mounted under by the application /238 web server. This is used for generating URLs outside the context of a
483 unmodified lines
modified:src/flask/helpers.py+10 added
1 unmodified line
2import pkgutil3import socket4import sys5import typing as t6import warnings7from datetime import datetime8from functools import lru_cache9from functools import update_wrapper10from threading import RLock
651 unmodified lines
662 :type value: str663664 :return: True if string is an IP address665 :rtype: bool666667 .. deprecated:: 2.3668 Will be removed in Flask 2.4.669 """670 warnings.warn(671 "The 'is_ip' function is deprecated and will be removed in Flask 2.4.",672 DeprecationWarning,673 stacklevel=2,674 )675676 for family in (socket.AF_INET, socket.AF_INET6):677 try:678 socket.inet_pton(family, value)679 except OSError:
15 unmodified lines
modified:src/flask/sessions.py+7 added-54 removed
1import hashlib2import typing as t3import warnings3from collections.abc import MutableMapping4from datetime import datetime5from datetime import timezone67from itsdangerous import BadSignature8from itsdangerous import URLSafeTimedSerializer9from werkzeug.datastructures import CallbackDict1012from .helpers import is_ip11from .json.tag import TaggedJSONSerializer1213if t.TYPE_CHECKING: # pragma: no cover14 import typing_extensions as te
163 unmodified lines
178 """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``."""179 return app.config["SESSION_COOKIE_NAME"]180181 def get_cookie_domain(self, app: "Flask") -> t.Optional[str]:184 """Returns the domain that should be set for the session cookie.182 """The value of the ``Domain`` parameter on the session cookie. If not set,183 browsers will only send the cookie to the exact domain it was set from.184 Otherwise, they will send it to any subdomain of the given value as well.185186 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise187 falls back to detecting the domain based on ``SERVER_NAME``.186 Uses the :data:`SESSION_COOKIE_DOMAIN` config.187189 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is190 updated to avoid re-running the logic.188 .. versionchanged:: 2.3189 Not set by default, does not fall back to ``SERVER_NAME``.190 """192191 rv = app.config["SESSION_COOKIE_DOMAIN"]192 return rv if rv else None193195 # set explicitly, or cached from SERVER_NAME detection196 # if False, return None197 if rv is not None:198 return rv if rv else None199200 rv = app.config["SERVER_NAME"]201202 # server name not set, cache False to return none next time203 if not rv:204 app.config["SESSION_COOKIE_DOMAIN"] = False205 return None206207 # chop off the port which is usually not supported by browsers208 # remove any leading '.' since we'll add that later209 rv = rv.rsplit(":", 1)[0].lstrip(".")210211 if "." not in rv:212 # Chrome doesn't allow names without a '.'. This should only213 # come up with localhost. Hack around this by not setting214 # the name, and show a warning.215 warnings.warn(216 f"{rv!r} is not a valid cookie domain, it must contain"217 " a '.'. Add an entry to your hosts file, for example"218 f" '{rv}.localdomain', and use that instead."219 )220 app.config["SESSION_COOKIE_DOMAIN"] = False221 return None222223 ip = is_ip(rv)224225 if ip:226 warnings.warn(227 "The session cookie domain is an IP address. This may not work"228 " as intended in some browsers. Add an entry to your hosts"229 ' file, for example "localhost.localdomain", and use that'230 " instead."231 )232233 # if this is not an ip and app is mounted at the root, allow subdomain234 # matching by adding a '.' prefix235 if self.get_cookie_path(app) == "/" and not ip:236 rv = f".{rv}"237238 app.config["SESSION_COOKIE_DOMAIN"] = rv239 return rv240194 def get_cookie_path(self, app: "Flask") -> str:195 """Returns the path for which the cookie should be valid. The196 default implementation uses the value from the ``SESSION_COOKIE_PATH``197 config var if it's set, and falls back to ``APPLICATION_ROOT`` or
175 unmodified lines
modified:tests/test_basic.py+2 added-60 removed
249 unmodified lines
250 assert client.post("/set", data={"value": "42"}).data == b"value set"251 assert client.get("/get").data == b"42"252253254def test_session_using_server_name(app, client):255 app.config.update(SERVER_NAME="example.com")254def test_session_path(app, client):255 app.config.update(APPLICATION_ROOT="/foo")256257 @app.route("/")258 def index():259 flask.session["testing"] = 42260 return "Hello World"261262 rv = client.get("/", "http://example.com/")263 cookie = rv.headers["set-cookie"].lower()264 # or condition for Werkzeug < 2.3265 assert "domain=example.com" in cookie or "domain=.example.com" in cookie266267268def test_session_using_server_name_and_port(app, client):269 app.config.update(SERVER_NAME="example.com:8080")270271 @app.route("/")272 def index():273 flask.session["testing"] = 42274 return "Hello World"275276 rv = client.get("/", "http://example.com:8080/")277 cookie = rv.headers["set-cookie"].lower()278 # or condition for Werkzeug < 2.3279 assert "domain=example.com" in cookie or "domain=.example.com" in cookie280281282def test_session_using_server_name_port_and_path(app, client):283 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")284285 @app.route("/")286 def index():287 flask.session["testing"] = 42288 return "Hello World"289262 rv = client.get("/", "http://example.com:8080/foo")291 assert "domain=example.com" in rv.headers["set-cookie"].lower()263 assert "path=/foo" in rv.headers["set-cookie"].lower()293 assert "httponly" in rv.headers["set-cookie"].lower()264265266def test_session_using_application_root(app, client):267 class PrefixPathMiddleware:
83 unmodified lines
351 cookie = rv.headers["set-cookie"].lower()352 assert "samesite=lax" in cookie353354385def test_session_localhost_warning(recwarn, app, client):386 app.config.update(SERVER_NAME="localhost:5000")387388 @app.route("/")389 def index():390 flask.session["testing"] = 42391 return "testing"392393 rv = client.get("/", "http://localhost:5000/")394 assert "domain" not in rv.headers["set-cookie"].lower()395 w = recwarn.pop(UserWarning)396 assert "'localhost' is not a valid cookie domain" in str(w.message)397398399def test_session_ip_warning(recwarn, app, client):400 app.config.update(SERVER_NAME="127.0.0.1:5000")401402 @app.route("/")403 def index():404 flask.session["testing"] = 42405 return "testing"406407 rv = client.get("/", "http://127.0.0.1:5000/")408 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()409 w = recwarn.pop(UserWarning)410 assert "cookie domain is an IP" in str(w.message)411412355def test_missing_session(app):356 app.secret_key = None357358 def expect_exception(f, *args, **kwargs):
1507 unmodified lines
modified:CHANGES.rst+4 added
35 unmodified lines
36- ``config.from_file`` can use ``text=False`` to indicate that the parser wants a37 binary file instead. :issue:`4989`38- If a blueprint is created with an empty name it raises a ``ValueError``.39 :issue:`5010`40- ``SESSION_COOKIE_DOMAIN`` does not fall back to ``SERVER_NAME``. The default is not41 to set the domain, which modern browsers interpret as an exact match rather than42 a subdomain match. Warnings about ``localhost`` and IP addresses are also removed.43 :issue:`5051`444546Version 2.2.447-------------
1423 unmodified lines