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
Provenance
- Commit
c9a5660- Tree
15da16d- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
fa0ceb6- Parent 2
c24f8c8
5 files changed+34 added−125 removed
modified:docs/config.rst+11 added-11 removed
132 unmodified lines133 Default: ``'session'``134 135 .. py:data:: SESSION_COOKIE_DOMAIN136 137- 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.140 141+ Not setting this value is more restricted and secure than setting it.142+143 Default: ``None``144 145+ .. versionchanged:: 2.3146+ Not set by default, does not fall back to ``SERVER_NAME``.147+148 .. py:data:: SESSION_COOKIE_PATH149 150 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 lines223 224 Inform the application what host and port it is bound to. Required225 for subdomain route matching support.226 222- 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. ::227-228- 127.0.0.1 localhost.dev229-227 If set, ``url_for`` can generate external URLs with only an application228 context instead of a request context.229 230 Default: ``None``231 232+ .. versionchanged:: 2.3233+ Does not affect ``SESSION_COOKIE_DOMAIN``.234+235 .. py:data:: APPLICATION_ROOT236 237 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 a483 unmodified linesmodified:src/flask/helpers.py+10 added
1 unmodified line2 import pkgutil3 import socket4 import sys5 import typing as t6+import warnings7 from datetime import datetime8 from functools import lru_cache9 from functools import update_wrapper10 from threading import RLock651 unmodified lines662 :type value: str663 664 :return: True if string is an IP address665 :rtype: bool666+667+ .. 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+ )675+676 for family in (socket.AF_INET, socket.AF_INET6):677 try:678 socket.inet_pton(family, value)679 except OSError:15 unmodified linesmodified:src/flask/sessions.py+7 added-54 removed
1 import hashlib2 import typing as t3-import warnings3 from collections.abc import MutableMapping4 from datetime import datetime5 from datetime import timezone6 7 from itsdangerous import BadSignature8 from itsdangerous import URLSafeTimedSerializer9 from werkzeug.datastructures import CallbackDict10 12-from .helpers import is_ip11 from .json.tag import TaggedJSONSerializer12 13 if t.TYPE_CHECKING: # pragma: no cover14 import typing_extensions as te163 unmodified lines178 """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``."""179 return app.config["SESSION_COOKIE_NAME"]180 181 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.185 186- 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.187 189- 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 """192-191 rv = app.config["SESSION_COOKIE_DOMAIN"]192+ return rv if rv else None193 195- # set explicitly, or cached from SERVER_NAME detection196- # if False, return None197- if rv is not None:198- return rv if rv else None199-200- rv = app.config["SERVER_NAME"]201-202- # server name not set, cache False to return none next time203- if not rv:204- app.config["SESSION_COOKIE_DOMAIN"] = False205- return None206-207- # 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(".")210-211- 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 None222-223- ip = is_ip(rv)224-225- 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- )232-233- # 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}"237-238- app.config["SESSION_COOKIE_DOMAIN"] = rv239- return rv240-194 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`` or175 unmodified linesmodified:tests/test_basic.py+2 added-60 removed
249 unmodified lines250 assert client.post("/set", data={"value": "42"}).data == b"value set"251 assert client.get("/get").data == b"42"252 253 254-def test_session_using_server_name(app, client):255- app.config.update(SERVER_NAME="example.com")254+def test_session_path(app, client):255+ app.config.update(APPLICATION_ROOT="/foo")256 257 @app.route("/")258 def index():259 flask.session["testing"] = 42260 return "Hello World"261 262- 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 cookie266-267-268-def test_session_using_server_name_and_port(app, client):269- app.config.update(SERVER_NAME="example.com:8080")270-271- @app.route("/")272- def index():273- flask.session["testing"] = 42274- return "Hello World"275-276- 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 cookie280-281-282-def test_session_using_server_name_port_and_path(app, client):283- app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")284-285- @app.route("/")286- def index():287- flask.session["testing"] = 42288- return "Hello World"289-262 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()264 265 266 def test_session_using_application_root(app, client):267 class PrefixPathMiddleware:83 unmodified lines351 cookie = rv.headers["set-cookie"].lower()352 assert "samesite=lax" in cookie353 354 385-def test_session_localhost_warning(recwarn, app, client):386- app.config.update(SERVER_NAME="localhost:5000")387-388- @app.route("/")389- def index():390- flask.session["testing"] = 42391- return "testing"392-393- 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)397-398-399-def test_session_ip_warning(recwarn, app, client):400- app.config.update(SERVER_NAME="127.0.0.1:5000")401-402- @app.route("/")403- def index():404- flask.session["testing"] = 42405- return "testing"406-407- 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)411-412-355 def test_missing_session(app):356 app.secret_key = None357 358 def expect_exception(f, *args, **kwargs):1507 unmodified linesmodified:CHANGES.rst+4 added
35 unmodified lines36 - ``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`44 45 46 Version 2.2.447 -------------1423 unmodified lines