add config and docs for limits (#5626)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 62c56e0, c7a5388 · Browse files · 7 files·+231 added−33 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+231 added−33 removed
- tests:+54 added−21 removed
- other:+177 added−12 removed
Provenance
- Commit
6f2014d- Tree
023914d- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
62c56e0- Parent 2
c7a5388
7 files changed+231 added−33 removed
modified:docs/config.rst+45 added-3 removed
257 unmodified lines258 Default: ``'http'``259 260 .. py:data:: MAX_CONTENT_LENGTH261 262- Don't read more than this many bytes from the incoming request data. If not263- set and the request does not specify a ``CONTENT_LENGTH``, no data will be264- read for security.262+ The maximum number of bytes that will be read during this request. If263+ this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge`264+ error is raised. If it is set to ``None``, no limit is enforced at the265+ Flask application level. However, if it is ``None`` and the request has no266+ ``Content-Length`` header and the WSGI server does not indicate that it267+ terminates the stream, then no data is read to avoid an infinite stream.268 269+ Each request defaults to this config. It can be set on a specific270+ :attr:`.Request.max_content_length` to apply the limit to that specific271+ view. This should be set appropriately based on an application's or view's272+ specific needs.273+274 Default: ``None``275 276+ .. versionadded:: 0.6277+278+.. py:data:: MAX_FORM_MEMORY_SIZE279+280+ The maximum size in bytes any non-file form field may be in a281+ ``multipart/form-data`` body. If this limit is exceeded, a 413282+ :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it is283+ set to ``None``, no limit is enforced at the Flask application level.284+285+ Each request defaults to this config. It can be set on a specific286+ :attr:`.Request.max_form_memory_parts` to apply the limit to that specific287+ view. This should be set appropriately based on an application's or view's288+ specific needs.289+290+ Default: ``500_000``291+292+ .. versionadded:: 3.1293+294+.. py:data:: MAX_FORM_PARTS295+296+ The maximum number of fields that may be present in a297+ ``multipart/form-data`` body. If this limit is exceeded, a 413298+ :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it299+ is set to ``None``, no limit is enforced at the Flask application level.300+301+ Each request defaults to this config. It can be set on a specific302+ :attr:`.Request.max_form_parts` to apply the limit to that specific view.303+ This should be set appropriately based on an application's or view's304+ specific needs.305+306+ Default: ``1_000``307+308+ .. versionadded:: 3.1309+310 .. py:data:: TEMPLATES_AUTO_RELOAD311 312 Reload templates when they are changed. If not set, it will be enabled in313 debug mode.466 unmodified linesmodified:docs/web-security.rst+37 added-3 removed
1 Security Considerations2 =======================3 4-Web applications usually face all kinds of security problems and it's very5-hard to get everything right. Flask tries to solve a few of these things6-for you, but there are a couple more you have to take care of yourself.4+Web applications face many types of potential security problems, and it can be5+hard to get everything right, or even to know what "right" is in general. Flask6+tries to solve a few of these things by default, but there are other parts you7+may have to take care of yourself. Many of these solutions are tradeoffs, and8+will depend on each application's specific needs and threat model. Many hosting9+platforms may take care of certain types of problems without the need for the10+Flask application to handle them.11 12+Resource Use13+------------14+15+A common category of attacks is "Denial of Service" (DoS or DDoS). This is a16+very broad category, and different variants target different layers in a17+deployed application. In general, something is done to increase how much18+processing time or memory is used to handle each request, to the point where19+there are not enough resources to handle legitimate requests.20+21+Flask provides a few configuration options to handle resource use. They can22+also be set on individual requests to customize only that request. The23+documentation for each goes into more detail.24+25+- :data:`MAX_CONTENT_LENGTH` or :attr:`.Request.max_content_length` controls26+ how much data will be read from a request. It is not set by default,27+ although it will still block truly unlimited streams unless the WSGI server28+ indicates support.29+- :data:`MAX_FORM_MEMORY_SIZE` or :attr:`.Request.max_form_memory_size`30+ controls how large any non-file ``multipart/form-data`` field can be. It is31+ set to 500kB by default.32+- :data:`MAX_FORM_PARTS` or :attr:`.Request.max_form_parts` controls how many33+ ``multipart/form-data`` fields can be parsed. It is set to 1000 by default.34+ Combined with the default `max_form_memory_size`, this means that a form35+ will occupy at most 500MB of memory.36+37+Regardless of these settings, you should also review what settings are available38+from your operating system, container deployment (Docker etc), WSGI server, HTTP39+server, and hosting platform. They typically have ways to set process resource40+limits, timeouts, and other checks regardless of how Flask is configured.41+42 .. _security-xss:43 44 Cross-Site Scripting (XSS)45 --------------------------263 unmodified linesmodified:src/flask/app.py+2 added
190 unmodified lines191 "SESSION_COOKIE_SECURE": False,192 "SESSION_COOKIE_SAMESITE": None,193 "SESSION_REFRESH_EACH_REQUEST": True,194 "MAX_CONTENT_LENGTH": None,195+ "MAX_FORM_MEMORY_SIZE": 500_000,196+ "MAX_FORM_PARTS": 1_000,197 "SEND_FILE_MAX_AGE_DEFAULT": None,198 "TRAP_BAD_REQUEST_ERRORS": None,199 "TRAP_HTTP_EXCEPTIONS": False,200 "EXPLAIN_TEMPLATE_LOADING": False,1319 unmodified linesmodified:src/flask/wrappers.py+89 added-6 removed
50 unmodified lines51 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or52 #: something similar.53 routing_exception: HTTPException | None = None54 55+ _max_content_length: int | None = None56+ _max_form_memory_size: int | None = None57+ _max_form_parts: int | None = None58+59 @property56- def max_content_length(self) -> int | None: # type: ignore[override]57- """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""58- if current_app:59- return current_app.config["MAX_CONTENT_LENGTH"] # type: ignore[no-any-return]60- else:61- return None60+ def max_content_length(self) -> int | None:61+ """The maximum number of bytes that will be read during this request. If62+ this limit is exceeded, a 413 :exc:`~werkzeug.exceptions.RequestEntityTooLarge`63+ error is raised. If it is set to ``None``, no limit is enforced at the64+ Flask application level. However, if it is ``None`` and the request has65+ no ``Content-Length`` header and the WSGI server does not indicate that66+ it terminates the stream, then no data is read to avoid an infinite67+ stream.68 69+ Each request defaults to the :data:`MAX_CONTENT_LENGTH` config, which70+ defaults to ``None``. It can be set on a specific ``request`` to apply71+ the limit to that specific view. This should be set appropriately based72+ on an application's or view's specific needs.73+74+ .. versionchanged:: 3.175+ This can be set per-request.76+77+ .. versionchanged:: 0.678+ This is configurable through Flask config.79+ """80+ if self._max_content_length is not None:81+ return self._max_content_length82+83+ if not current_app:84+ return super().max_content_length85+86+ return current_app.config["MAX_CONTENT_LENGTH"] # type: ignore[no-any-return]87+88+ @max_content_length.setter89+ def max_content_length(self, value: int | None) -> None:90+ self._max_content_length = value91+92 @property93+ def max_form_memory_size(self) -> int | None:94+ """The maximum size in bytes any non-file form field may be in a95+ ``multipart/form-data`` body. If this limit is exceeded, a 41396+ :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it97+ is set to ``None``, no limit is enforced at the Flask application level.98+99+ Each request defaults to the :data:`MAX_FORM_MEMORY_SIZE` config, which100+ defaults to ``500_000``. It can be set on a specific ``request`` to101+ apply the limit to that specific view. This should be set appropriately102+ based on an application's or view's specific needs.103+104+ .. versionchanged:: 3.1105+ This is configurable through Flask config.106+ """107+ if self._max_form_memory_size is not None:108+ return self._max_form_memory_size109+110+ if not current_app:111+ return super().max_form_memory_size112+113+ return current_app.config["MAX_FORM_MEMORY_SIZE"] # type: ignore[no-any-return]114+115+ @max_form_memory_size.setter116+ def max_form_memory_size(self, value: int | None) -> None:117+ self._max_form_memory_size = value118+119+ @property # type: ignore[override]120+ def max_form_parts(self) -> int | None:121+ """The maximum number of fields that may be present in a122+ ``multipart/form-data`` body. If this limit is exceeded, a 413123+ :exc:`~werkzeug.exceptions.RequestEntityTooLarge` error is raised. If it124+ is set to ``None``, no limit is enforced at the Flask application level.125+126+ Each request defaults to the :data:`MAX_FORM_PARTS` config, which127+ defaults to ``1_000``. It can be set on a specific ``request`` to apply128+ the limit to that specific view. This should be set appropriately based129+ on an application's or view's specific needs.130+131+ .. versionchanged:: 3.1132+ This is configurable through Flask config.133+ """134+ if self._max_form_parts is not None:135+ return self._max_form_parts136+137+ if not current_app:138+ return super().max_form_parts139+140+ return current_app.config["MAX_FORM_PARTS"] # type: ignore[no-any-return]141+142+ @max_form_parts.setter143+ def max_form_parts(self, value: int | None) -> None:144+ self._max_form_parts = value145+146+ @property147 def endpoint(self) -> str | None:148 """The endpoint that matched the request URL.149 150 This will be ``None`` if matching failed or has not been107 unmodified linesmodified:tests/test_basic.py-21 removed
1536 unmodified lines1537 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1538 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1539 1540 1541-def test_max_content_length(app, client):1542- app.config["MAX_CONTENT_LENGTH"] = 641543-1544- @app.before_request1545- def always_first():1546- flask.request.form["myfile"]1547- AssertionError()1548-1549- @app.route("/accept", methods=["POST"])1550- def accept_file():1551- flask.request.form["myfile"]1552- AssertionError()1553-1554- @app.errorhandler(413)1555- def catcher(error):1556- return "42"1557-1558- rv = client.post("/accept", data={"myfile": "foo" * 100})1559- assert rv.data == b"42"1560-1561-1541 def test_url_processors(app, client):1542 @app.url_defaults1543 def add_language_code(endpoint, values):1544 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(325 unmodified linesadded:tests/test_request.py+54 added
1+from __future__ import annotations2+3+from flask import Flask4+from flask import Request5+from flask import request6+from flask.testing import FlaskClient7+8+9+def test_max_content_length(app: Flask, client: FlaskClient) -> None:10+ app.config["MAX_CONTENT_LENGTH"] = 5011+12+ @app.post("/")13+ def index():14+ request.form["myfile"]15+ AssertionError()16+17+ @app.errorhandler(413)18+ def catcher(error):19+ return "42"20+21+ rv = client.post("/", data={"myfile": "foo" * 50})22+ assert rv.data == b"42"23+24+25+def test_limit_config(app: Flask):26+ app.config["MAX_CONTENT_LENGTH"] = 10027+ app.config["MAX_FORM_MEMORY_SIZE"] = 5028+ app.config["MAX_FORM_PARTS"] = 329+ r = Request({})30+31+ # no app context, use Werkzeug defaults32+ assert r.max_content_length is None33+ assert r.max_form_memory_size == 500_00034+ assert r.max_form_parts == 1_00035+36+ # in app context, use config37+ with app.app_context():38+ assert r.max_content_length == 10039+ assert r.max_form_memory_size == 5040+ assert r.max_form_parts == 341+42+ # regardless of app context, use override43+ r.max_content_length = 9044+ r.max_form_memory_size = 3045+ r.max_form_parts = 446+47+ assert r.max_content_length == 9048+ assert r.max_form_memory_size == 3049+ assert r.max_form_parts == 450+51+ with app.app_context():52+ assert r.max_content_length == 9053+ assert r.max_form_memory_size == 3054+ assert r.max_form_parts == 4modified:CHANGES.rst+4 added
9 unmodified lines10 responses. :pr:`5496`11 - ``Flask.open_resource``/``open_instance_resource`` and12 ``Blueprint.open_resource`` take an ``encoding`` parameter to use when13 opening in text mode. It defaults to ``utf-8``. :issue:`5504`14+- ``Request.max_content_length`` can be customized per-request instead of only15+ through the ``MAX_CONTENT_LENGTH`` config. Added16+ ``MAX_FORM_MEMORY_SIZE`` and ``MAX_FORM_PARTS`` config. Added documentation17+ about resource limits to the security page. :issue:`5625`18 19 20 Version 3.0.321 -------------1563 unmodified lines