Skip to content
Myr

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

7 files+231 added−33 removed

modified:docs/config.rst+45 added-3 removed
257 unmodified lines
258 Default: ``'http'``259260.. py:data:: MAX_CONTENT_LENGTH261262 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.268269 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.273274 Default: ``None``275276 .. versionadded:: 0.6277278.. py:data:: MAX_FORM_MEMORY_SIZE279280 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.284285 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.289290 Default: ``500_000``291292 .. versionadded:: 3.1293294.. py:data:: MAX_FORM_PARTS295296 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.300301 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.305306 Default: ``1_000``307308 .. versionadded:: 3.1309310.. py:data:: TEMPLATES_AUTO_RELOAD311312 Reload templates when they are changed. If not set, it will be enabled in313 debug mode.
466 unmodified lines
modified:docs/web-security.rst+37 added-3 removed
1Security Considerations2=======================34Web applications usually face all kinds of security problems and it's very5hard to get everything right. Flask tries to solve a few of these things6for you, but there are a couple more you have to take care of yourself.4Web applications face many types of potential security problems, and it can be5hard to get everything right, or even to know what "right" is in general. Flask6tries to solve a few of these things by default, but there are other parts you7may have to take care of yourself. Many of these solutions are tradeoffs, and8will depend on each application's specific needs and threat model. Many hosting9platforms may take care of certain types of problems without the need for the10Flask application to handle them.1112Resource Use13------------1415A common category of attacks is "Denial of Service" (DoS or DDoS). This is a16very broad category, and different variants target different layers in a17deployed application. In general, something is done to increase how much18processing time or memory is used to handle each request, to the point where19there are not enough resources to handle legitimate requests.2021Flask provides a few configuration options to handle resource use. They can22also be set on individual requests to customize only that request. The23documentation for each goes into more detail.2425- :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.3637Regardless of these settings, you should also review what settings are available38from your operating system, container deployment (Docker etc), WSGI server, HTTP39server, and hosting platform. They typically have ways to set process resource40limits, timeouts, and other checks regardless of how Flask is configured.4142.. _security-xss:4344Cross-Site Scripting (XSS)45--------------------------
263 unmodified lines
modified:src/flask/app.py+2 added
190 unmodified lines
191 "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 lines
modified:src/flask/wrappers.py+89 added-6 removed
50 unmodified lines
51 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or52 #: something similar.53 routing_exception: HTTPException | None = None5455 _max_content_length: int | None = None56 _max_form_memory_size: int | None = None57 _max_form_parts: int | None = None5859 @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.6869 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.7374 .. versionchanged:: 3.175 This can be set per-request.7677 .. versionchanged:: 0.678 This is configurable through Flask config.79 """80 if self._max_content_length is not None:81 return self._max_content_length8283 if not current_app:84 return super().max_content_length8586 return current_app.config["MAX_CONTENT_LENGTH"] # type: ignore[no-any-return]8788 @max_content_length.setter89 def max_content_length(self, value: int | None) -> None:90 self._max_content_length = value9192 @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.9899 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.103104 .. 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_size109110 if not current_app:111 return super().max_form_memory_size112113 return current_app.config["MAX_FORM_MEMORY_SIZE"] # type: ignore[no-any-return]114115 @max_form_memory_size.setter116 def max_form_memory_size(self, value: int | None) -> None:117 self._max_form_memory_size = value118119 @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.125126 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.130131 .. versionchanged:: 3.1132 This is configurable through Flask config.133 """134 if self._max_form_parts is not None:135 return self._max_form_parts136137 if not current_app:138 return super().max_form_parts139140 return current_app.config["MAX_FORM_PARTS"] # type: ignore[no-any-return]141142 @max_form_parts.setter143 def max_form_parts(self, value: int | None) -> None:144 self._max_form_parts = value145146 @property147 def endpoint(self) -> str | None:148 """The endpoint that matched the request URL.149150 This will be ``None`` if matching failed or has not been
107 unmodified lines
modified:tests/test_basic.py-21 removed
1536 unmodified lines
1537 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1538 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)153915401541def test_max_content_length(app, client):1542 app.config["MAX_CONTENT_LENGTH"] = 6415431544 @app.before_request1545 def always_first():1546 flask.request.form["myfile"]1547 AssertionError()15481549 @app.route("/accept", methods=["POST"])1550 def accept_file():1551 flask.request.form["myfile"]1552 AssertionError()15531554 @app.errorhandler(413)1555 def catcher(error):1556 return "42"15571558 rv = client.post("/accept", data={"myfile": "foo" * 100})1559 assert rv.data == b"42"156015611541def 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 lines
added:tests/test_request.py+54 added
1from __future__ import annotations23from flask import Flask4from flask import Request5from flask import request6from flask.testing import FlaskClient789def test_max_content_length(app: Flask, client: FlaskClient) -> None:10 app.config["MAX_CONTENT_LENGTH"] = 501112 @app.post("/")13 def index():14 request.form["myfile"]15 AssertionError()1617 @app.errorhandler(413)18 def catcher(error):19 return "42"2021 rv = client.post("/", data={"myfile": "foo" * 50})22 assert rv.data == b"42"232425def 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({})3031 # 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_0003536 # 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 == 34142 # regardless of app context, use override43 r.max_content_length = 9044 r.max_form_memory_size = 3045 r.max_form_parts = 44647 assert r.max_content_length == 9048 assert r.max_form_memory_size == 3049 assert r.max_form_parts == 45051 with app.app_context():52 assert r.max_content_length == 9053 assert r.max_form_memory_size == 3054 assert r.max_form_parts == 4
modified:CHANGES.rst+4 added
9 unmodified lines
10 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`181920Version 3.0.321-------------
1563 unmodified lines